var Site = {
	init : function() {
		/*if ($('#default-index-index').size()) {
			$(window).load(function() {
				Site.Default.init();
			});
		}	
		if ($('#default-index-search').size()) {
			Site.Default.search();
			$('.filter:eq(1) h4, .filter:eq(2) h4').trigger('click');
		}	
		if ($('#default-index-view').size()) {
			Site.Default.view();
		}	
		if ($('#default-index-view').size()) {
			Site.Default.view();
		}	
		*/
		/*if ($('#default-index-about').size()) {
			$(window).load(function() {
				Site.Default.about();
			});
		}	*/

		/*if ($('#contact-index-index').size()) {
			$(window).load(function() {
				Site.Contact.init();
			});
		}*/
		
		/* CSS3 pour IE */
		if (window.PIE) {
			$('.shadow').each(function() {
				PIE.attach(this);
			});
		}
		
		var body = $('body:first');
		var pageid = body.attr('id');
	
		switch (pageid) {
			case 'annonce-annonces-search':
				Site.Annonces.search();
				break;
			case 'annonce-annonces-view':
				Site.Annonces.view();
				break;
			case 'contact-index-index': case 'contact-index-request':
				Site.Contact.init();
				break;
		}
	}
};

Site.Default = {
	init : function() {
		if($('.grid .element').size() >= '3') {
			$('.grid > div:nth-child(1), .grid > div:nth-child(2), .grid > div:nth-child(3)').equalHeightColumns();
		}
		if($('.grid .element').size() == '6') {
			$('.grid > div:nth-child(4), .grid > div:nth-child(5), .grid > div:nth-child(6)').equalHeightColumns();
		}
	},
	about : function() {
		$('.grid .element').equalHeightColumns();
	},
	search : function() {
		$('#filters h4 span').hide();
		$('#filters h4').bind('click', function() {
			$(this).toggleClass('active');
			$('span', this).toggle('fast');
			$(this).next().toggle('slow');
			return false;
		}).next().hide();
	},
	view : function() {
		var gallery = $('#thumbs').galleriffic({
			delay:                     3000, // in milliseconds
			numThumbs:                 6, // The number of thumbnails to show page
			preloadAhead:              40, // Set to -1 to preload all images
			enableTopPager:            false,
			enableBottomPager:         true,
			maxPagesToShow:            7,  // The maximum number of pages to display in either the top or bottom pager
			imageContainerSel:         '#slideshow',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading',
			renderSSControls:          true, // Specifies whether the slideshow's Play and Pause links should be rendered
			renderNavControls:         false, // Specifies whether the slideshow's Next and Previous links should be rendered
			playLinkText:              'Start Diashow',
			pauseLinkText:             'Stop Diashow',
			prevLinkText:              'Previous',
			nextLinkText:              'Next',
			nextPageLinkText:          'Next &rsaquo;',
			prevPageLinkText:          '&lsaquo; Prev',
			enableHistory:             false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
			enableKeyboardNavigation:  true, // Specifies whether keyboard navigation is enabled
			autoStart:                 false, // Specifies whether the slideshow should be playing or paused when the page first loads
			syncTransitions:           false, // Specifies whether the out and in transitions occur simultaneously or distinctly
			defaultTransitionDuration: 1000, // If using the default transitions, specifies the duration of the transitions
			onSlideChange:             undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
			onTransitionOut:           undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... }
			onTransitionIn:            undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... }
			onPageTransitionOut:       undefined, // accepts a delegate like such: function(callback) { ... }
			onPageTransitionIn:        undefined, // accepts a delegate like such: function() { ... }
			onImageAdded:              undefined, // accepts a delegate like such: function(imageData, $li) { ... }
			onImageRemoved:            undefined  // accepts a delegate like such: function(imageData, $li) { ... }
		});	
	}
};

Site.Contact = {
	init : function() {
		if($('.grid .element').size()) {
			$('.grid .element').equalHeightColumns();
		}
		
		$('input[title], textarea[title]').each(function() {
			var $this = $(this);
			if($this.val() === '') {
				$this.val(this.title); 
			}
			
			$this.focus(function() {
				if($this.val() === this.title) {
					$this.val(''); 
				}
			});
			
			$this.blur(function() {
				if($this.val() === '') {
					$this.val(this.title); 
				}
			});
		});	
	}
};


Site.Annonces = {
	checkbox: null,
	
	search: function() {
		var self = this;
		
		self.checkbox = $('input[type=checkbox]');
		
		// Filters click
		$('#filters h4').bind('click', function() {
			$(this).toggleClass('active');
			$('span', this).toggle('fast');
			$(this).next().toggle('slow');
			
			return false;
		}).next().hide();
		
		// Clear click
		var span = $('#filters h4 span');
		span.hide();
		span.each(function() {
			// Span courant
			var current = $(this);
			
			current.click(function(e) {
				// Stop l'event click du h4
				e.stopPropagation();

				// Class du span cliqué
				var spanClass = current.attr('class');

				// Checkbox de la liste ayant la même classe
				var checkboxs = $('ul.' + spanClass + ' li input[type=checkbox]');

				// Uncheck des checkbox
				checkboxs.attr('checked', false);
				
				// Recherche
				self.submitForm();
			});
		});
		
		// Location déplié par défaut
		$('span.filter-location').parent().trigger('click');
		
		// Other locations click
		/*var moreLocationsLink = $('#more-locations-link');
		var moreLocationsList = $('#more-locations-list');
		
		if (moreLocationsLink) {
			moreLocationsList.hide();
			
			moreLocationsLink.click(function() {
				moreLocationsList.toggle('slow');
				moreLocationsLink.toggle('slow');
				return false;
			});
		}*/
		
		// Checkbox click
		self.checkbox.each(function() {
			var current = $(this);
			
			current.click(function() {
				self.submitForm();
			});
		});
		
		// Recherche sans critère
		self.submitForm();
	},
	
	submitForm: function() {
		var self = this;
		
		var formValues = $('#filters').serialize();

		$.ajax({
			url: BASE_URL + 'annonce/annonces/ajaxsearch',
			data: formValues,
			type: 'post',
			success: function(response) {
				var content = $('#content');
				
				content.fadeOut('fast', function() {
					content.html(response);
					self.detailFilters();
					content.fadeIn();
				});
			}
		});
	},
	
	detailFilters: function() {
		var self = this;

		var filters = ['transaction', 'location', 'property'];
		for (filter in filters) {
			// Checkbox qui ont un name commençant par le filtre
			$(self.checkbox + '[name^=' + filters[filter] + ']').each(function() {
				var current = $(this);

				// Nombre d'éléments trouvés
				var nb = $('div.' + filters[filter] + '_' + current.val()).length;

				if (0 < nb) {
					current.next('span').text(' (' + nb + ')');
				} else {
					current.next('span').text('');
				}
			});
		}
		

		filters = ['price', 'area', 'bedroom'];
		
		$(self.checkbox + '[name^=price]').next('span').text('');
		$(self.checkbox + '[name^=area]').next('span').text('');
		$(self.checkbox + '[name^=bedroom]').next('span').text('');
		
		$('#content .element:nth-child(2n+1)').css('clear','both');

		$('#content div.element').each(function() {
			var currentDiv = $(this);

			for (filter in filters) {
				// Checkbox qui ont un name commençant par le filtre
				$(self.checkbox + '[name^=' + filters[filter] + ']').each(function() {
					var currentChk = $(this);
					
					// Valeurs du filtre en cours
					var filterValue	= currentChk.val().split('_');
					filterValue[0] = parseInt(filterValue[0]);
					if (2 == filterValue.length) filterValue[1] = parseInt(filterValue[1]);
					
					// Valeur du filtre du produit
					var productTxt		= currentDiv.find('span.' + filters[filter]).text()
					var productValue	= ((isNaN(parseInt(productTxt))) ? 0 : parseInt(productTxt));
					
					// Nombre de produits concernés
					var spanInfo		= currentChk.next('span');
					var spanTxt			= spanInfo.text().replace('(', '').replace(')', '');
					var spanInfoValue	= ((isNaN(parseInt(spanTxt))) ? 0 : parseInt(spanTxt));
					
					// Si la valeur est supérieur à 0 (évite les prix à NULL)
					if (0 < productValue) {
						spanInfoValue += 1;
						var txt = '(' + spanInfoValue + ')';
						
						// Si le filtre a 1 ou 2 valeurs (Typiquement "x à y" ou "x +")
						if (2 == filterValue.length) {
							if (productValue >= filterValue[0] && productValue <= filterValue[1]) {
								spanInfo.text(txt);
							}
						} else {
							if (productValue >= filterValue[0]) {
								spanInfo.text(txt);
							}
						}
					}
				});
			}
		});
	},
	
	view: function() {
		$('#tabs-2 .two-columns').equalHeightColumns();
		$('#tabs-3 .two-columns').equalHeightColumns();
		$("#description").tabs();
		// Récupération des termes à afficher en ajax
		// puis mise en place de la gallerie
		$.ajax({
			url: BASE_URL + 'annonce/annonces/galleryterms',
			dataType: 'json',
			success: function(terms) {
				$('#thumbs').galleriffic({
					delay:                     3000, // in milliseconds
					numThumbs:                 6, // The number of thumbnails to show page
					preloadAhead:              40, // Set to -1 to preload all images
					enableTopPager:            false,
					enableBottomPager:         true,
					maxPagesToShow:            7,  // The maximum number of pages to display in either the top or bottom pager
					imageContainerSel:         '#slideshow',
					controlsContainerSel:      '#controls',
					captionContainerSel:       '#caption',
					loadingContainerSel:       '#loading',
					renderSSControls:          true, // Specifies whether the slideshow's Play and Pause links should be rendered
					renderNavControls:         false, // Specifies whether the slideshow's Next and Previous links should be rendered
					playLinkText:              terms.play,
					pauseLinkText:             terms.pause,
					prevLinkText:              terms.previous,
					nextLinkText:              terms.next,
					nextPageLinkText:          terms.nextM + ' &rsaquo;',
					prevPageLinkText:          '&lsaquo; ' + terms.previousM,
					enableHistory:             false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
					enableKeyboardNavigation:  true, // Specifies whether keyboard navigation is enabled
					autoStart:                 false, // Specifies whether the slideshow should be playing or paused when the page first loads
					syncTransitions:           false, // Specifies whether the out and in transitions occur simultaneously or distinctly
					defaultTransitionDuration: 1000, // If using the default transitions, specifies the duration of the transitions
					onSlideChange:             undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
					onTransitionOut:           undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... }
					onTransitionIn:            undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... }
					onPageTransitionOut:       undefined, // accepts a delegate like such: function(callback) { ... }
					onPageTransitionIn:        undefined, // accepts a delegate like such: function() { ... }
					onImageAdded:              undefined, // accepts a delegate like such: function(imageData, $li) { ... }
					onImageRemoved:            undefined  // accepts a delegate like such: function(imageData, $li) { ... }
				});
			}
		});
	}
};

$(Site.init);
