/**
 * @author Airzebeth
 */
$(document).ready(function (event) {
	
	$('body').removeClass('nojs');
	
	$('#words').attr('title', $('#words').val());
	$('#words').focus(function() {
		if ($(this).attr('title') == $(this).val()) {
			$(this).val('');
		}
	});
	$('#words').blur(function() {
		if ($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
	});
	
	$('#index .actualite > ul > li > a').removeAttr('href');
	$('#index .actualite > ul > li > a').click(function() {
		
		$('#index .actualite > ul > li > div').fadeOut('slow');
		$(this).parent().children('div').fadeIn('slow', function() {
		
			$('#index .actualite > ul > li').removeClass('on');
			$(this).parent().addClass('on');
		});
	});
	
	//$('#index #partenaires').bxSlider({displaySlideQty:7, moveSlideQty:3});
	
	$('.slider ul').each(function() {
		if($(this).children('li').length > 1) {
			$('.slider ul').bxSlider({auto: true});
		} 
	});
	
	
	$('.tabs-content ul').each(function() {
		$(this).bxSlider({pager: true, infiniteLoop: false, controls: false});
	});
	
	$('.tabs .bx-pager').each(function() {
		$(this).wrap('<div class="bx-pager-out"></div>');
	});
	
	$('.tabs h4').click(function() {
		
		//$('#index .annonces > ul > li > .tabs-content').fadeOut('fast');
		$(this).parents('.tabs').find('.tabs-content').fadeOut('fast');
		//$('#index .annonces > ul > li').css('z-index', '');
		$(this).parents('.tabs').children().css('z-index', '');
		
		$(this).next('.tabs-content').fadeIn('fast');
		$(this).parent().css('z-index', '11');
	});
	
	
	// Commander
	$('#commander.list #main, #commander.invoice #main').submit(function(event) { 
		return false;});
	$('#commander.list form#main input[type=submit]').click(function() { 
		if ($(this).hasClass('on')) {
			$(this).removeClass('on');
		} else {
			$(this).addClass('on');
		}
	});
	$('#commander .back a').removeAttr('href').click(function() {
		var list = Array();
		$('#commander input[type=submit]').each(function() { 
			if($(this).hasClass('on')) {
				var h = $(this).attr('id').split('_');
				list.push(h[1]);
			}
		});
		$('#commanderCart').val(list.join(';'));
		if(list.length == 0) {
			alert('Vous devez sélectionner votre édition pour pouvoir éditer votre bon de commande.');
		} else {
			$('#main').attr('action', $('#main').attr('action') + '?action=order');
			$('#main').unbind('submit');
			$('#main').submit();
		}
	});	
	$('#print-button').click(function() {
		window.print();
	});
	
	// Index
	
	$('#typesearch-geo').parent().nextAll('map').find('area').each(function() {
		$(this).attr('rel',$(this).attr('href'));
		if($('#typesearch-geo').val() == '') {
			$(this).removeAttr('href');
		} 
	});
	
	$('#typesearch-geo').parent().nextAll('map').find('area').click(function() {
		if($('#typesearch-geo').val() == '') {
			alert('Vous devez sélectionner le type de ' + ($('body.annonce').length > 0 ? 'projet' : 'professionnel') + ' avant de choisir une région.');
		} else {
			var href = $(this).attr('rel').split('?');
			if(href.length > 1) {
				var arg = href[1].split('&');
				newArg = '';
				$.each(arg, function(key,elem) {
					if(elem.indexOf('region') != -1) {
						newArg +='&'+elem;
					}
				});
			} else {
				newArg = '';
			}
			var regionId = $(this).attr('id').substr(5);
			ECOG_goToFullUrl(href[0] + '?typesearch=' + $('#typesearch-geo').val()+'&submit=1&region=' + regionId + newArg);
		}
	});
	
	$().UItoTop({ easingType: 'easeOutQuart',text:'Haut de page', scrollSpeed: 1000 });
	
	// FB like
var root = $('base').attr('href');
		var locationH = document.location.href.replace('http://','').split('/');
		locationH[0] = 'http://' + locationH[0];
		if(locationH[0] != root) {
			root = locationH[0];
		}
		
	$('.dd.toToken').each(function() {
		
		ddId = $(this).attr('id');
		sel = Array();
		$(this).find('input[type=checkbox]:checked').each(function() {
			arr = {};
			arr.id = $(this).val();
			arr.name = $(this).next('label').text();
			sel.push(arr);
		});
		$(this).replaceWith('<div class="token-wrapper"><input type="text" name="'+ddId +'" id="'+ddId +'"></div>');
		//
		$("#"+ddId).tokenInput(root + '/param/ajax/regions.php'+(ddId=='region_maison'? '?limit=1' :''), {
					theme: "facebook",
					  prePopulate: sel,
					  hintText:'Saisissez le premier caractère de votre localisation...',
					  noResultsText:'Aucun résultat',
					  searchingText:'Recherche en cours...',
					animateDropdown:false,
					resultsFormatter: function(item){ return "<li>" + item.name + ", <em>" + item.cname + "</em></li>" },
				  tokenFormatter: function(item) { return "<li>" + item.name + "</li>" }
				});
	});

		// Search field
		$('#keysearch-text').attr('title', $('#keysearch-text').attr('value'));
		$('#keysearch-text').focus(function() {
				if($('#keysearch-text').val() == $('#keysearch-text').attr('title')) {
						$('#keysearch-text').val('');
				}
		});
		$('#keysearch-text').blur(function() {
				if($('#keysearch-text').val() == '') {
						$('#keysearch-text').val($('#keysearch-text').attr('title'));
				}
		});
	
	/*$('.dropdown').css('display','block');
	var selH = Array('region_top','region_investir','region','region_maison','promoteur','constructeur', 'lotisseur');
	$.each(selH, function(index,value) {
	
		if($("select#"+value).length > 0) {
			$("select#"+value).multiSelect({ selectAll:false, noneSelected: 'Sélectionnez', oneOrMoreSelected: '*' }, function() {
				cleanSel("#"+value);
		
			});
			cleanSel("#"+value);
		}
	});
	$('.dropdown').removeAttr('style');*/
	
	if($('p.criteria').length > 0 && $('div.criteria.show').length == 0) {

		$('p.criteria a').removeAttr('href');
		$('div.criteria #submit').hide();
		$('p.criteria a').toggle(function()  {
			$('div.criteria').animate({'height':'180px'}, {duration:300});
			$(this).html('X').parent().css('margin',0);
			$('p.criteria').before('<p class="back search relaunch" style="float:right;margin:0 30px 0 0;clear:none"><a><span>Relancer la recherche</span></a></p>');
			$('p.relaunch a').click(function() {
				$('div.criteria #submit').click();
			});
		},function()  {
			$('div.criteria').animate({'height':'10px'}, {duration:300});
			$(this).html('<span>Modifier vos critères</span>');
			$(this).parent().removeAttr('style');
			$('p.relaunch').remove();
		});
	}
	
	
	if($('body.index').length == 1) {
		
		var height = 150;
		$('#line2 > div').css('padding', 0).css('height', 0);
		$('#line3').append('<a class="left">Plus d\'options</a>');
		$('#line3 input').addClass('left');
		$('#line3 a').toggle(function() {		
			$('#line2 > div').stop().animate({'height':height}, 300, function() {
						$('#line2 > div').removeAttr('style');
					  });
		},function() {
			$('#line2 > div').stop().animate({'height':0, 'padding':0}, 300);
		});
	}
	
	// Annonces
	filterSeachForm($('#typesearch'));
	$('#typesearch').change(function() {
		filterSeachForm(this);
	});
			
	geocoder = new google.maps.Geocoder();
    var myOptions = {
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
     map = new google.maps.Map(document.getElementById("gmap"),
        myOptions);
	 codeAddress($('.e_item .left .address').text() + ', ' + $('.e_item .left .lieu').text() +', france');
	
	
	
});

function cleanSel(objId) {

	var toto = Array();
	
		var h = $(objId + '.multiSelect span').html().split(',');
		$.each(h, function(index, value) {
			toto.push(value.replace('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;','').replace('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',''));
		});
		
		$(objId + '.multiSelect span').html(toto.join(',')); 
}


function codeAddress(address) {
	geocoder.geocode( {'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
        
      } else {
        $('#gmap').html("<p>Nous n'avons pas réussi à localiser cette adresse : " + address + ' (' + status + ')</p>');
      }
    });
  }
 
function filterSeachForm(obj) {
	
	// Si promoteur : livraison + typebien + nbpieces + energie + promoteur + tva + defisc
	if ($(obj).val() == 13) {
		$('#annonces-form fieldset#line2 > div > div, #regionDiv').show();
		$('#regionMaisonDiv, #lotisseurP, #constructeurP, #prixP').hide();
				
	// Si lotisseur : lotisseur
	} else if ($(obj).val() == 14) {
		$('#annonces-form fieldset#line2 > div > div, #regionMaisonDiv').hide();
		$('#typesearchP, #regionDiv, #lotisseurP, #submitP, .left.options').show();
	
	// Si constructeur : nbpieces + energie + constructeur
	} else if ($(obj).val() == 15) {
		$('#annonces-form fieldset#line2 > div > div, #regionDiv').hide();
		$('#typesearchP, #regionMaisonDiv, #constructeurP, #submitP, #nbpieceP, #energieP, #prixP, .left.options').show();
	}

}

