$(document).ready(function(){
	/* CARTE */
	if($('#departement').length > 0){
		rollCarte('departement');
	}

	/* CAROUSEL SELECTION */
	if($('#carousel-selection').length > 0){
		jQuery('#carousel-selection').jcarousel({
			scroll: 3,
			initCallback: initCarousel,
			itemLoadCallback: positionCarousel,
			buttonNextHTML: null,
			buttonPrevHTML: null
		});
	}
	
	$('.print-this').bind('click', function() {
	  window.print();
	  return false;
	 });
						   
	/* VISIONNEUSE */
	if($('#visionneuse').length > 0){
		jQuery('#visionneuse').jcarousel({
			scroll: 5,
			initCallback: initCarousel,
			itemLoadCallback: positionCarousel,
			buttonNextHTML: null,
			buttonPrevHTML: null
		});
		$('#visionneuse a').click(function(event){
			event.preventDefault();
			var img = $(this).attr('href');
			$('#ecran img').attr('src',img);
		});
		$('.voir-photos a').click(function(event){
			event.preventDefault();
			if($(this).hasClass('carousel') == true){
				$(this).html('Retour à la visionneuse photo').attr('class','liste');
				$('.visionneuse-carousel').hide();
				var tpl = '';
				$.each($('#visionneuse a'),function(i,e){
					var url = $(e).attr('href');
					tpl+='<div class="item"><img width="648" src="'+url+'" alt=""/></div>';
				});
				$('.visionneuse-liste').html(tpl).show();
			}else{
				$(this).html('Voir toute les photos').attr('class','carousel');
				$('.visionneuse-carousel').show();
				$('.visionneuse-liste').hide();
			}
		});
	}
	
	/* CONTACT AGENCE */
	$.each($('.contact-agence form'),function(i,e){
		$(e).validate();
	});
	
	/* DEMANDE D4ESTIMATION */
	$('.demande-estimation form').validate();
	
	if($('#gmap').length){
		var latlng = new google.maps.LatLng($('#gmap').data('lat'), $('#gmap').data('lng'));
		var myOptions = {
			zoom: 15,
			center: latlng,
			scrollwheel: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("gmap"), myOptions);
		var marker = new google.maps.Marker({
			position: latlng,
			map: map
		});
	}
	
	/* UTILS LISTE */
	if($('.utils-liste .onglets').length){
		$('.utils-liste .onglets a').click(function(event){
			event.preventDefault();
			$('.utils-liste .onglets a').removeClass('on');
			$(this).addClass('on');
			var num = $('.utils-liste .onglets a').index(this);
			$('.utils-liste .onglet').hide();
			$('.utils-liste .onglet:eq('+num+')').show();
		});
	}
	
	/* FORM RECHERCHE */
	if($('.form-recherche').length && $('.utils-liste .onglets').length){
		$('.form-recherche .actions a').click(function(event){
			event.preventDefault();
			$(this).parents('.onglet').hide();
			$('.utils-liste .onglets a').removeClass('on');
		});
	}
	
	if($('#order').length) {
        $('#order').bind('change',
        function() {
        	$('#sort').val($('#order').val());
        	$('#search_form').submit();
        });
    }
});

/*
#############
# FUNCTIONS #
#############
*/

var rollCarte = function(carte){
	$('#'+carte+' area').mouseenter(function(){
		var num = parseInt($('#'+carte+' area').index(this)+1);
		var y = Math.ceil(num / 10);
		var x = num - ((y-1)*10);
		var pos = '-'+((x * 300) -300) + 'px -'+y*300+'px';
		$('.map-fg.'+carte).css({
			backgroundPosition: pos				 
		});
	}).mouseleave(function(){
		$('.map-fg.'+carte).css({
			backgroundPosition: '0 0'
		});
	});
};

/* GENERIQUE CAROUSEL */
var initCarousel = function(carousel){
	$('#next-'+carousel.list[0].id).click(function(event){
		event.preventDefault();
		if(!$(this).hasClass('off')){
			carousel.next();
		}
    });
    $('#previous-'+carousel.list[0].id).click(function(event){
		event.preventDefault();
		if(!$(this).hasClass('off')){
			carousel.prev();
		}
    });
	if($('.position-'+carousel.list[0].id).length){
		for(i=0;i<parseInt(carousel.options.size/carousel.options.scroll,10);i++){
			$('.position-'+carousel.list[0].id).append('<a href="#">'+(i+1)+'</a>');
		}
		$('.position-'+carousel.list[0].id+' a').click(function(event){
			event.preventDefault();
			var index = $('.position-'+carousel.list[0].id+' a').index(this);
			carousel.scroll((index*carousel.options.scroll)+1);
		});
	}
	if($('.count-'+carousel.list[0].id).length){
		$('.count-'+carousel.list[0].id).html('1 / '+parseInt(carousel.options.size/carousel.options.scroll,10));
	}
};
var positionCarousel = function(carousel){
	var index = Math.ceil(carousel.last/carousel.options.scroll);
	if(index === 0 || index === 1){
		$('#previous-'+carousel.list[0].id).addClass('off');
	}else{
		$('#previous-'+carousel.list[0].id).removeClass('off');			
	}
	if(index === Math.ceil(parseInt(carousel.options.size,10)/carousel.options.scroll)){
		$('#next-'+carousel.list[0].id).addClass('off');
	}else{
		$('#next-'+carousel.list[0].id).removeClass('off');
	}
	if($('.position-'+carousel.list[0].id).length){
		$('.position-'+carousel.list[0].id+' a').removeClass('on');
		$('.position-'+carousel.list[0].id+' a:eq('+parseInt(index-1,10)+')').addClass('on');
	}
	if($('.count-'+carousel.list[0].id).length){
		$('.count-'+carousel.list[0].id).html(Math.ceil(carousel.last/carousel.options.scroll)+' / '+Math.ceil(carousel.options.size/carousel.options.scroll));
	}
};




var Application = {
    init: function() {
//        Application.autocomplete();
//        Application.placeholder();
//        Application.validate();
        Application.map();
        Application.lead_project();
    },

	lead_project: function() {
		if ($('#request_type_3').length > 0) {
			$('#request_type_3').bind('change', function() {
				$('.request_type_4_row').hide();
			});
			$('#request_type_4').bind('change', function() {
				$('.request_type_4_row').show();
			});
		} 
	},

	map: function() {
		if ($('#map').hasClass('tobind')) {
	        $('#map area, #places a').bind('mouseover',
	        function() {
	            var region = $(this).attr('class');
	            $('#area_image').css('background', "url('/images/" + region + ".gif') no-repeat");
	            $('#places .' + region).css('text-decoration', 'underline').css('color', '#e99200');
	        });
	        $('#map area, #places a').bind('mouseout',
	        function() {
	            $('#area_image').css('background', "url('/images/none.gif')");
	            $('#places .' + $(this).attr('class')).css('text-decoration', 'none').css('color', '#0E6FCB');
	        });
	      }
    },

    placeholder: function() {
        $('input').placeholder();
    },

    validate: function() {
        $('#form_search').validate();
        $('#form_contact').validate();
        $('#form_suggestion').validate({
            submitHandler: function(form) {
                $.post($(form).attr('action'), $(form).serialize(),
                function(data) {
                    if (data.type == 'success') {
                        _gaq.push([
                        '_trackEvent',
                        'Create alert result',
                        "'" + data.email + "'"
                        ]);
                        $('#suggestion').removeClass('notice').addClass('success').html("<p><strong>" + data.message + "</strong></p>");
                    } else {
                        alert("Une erreur est survenue, veuillez recommencer.");
                    }
                });
                return false
            }
        });
        $('#form_lead').validate({
            submitHandler: function(form) {
                $(form).find('input[type=submit]').attr('disabled', 'disabled');
                $.post($(form).attr('action'), $(form).serialize(),
                function(data) {
                    $(form).find('input[type=submit]').removeAttr('disabled');
                    if (data.type == 'success') {
                        _gaq.push([
                        '_trackEvent',
                        'Lead agence',
                        "'" + data.listing_type_id + "'"
                        ]);
                        $('.navigation').prepend($('<p class="' + data.type + '">' + data.message + '</p>'));
                        $('#broker').append($(data.broker + "<p class=\"contacted success\"><strong>Votre demande a été envoyée avec succès à l'agence!</strong></p><div class=\"clear\"></div>"));
                        $.scrollTo($('.success'), 300);
                        $(form).hide();
                        $('#show-lead').remove();
                        $('.help').remove();
                        $('.error').remove();
                    } else if (data.type == 'redirection') {
                    	window.location = data.message;
                    } else {
                        $('.error').remove();
                        $.each(data.errors,
                        function(i, e) {
                            $('#' + i).parent().append($('<label class="error" for="' + i + '">' + e + '</label>'));
                        });
                        $(form).prepend($('<p class="' + data.type + '">' + data.message + '</p>'));
                        $.scrollTo($('.error')[0], 300);
                    }
                });
                return false;
            }
        });
    }
};

jQuery(function($) {
    Application.init();
});

var ie7 = false;
var ie6 = false;
var ac;
var output;
var outputdata = new Array;
var outputvalue = new Array;

jQuery(function($) {
	if ($('#location').length > 0) {
		$('#location').addClass('nokeyup');
		if ($('#location').attr("complex")=="1" || $('#location').attr("complex")=="2") {
			output = $('#location').attr("output");
			outputdata = $('#'+output).val();
			outputvalue = $('#'+output+'_name').val();
			if (outputdata.length > 0) outputdata = outputdata.split(',');
			if (outputvalue.length > 0) outputvalue = outputvalue.split(',');
			if (outputdata!='') {
				$('#ajaxresults').html('');
				for (i=0;i<outputdata.length;i++){
					if ($('#location').attr("complex")=="1") {
						$('#ajaxresults').append('<div id="auto_'+outputdata[i]+'" class="width240 clear clearfix spad"><div class="fleft pixel11 black width225">'+outputvalue[i]+'</div><div class="fright miniclose" onclick="removeData(\''+outputdata[i]+'\');"></div></div>');
					} else {
						$('#ajaxresults').append('<div id="auto_'+outputdata[i]+'" class="l2pad clear clearfix width155" ><div class="fleft pixel11 black width125">'+outputvalue[i]+'</div><div class="fright miniclose" onclick="removeData(\''+outputdata[i]+'\');"></div></div>');
					}
				}
				$('#ajaxresults').prev().show();
				$('#ajaxresults').show();
			} else {
				outputdata = new Array;
				outputvalue = new Array;
			}
			ac = $('#location').autocomplete({
				serviceUrl: $('#location').attr("autocompleter"),
				onSelect: function(value, data) {			
					if (typeof(data)!='undefined' && jQuery.inArray(data.toString(), outputdata)==-1) {
						outputdata.push(data.toString());
						outputvalue.push(value);
						$('#'+output).val(outputdata);
						$('#'+output+'_name').val(outputvalue);
						if (outputdata.length > 0) {
							$('#ajaxresults').prev().show();
							$('#ajaxresults').show();
						}	
					}
				}
			});
		} else {
			var o = $('#location').attr("output");
			if ($('#location').attr("home")) {
				ac = $('#location').autocomplete({width:468,
					serviceUrl: $('#location').attr("autocompleter"),
					onSelect: function(value, data){
						$('#'+o).val(data);
						$('#'+o+'_name').val(value);
					}
				});
			} else {
				ac = $('#location').autocomplete({
					serviceUrl: $('#location').attr("autocompleter"),
					onSelect: function(value, data){
						$('#'+o).val(data);
						$('#'+o+'_name').val(value);
					}
				});
			}
		}
	}

	if ($('#locationm').length > 0) {
		$('#locationm').addClass('nokeyup');
		$('#locationm').closest('form').keypress(function(){return noenter();});
		var om = $('#locationm').attr("output");
		$('#locationm').autocomplete({width:202,
			serviceUrl: $('#locationm').attr("autocompleter"),
			onSelect: function(value, data){
				$('#'+om).val(data);
				$('#'+om+'_name').val(value);
			}
		});
	}
});

function hideSelects() {
	if (ie7) {
		$('select').parent().css('min-height',$('select').height() + 2 + 'px');
		$('select').not('#box select').hide();
	}
}

function showSelects() {
	if (ie7) {
		$('select').not('#box select').show();
	}
}

function noenter() {
	if (window.event && window.event.keyCode == 13) {
		ac.select(ac.selectedIndex);
		return false;
	}
}





var Stats;
Stats = (function() {
  function Stats(base_url, token) {
    this.base_url = base_url;
    this.token = token;
    this.item = 'listing';
    this.ids_search = new Array;
    this.ids_view = new Array;
    this.expiry_date;
  }
  
  Stats.prototype.setCookie = function(cookie_name, value, ms_to_expire, path, domain, secure) {
    var _this = this;
	if (ms_to_expire) {
      _this.expiry_date = new Date();
      _this.expiry_date.setTime(_this.expiry_date.getTime() + ms_to_expire);
    }
    document.cookie = cookie_name + '=' + window.encodeURIComponent(value) +
		(ms_to_expire ? ';expires=' + _this.expiry_date.toGMTString() : '') +
        ';path=' + (path || '/') +
        (domain ? ';domain=' + domain : '') +
        (secure ? ';secure' : '');

  };
  
  Stats.prototype.getCookie = function(cookie_name) {
  	var cookie_pattern = new RegExp('(^|;)[ ]*' + cookie_name + '=([^;]*)'),
		cookie_match = cookie_pattern.exec(document.cookie);
	return cookie_match ? window.decodeURIComponent(cookie_match[2]) : 0;
  }

  Stats.prototype.track = function() {
    var _this = this;
    
    $('.track_search').each(function(i, el) {
      _this.item = $(el).data('item');
      _this.ids_search.push("%22" + $(el).val() + "%22");
    });
    
    $('.track_view').each(function(i, el) {
      _this.item = $(el).data('item');
      _this.ids_view.push("%22" + $(el).val() + "%22");
    });
    
    if (_this.ids_search.length > 0) {
      if (!_this.getCookie('search' + _this.ids_search.join('_'))) {
        $('body').append($('<img style="display:none;" src="' + _this.base_url + '?ids=[' + _this.ids_search.join(',') + ']&type=display_search_count&token=' + _this.token + '&item=' + _this.item + '" />'));
      }
      return _this.setCookie('search' + _this.ids_search.join('_'), 1, (5* 1000), '/');
    }
    
    if (_this.ids_view.length > 0) {
      if (!_this.getCookie('view' + _this.ids_view.join('_'))) {
      	$('body').append($('<img style="display:none;" src="' + _this.base_url + '?ids=[' + _this.ids_view.join(',') + ']&type=display_view_count&token=' + _this.token + '&item=' + _this.item + '" />'));
      } 
      return _this.setCookie('view' + _this.ids_view.join('_'), 1, (5* 1000), '/');
    }
    
  };
  
  return Stats;
})();

$(function() {
	stats = new Stats("http://stats.prestige-et-charme.com/api/stats", "pc");
	stats.track();
});
