var ajaxNavigation = false;

$(document).ready( function() {

	if( typeof(ajaxRedirection)!='undefined' && ajaxRedirection==true )
		return;
	
	if(  ! cdtRegistry.IE6 ) _initCategoriesList();
	
	_triggerCatergoriesDescriptionsMouseBehaviour();
	
	if(  ! cdtRegistry.IE6 ) _initOpenedSubCat();
	
	_handleGroupsVisibilityOnGoogleMap();

	_removeBottomLinksLastSeparatorIfNeeded();

	_initMySelectionModificationButtons();
	
} );



function addGoogleMapButton( aAnnonceId, aAction ) {

	var geolocalizationLink;

	if( aAnnonceId==null )
		geolocalizationLink = $('.geolocalizationLink');
	else
		geolocalizationLink = $('#geolocalizationLink_'+aAnnonceId);
		
	geolocalizationLink.attr( 'href', 'javascript:'+aAction );
	
}


function _initCategoriesList() {
	
	$('#categoriesList .categoryBlock h3').each( function() {

		var $me, $myLink;

		$me = $(this);

		if( $me.hasClass('disabled') )
			return;
		if( $me.hasClass('noAjax') )
			return;
		
		if( $me.hasClass('opened') || $me.parents('#aLaUneBlock').length==1 ) {

			// jQuery simple open/close behaviour

			$me.html('<a href="javascript:;">'+$me.html()+'</a>');
			
			if(  ! cdtRegistry.IE6 ) {
				$me.click( _onOpenedCategoryTitleClicked );
				$me.css( 'cursor', 'pointer' );
			} else {
				myLink = $me.find('a');
				myLink.click( _onOpenedCategoryTitleClicked );
			}

		} else {

			// click on H3=click on inner <A>

			if(  ! cdtRegistry.IE6 ) {
				$me.click( _onCategoryBlockTitleClicked );
				$me.css( 'cursor', 'pointer' );
			} else {
				$myLink = $me.find('a');
				$myLink.click( _onCategoryBlockTitleClicked );
			}

		}

		if( typeof($myLink)!='undefined' && $myLink.length>0 ) {
			$myLink.css('display', 'block');
			$myLink.css('width', '540px');
		}
		
	} );
	
}


function _triggerCatergoriesDescriptionsMouseBehaviour() {

	var $descriptions;

	$descriptions = $('#categoriesList .categoryBlock H3 .description');

	$descriptions.hide();
	
	$descriptions.parents('H3').hover(
		function() {
			$(this).find('.description').show();
		},
		function() {
			$(this).find('.description').hide();
		}
	);

}

function _initOpenedSubCat() {

	var openedSubCatTitle;

	openedSubCatTitle = $('.subCatTitleOpened');

	if( openedSubCatTitle.length==0 )
		return;

	openedSubCatTitle.click( _onOpenedSubCatTitleClicked );
	openedSubCatTitle.css('cursor', 'pointer');

}

function _handleGroupsVisibilityOnGoogleMap() {

	if( typeof(ajaxCategory)=='undefined' )
		return;
	
	var cat = ajaxCategory;

	if (ajaxCategory == "hebergements" && typeof(ajaxSubCat)!='undefined')
		cat = ajaxSubCat;

	if( typeof(gMapMarkersReady)!='undefined' && gMapMarkersReady ) {
		if (cat == "hebergements")
			maskGroupsButArray( ['hotels','locations','chambres_d_hotes','campings', 'hebergements'] );
		else if (cat == "auberges_de_jeunesse" || cat == "residences_et_villages_vacances")
			maskGroupsButOne( "hebergements" );
		else if (cat == "gitesDeFrance")
			maskGroupsButArray( ['locations','chambres_d_hotes'] );
		else
			maskGroupsButOne( cat.replace("-","_") );
	} else {
		setTimeout('_handleGroupsVisibilityOnGoogleMap();', 1000 );
	}

}


function _onOpenedCategoryTitleClicked(event) {

	event.preventDefault();

	var $myTitle, $myContent, isVisible;
	var $myIntro;

	$myTitle = ( ! cdtRegistry.IE6 ) ? $(this) : $(this).parent();
	
	$myIntro = $myTitle.parent().find('.categoryIntro');
	$myContent = $myTitle.parent().find('.subCatsList');

	if( $myContent.length==0 ) {
		// Ok, it seems we have no subcats : let's try with 'annoncesListContainer'
		$myContent = $myTitle.parent().find('.annoncesListContainer');
	}

	if( $myContent.length==0 ) {
		return false;//Caramba, encore rate !
	}

	isVisible = ($myContent.css('display')=='none') ? false : true ;
	if( isVisible ) {
		
		$myIntro.hide();
		
		// Hide !
		if( ! cdtRegistry.IE6 )
			$myContent.slideUp( {duration: 400, easing: 'easeOutQuint'} );
		else
			$myContent.hide();

		$myTitle.addClass('closed');
		$myTitle.removeClass('opened');
		
	} else {

		// Show !
		if( ! cdtRegistry.IE6 )
			$myContent.slideDown( {duration: 600, easing: 'easeOutQuint'} );
		else
			$myContent.show();

		$myIntro.show();
		
		$myTitle.addClass('opened');$myTitle.removeClass('closed');

		if( $myTitle.find('.minusContainer').length==0 )
			$myTitle.html('<span class="minusContainer">' + $myTitle.html() + '</span>');

		// Let's close any opened category
		$('#categoriesList .categoryBlock h3.opened').parent().each( function() {
			var $currentMe = $(this);
			var $currentTitle = $currentMe.find('H3');
			if( $currentTitle.get(0)==$currentTitle.get(0) )
				return;//we don't close ourself
			var $currentContent = $currentMe.find('.annoncesListContainer, .subCatsList');
			$currentTitle.removeClass('opened');$currentTitle.addClass('closed');
			$currentContent.hide();
		} );


		// GMap update
		if( $myTitle.parents('#aLaUneBlock').length==1 )
			return;//no GMap update for "A la Une" pseudo category block
		
		var $myAnchor = $myTitle.parents('.categoryBlock').find('a:first');
		if( $myAnchor.length==1 && $myAnchor.attr('name').length>0 )
			maskGroupsButOne( $myAnchor.attr('name') );

	}
	return false;
	
}


function _onOpenedSubCatTitleClicked() {

	var $myTitle, $myContent, isVisible;
	var $myAnnoncesListContainer;

	$myTitle = $(this);
	$myContent = $myTitle.parent().find('.subCatBlockContent');
	isVisible = ($myContent.css('display')=='none') ? false : true ;

	if( isVisible ) {

		// Hide !
		if( ! cdtRegistry.IE6 )
			$myContent.slideUp( {duration: 400, easing: 'easeOutQuint'} );
		else
			$myContent.hide();

		$myTitle.addClass('subCatTitleClosed');$myTitle.removeClass('subCatTitleOpened');

	} else {

		// Show !
		//
		// If we have a #annoncesListContainer, we have to be sure it is displayed
		$myAnnoncesListContainer = $myContent.find('.annoncesListContainer');
		if( $myAnnoncesListContainer.length==1 && $myAnnoncesListContainer.css('display')=='none' )
			$myAnnoncesListContainer.css('display', 'block');
		
		if( ! cdtRegistry.IE6 )
			$myContent.slideDown( {duration: 600, easing: 'easeOutQuint'} );
		else
			$myContent.show();

		$myTitle.addClass('subCatTitleOpened');$myTitle.removeClass('subCatTitleClosed');

		// Let's close any opened subCat
		$('.subCatTitleOpened').parent().each( function() {
			var $me = $(this);
			var $myLocalTitle = $me.find('.subCatTitleOpened');
			if( $myLocalTitle.get(0)==$myTitle.get(0) )
				return;//we don't close ourself
			var $myLocalContent = $me.find('.subCatBlockContent');
			$myLocalTitle.removeClass('subCatTitleOpened');$myLocalTitle.addClass('subCatTitleClosed');
			$myLocalContent.hide();
		} );

	}

}


function _initGMapBox() {

	var $mapBlock;
	var $mapButton, $mapButtonImg;

	$mapBlock = $('.darkblock');

	$mapButton = $('A#carteButton');
	$mapButtonImg = $mapButton.find('IMG');

	$mapButton.click(function () {

		if ( $mapBlock.css('position') == 'absolute') {

			// Let's show the map !'

			$mapBlock.css( {position: 'static', visibility: 'visible', padding: '3px 10px 5px 5px' } );
			$mapBlock.css( {height: '458px'} );
			
			if( ! cdtRegistry.IE6 )
				$mapBlock.fadeIn(400);//$mapBlock.animate({height: '458px'}, 400 );

			$mapButtonImg.attr('src', cdtRegistry.baseUrl + 'images/header/' + cdtRegistry.lang.substr(0, 2) + '/gmap_on.gif');

		} else {

			// Ok, now let's hide it...

			if( cdtRegistry.IE6 ) {
				$mapBlock.css( {height: '0px', visibility: 'hidden', position: 'absolute'} );
			} else {
				$mapBlock.fadeOut(300);//$mapBlock.animate({height: '0px'}, 300 );
				setTimeout("$('.darkblock').css( {position: 'absolute', visibility: 'hidden', padding: '0'} );", 310);
			}

			$mapButtonImg.attr('src', cdtRegistry.baseUrl + 'images/header/' + cdtRegistry.lang.substr(0, 2) + '/gmap_off.gif');

		}

		return false;

	});
	
}


function _removeBottomLinksLastSeparatorIfNeeded() {

	var bottomLinksContainer;

	bottomLinksContainer = $('.bottomLinksContainer');
	bottomLinksContainer.each( function() {

		var visibleChildren = $(this).children(':visible');

		if( visibleChildren.length==0 )
			return;

		var lastVisibleChild = visibleChildren.eq( visibleChildren.length-1 );

		var separator = lastVisibleChild.find('.bord');
		
		if( separator.length==1 )
			separator.remove();

	} );
	
}

function _onCategoryBlockTitleClicked(event) {
	
	event.preventDefault();
	
	var myLink;
	
	var me = $(this);
	
	myLink = me.find('a');

	location.href = myLink.attr( 'href' );
	
}



function _initMySelectionModificationButtons() {

	var $targetLinks;
	
	$targetLinks = $('A.removeFromBasketButton, A.addToBasketButton');

	$targetLinks.each( function() {
		var $me = $(this);
		if( $me.attr('href')=='javascript:;')
			return;//already handled
		$me.attr('href', 'javascript:;');
		$me.click( _onMySelectionModification );
	});

}


function _onMySelectionModification() {

	var me, myId, operationCode, myAnnonceIdArray, myAnnonceId;

	me = $(this);

	if( me.hasClass( 'ajaxLoader' ) )
		return;
	
	myId = me.attr('id');
	operationCode = (me.hasClass('addToBasketButton')) ? 'addition' : 'removal' ;
	myAnnonceIdArray = myId.split('_');
	myAnnonceId = myAnnonceIdArray[1];

	me.addClass( 'ajaxLoader' );
	me.blur();
	
	sendMySelectionModification( operationCode, [ myAnnonceId ] );

	return false;

}


function sendMySelectionModification( aOperationCode/*String*/, aAnnoncesIdsArray/*Array*/, aCallbackFunction /*Function*/ ) {

	var i/*integer*/;
	var operationVarName/*String*/, varsToSendStr/*String*/;
	var currentAnnonceId/*integer*/;

	if( aOperationCode!='addition' && aOperationCode!='removal' )
		return;

	if( ! (aAnnoncesIdsArray instanceof Array) )
		return;

	operationVarName = (aOperationCode=='addition') ? 'mySelectionAddition' : 'mySelectionRemoval' ;
	varsToSendStr = '';
	for( i=0;i<aAnnoncesIdsArray.length;i++ ) {

		currentAnnonceId = aAnnoncesIdsArray[i];
		if( isNaN(currentAnnonceId) )
			continue;

		varsToSendStr += operationVarName+'[]='+currentAnnonceId+'&';

	}

	if( varsToSendStr=='' )
		return;

	// Go! Go! Go!
	$.ajax( {
		type: 'POST',
		url: cdtRegistry.mySelectionModUrl,
		data: varsToSendStr,
		dataType: 'json',
		success: function( aReturnObject ) {
			if( typeof(aCallbackFunction)!='undefined' && (aCallbackFunction instanceof Function) )
				aCallbackFunction();
			_onMySelectionModificationSuccess( aReturnObject );
		},
		error: _onMySelectionModificationError
	} );

}

function _onMySelectionModificationSuccess( aReturnObject ) {

	var success/*boolean*/, modifiedAnnoncesIds/*Array*/;
	var i/*integer*/, currentModifiedAnnonceId/*integer*/;
	var $currentModifiedAnnonceLink/*jQuery Element*/, $currentModifiedAnnonceLinkSpan/*jQuery Element*/;

	success = aReturnObject.success;

	$('.ajaxLoader').removeClass('ajaxLoader');
	
	if( ! success ) {
		alert('Error. Please retry');
		return;
	}
	
	modifiedAnnoncesIds = aReturnObject.modifiedAnnoncesIds;
	for( i=0; i<modifiedAnnoncesIds.length; i++) {

		currentModifiedAnnonceId = modifiedAnnoncesIds[ i ];

		$currentModifiedAnnonceLink = $('#basketLink_'+currentModifiedAnnonceId);
		$currentModifiedAnnonceLinkSpan = $currentModifiedAnnonceLink.find('span');

		if( $currentModifiedAnnonceLink.hasClass('addToBasketButton') ) {

			$currentModifiedAnnonceLinkSpan.html( cdtRegistry.i18n.gdv.removeFromBasketButtonText );
			$currentModifiedAnnonceLink.addClass('removeFromBasketButton');$currentModifiedAnnonceLink.removeClass('addToBasketButton');

			$currentModifiedAnnonceLink.removeAttr('onclick');//GA tracking removal
			
		} else {

			$currentModifiedAnnonceLinkSpan.html( cdtRegistry.i18n.gdv.addToBasketButtonText );
			$currentModifiedAnnonceLink.addClass('addToBasketButton');$currentModifiedAnnonceLink.removeClass('removeFromBasketButton');

		}

	}

	_onMySelectionUpdate( aReturnObject );
	
}


function _onMySelectionUpdate( aReturnObject ) {

	// Num annonces in "carnet de voyage" display update
	$('#mySelectionLink .num').text( aReturnObject.mySelectionAnnoncesIds.length );

}


function _onMySelectionModificationError( aXMLHttpRequest, aTextStatus, aErrorThrown) {



}

function _onFilterBlockTitleClicked() {
			
	var clickedH4, clickedFilterBlock, h4linkedContent, h4linkedContentIsVisible;
	
	clickedH4 = $(this);
	clickedFilterBlock = clickedH4.parent();
	h4linkedContent = clickedFilterBlock.find('.content');
	h4linkedContentIsVisible = (h4linkedContent.css('display')=='none') ? false : true ;
	
	
	if( h4linkedContentIsVisible ) {
		
		// Hide !
		h4linkedContent.hide( 50 );//100 = fast/4
		clickedH4.addClass('closed');clickedH4.removeClass('opened');
		
	} else {
		
		// Show !
		h4linkedContent.show( 100 );//100 = fast/2
		clickedH4.addClass('opened');clickedH4.removeClass('closed');
		
	}
	
}


// ------------------------------------------------------------------
// Specific case of empty restaurants list with a requested city
// ------------------------------------------------------------------

$(document).ready( function() {
	$('#seeTourismOfficeForRestaurantsLink').parents('H3').click( _onCityHasNoRestaurantSpecificLinkClicked );
} );

function _onCityHasNoRestaurantSpecificLinkClicked()
{

	var $clickedTitle;
	var $targetBlock, targetBlockIsVisible;
	
	//console.log('_onCityHasNoRestaurantSpecificLinkClicked()');
	
	$clickedTitle = $(this);
	$targetBlock = $('#seeTourismOfficeForRestaurants');
	
	targetBlockIsVisible = ($targetBlock.css('display')=='none') ? false : true ;
	
	if( targetBlockIsVisible ) {
		
		//console.log('hide()');
		
		// Hide !
		$targetBlock.hide( 50 );//100 = fast/4
		$clickedTitle.addClass('closed');$clickedTitle.removeClass('opened');
		
	} else {
		
		//console.log('show()');
		
		// Let's close any opened category
		$('#categoriesList .categoryBlock h3.opened').parent().each( function() {
			var $me = $(this);
			var $myTitle = $me.find('h3');
			var $myContent = $me.find('.annoncesListContainer, .subCatsList');
			$myTitle.removeClass('opened');$myTitle.addClass('closed');
			$myContent.hide();
		} );
				
		// Show !
		$targetBlock.show( 100 );//100 = fast/2
		$clickedTitle.addClass('opened');$clickedTitle.removeClass('closed');
		
	}	
	
	return false;
	
}
