$(document).ready(function(){
	//var map = new GMap2(document.getElementById('map_canvas'));
	var myLatlng = new google.maps.LatLng(46.666578980924875,6.510772705078125);
	var myOptions = {
	  zoom: 1,
	  center: myLatlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	var geocoder = new google.maps.Geocoder();
	var marker = new google.maps.Marker();
	var nb_picture = 0;
	var pic_id = 0;
	var $dialog = $('<div></div>')
	.html(sure_delete_pic)
	.dialog({
		autoOpen: false
		, title: '<span class="titledialog">'+delete_pic+'</span>'
		, buttons : {
			"ok":function() {
					if(pic_id){
						$(this).dialog("close");
						$("#sample"+pic_id).attr('src','/images/nopicture.jpg');
						$('#base64_'+pic_id).attr('value', '');
						$('#name_'+pic_id).attr('value', '');
						nb_picture--;
					}
			}
			, "cancel":function() { $(this).dialog("close");}
		}
	});
	loadMap(myLatlng, 1);
	updatePriceType();
	$('#price-type').change(function(){
		updatePriceType();
	});
	if(nb_pics){
		nb_picture = nb_pics;
	}
	var logged = ($('#email').val() == undefined);
	var geo = null;
	var request = null;
	if(edit){
		loadMap(new google.maps.LatLng(lat, long), 16);
	}else{
		// Try W3C Geolocation (Preferred)
		if(navigator.geolocation) {
			updateTipsSuccess(geoloc_available ,$("#search-error"));
			navigator.geolocation.getCurrentPosition(function(position) {
				updatePosition(position.coords);
			}, function() {
				handleError();
			}
		);
		// Try Google Gears Geolocation
		} else if (google.gears) {
			var geo = google.gears.factory.create('beta.geolocation');
			updateTipsSuccess(geoloc_available ,$("#search-error"));
			geo.getCurrentPosition(function(position) {
				updatePosition(position.coords);
				}, function() {
					handleError();
				}
			);
		// Browser doesn't support Geolocation
		} else {
			handleError();
		}

	}
	$('#classifiedform').submit(function() {
		return false;
	});
	$('#locationform').submit(function() {
		return false;
	});
	$('#searchlocation').click(function() {
		$("#search-error").html('&nbsp;').removeClass('error').removeClass('success').removeClass('tip-highlight');
		$("#searchStreet").removeClass('ui-state-error');
		if($('#searchStreet').val()){
			showAddress($('#searchStreet').val());
		}else{
			$("#searchStreet").addClass('ui-state-error');
        	updateTips(adress_needed ,$("#search-error"));
		}
	});
	$('#start_upload').click(function() {
		$('#fileUpload3').uploadifyUpload();
	});
	$('#clear_queue').click(function() {
		$('#fileUpload3').uploadifyClearQueue();
	});
	$('#html_description').wysiwyg({
		controls:{
			subscript:{visible:false},
			createLink:{visible:false},
			insertImage:{visible:false},
			separator05:{visible:false},
			justifyLeft:{visible:false},
			justifyCenter:{visible:false},
			justifyRight:{visible:false},
			justifyFull:{visible:false},
			h1mozilla:{visible:false},
			h2mozilla:{visible:false},
			h3mozilla:{visible:false},
			indent:{visible:false},
			outdent:{visible:false},
			superscript:{visible:false},
			undo:{visible:false},
			redo:{visible:false},
			removeFormat:{visible:false},
			insertOrderedList:{visible:false},
			insertUnorderedList:{visible:false},
			insertHorizontalRule:{visible:false},
			separator01:{visible:false},
			separator02:{visible:false},
			separator03:{visible:false},
			separator04:{visible:false},
			separator05:{visible:false},
			separator06:{visible:false},
			separator07:{visible:false},
			separator08:{visible:false},
			separator09:{visible:false},
			separator10:{visible:false}
		}
	});

	$('#sample0').attr('src', $('#picture_name0').val());
	$(".remove_picture").click(function(){
		if($('#name_'+this.id).attr('value')!=''){
			pic_id = this.id;
			$dialog.dialog('open'); 
			
		}
		if(nb_picture<4){
			$("#fileUpload3Uploader").css("display","block");
		}
	});
	$("#fileUpload3").uploadify({
		'uploader'		: '/js/uploadify/scripts/uploadify.swf',
		'script' 		: '/index/ajax-upload/?nb='+nb_picture,
		'cancelImg'     : '/images/cancel.png',
		//'buttonImg' 	: '/images/pluspicture.png',
		'buttonText' 	: buttonText,
		'width' 		: 200,
		'height' 		: 40,
		'folder' 		: 'files',
		'fileDesc' 		: 'Image Files',
		'fileExt' 		: '*.jpg;*.jpeg;*.gif;*.png',
		'multi'			: true,
		'auto'			: true,
		'sizeLimit' 	: 4000000,
		'onComplete' 	: function(a, b, c, d, e) {
		$("#picture-error").html('&nbsp;').removeClass('error').removeClass('tip-highlight');
			res = eval('(' + d + ')');
							if(d!=0){
								if(res.success){
									if($('#name_0').attr('value')!=''){
										if($('#name_1').attr('value')!=''){
											if($('#name_2').attr('value')!=''){
												id=3;
											}else{
												id = 2;
											}
										}else{
											id = 1;
										}
									}else{
										id = 0;
									}
									$('#sample'+id).attr('src', '/uploads/'+res.name);
									$('#name_'+id).attr('value', res.name);
									nb_picture++;
									if(nb_picture>=4){
										$("#fileUpload3Uploader").css("display","none");
									}
								}else{
									updateTips(res.error ,$("#picture-error"));
								}
						}
		}
	});

	var title 	= $("#title"),
	price 		= $("#price"),
	phone 		= $("#phone"),
	description = $('iframe').contents().find('body').html(),
	category 	= $("#category"),
	longitude 	= $("#longitude"),
	latitude 	= $("#latitude"),
	street	 	= $("#street"),
	zipcode 	= $("#zipcode"),
	city	 	= $("#city"),
	country 	= $("#country");
	var allFields = $([]).add(title).add(phone).add(price).add(description).add(category).add(longitude).add(latitude).add(street).add(city).add(country);
	if(!logged){
		var email	 	= $("#email");
		allFields = allFields.add(email);
	}
	tip = $(".errorvalidate"),
	tipvalidate = $(".validateTips"),
	allTips = $([]).add(tip).add(tipvalidate);

	$('#createButton').click(function(){
		
		var bValid 	= true;
		var bTop 	= false;
		allFields.removeClass('ui-state-error');
		allTips.html('&nbsp;').removeClass('success').removeClass('error').removeClass('tip-highlight');
		if(!logged){
			bValid 		= bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, email_format);
			if(!bValid && !bTop){
				bTop = true;
				$.scrollTo($('#email-container'),800);
			}
			var mail 	= email.val(),
			lang 		= $("#lang option:selected").attr('id'),
			first 		= $("#firstname").val(),
			last 		= $("#lastname").val();
		}else{
			var first 	= '',
			lang 		= '',
			last 		= '',
			mail 		= '';
		}
		
		bValid = bValid && checkLength(title,"title",1,140);
		if(!bValid && !bTop){
			bTop = true;
			$.scrollTo($('#title-container'),800);
		}
		bValid = bValid && checkValueRegexp(phone, phone.val().replace(/ /g,''), /^(\+?[0-9]*)$/,phone_problem);
		if(!bValid && !bTop){
			bTop = true;
			$.scrollTo($('#phone-container'),800);
		}
		bValid = bValid && checkOtherRegexp(price, $("#price-error"), /^(?:(?:\d*)|(?:\d*\.\d+))$/,price_only_number);
		if(!bValid && !bTop){
			bTop = true;
			$.scrollTo($('#price-container'),800);
		}
		if($("input[name=price-type]:checked").val() == 'notfree'){
			bValid = bValid && otherCheckLengthNotNull($("#price"), $("#price-error"), "price");
			if(!bValid && !bTop){
				bTop = true;
				$.scrollTo($('#price-container'),800);
			}
		}
		
		bValid = bValid && checkLengthOtherNotNull(latitude,$("#psearchlocation"),geolocalisation);
		if(!bValid && !bTop){
			bTop = true;
			$.scrollTo($('#locationform'),800);
		}
		
		
		data = {
	  		format: 'json',
			title : title.val(),
			phone : phone.val(),
	  		description: $('iframe').contents().find('body').html(),
			category: $("#category option:selected").attr('id'),
			longitude: $('#longitude').val(),
			latitude: $('#latitude').val(),
			street: street.val(),
			zipcode: zipcode.val(),
			city: city.val(),
			country: country.val(),
			type: $("input[name=type]:checked").val(),
			identity: $("input[name=identity]:checked").val(),
			email: mail,
			lang: lang,
			price_unit: 'fixed',
			price: $("#price").val(),
			currency: $("#currency option:selected").attr('id'),
			price_type: $("input[name=price-type]:checked").val()
		};
		
		var i = 0;
		$(".picture").each(function() {
			if($('#name_'+this.id.substring(8)).attr('value')!=''){
				eval('data.picture'+i+" = $('#sample'+this.id.substring(8)).attr('src')");
				eval('data.picture_name'+i+" = $('#name_'+this.id.substring(8)).val()");
				i++;
			}
		});
		data.nb_pics = i;
		if (bValid) {
			$.ajax({
				type : "POST",
			  	url : "/classifieds/ajax-creation/",
			  	data : data,
		  		dataType : "json",
			  	success:function(data){
		  			if(!data){
		  				updateTips(error_occured, tipvalidate);
		  			}else if(data.success){
		  				document.location.href = data.url;
					}else{
						updateTips(data.error, tipvalidate);
					}
				},
		  		error:function(){
		  			updateTips(error_occured, tipvalidate);
		  		}
			});
	    }
	});	

	function showAddress(address) {
		
	    if (geocoder) {
	      geocoder.geocode( { 'address': address}, function(results, status) {
	        if (status == google.maps.GeocoderStatus.OK) {
	        	marker.setMap(null);
	        	map.setCenter(results[0].geometry.location);
	        	map.setZoom(13);
		        pointeur = results[0].geometry.location;

		        $('#latitude').attr('value',pointeur.lat());
				$('#longitude').attr('value',pointeur.lng());
			       
			    marker = new google.maps.Marker({
					position: pointeur,
					map: map,
					draggable: true
				});
				geocoder.geocode({
					latLng: marker.getPosition()
					}, function(responses, status) {
						if (responses && responses.length > 0) {
							$('#geocode').attr('value', responses[0].formatted_address);	
							setMap(responses[0]);
						} else {
							resetMap();
						}
					}
				);
				
				loadDragEnd(marker);
	        } else {
	        	$("#searchStreet").addClass('ui-state-error');
	        	updateTips(address + search_not_found ,$("#search-error"));
	        }
	      });
	    }
	};
	
	
	function updatePriceType() {
		if($("#price-type option:selected").attr('id') == "notfree"){
			$("#pricing").css('display', 'block');
		}else{
			$("#pricing").css('display', 'none');
		}
	};
	
	function updatePosition(coords) {
		$("#search-error").html('&nbsp;').removeClass('error').removeClass('success').removeClass('tip-highlight');
		$("#searchStreet").removeClass('ui-state-error');
		loadMap(new google.maps.LatLng(coords.latitude,coords.longitude), 16);
	};
	
	function handleError(positionError) {
//		loadMap(new google.maps.LatLng(46.666578980924875,6.510772705078125), 1);
	};
	
	function loadMap(pointeur, zoom){
	    $('#latitude').attr('value',pointeur.lat());
	    $('#longitude').attr('value',pointeur.lng());
	    
	    marker.setMap(null);
    	map.setCenter(pointeur);
    	map.setZoom(zoom);
    	
	    marker = new google.maps.Marker({
	        position: pointeur,
	        map: map,
	        draggable: true
	    });
	    geocoder.geocode({
	    	latLng: marker.getPosition()
			}, function(responses, status) {
				if (responses && responses.length > 0) {
					$('#geocode').attr('value', responses[0].formatted_address);	
					setMap(responses[0]);
				} else {
					resetMap();
				}
			}
		);
	    loadDragEnd(marker);
	};
	
	function loadDragEnd(marker){
		google.maps.event.addListener(marker, 'dragend', function() {
			$("#searchStreet").attr('value', '');
			$("#searchStreet").removeClass('ui-state-error');
			$("#search-error").html('&nbsp;').removeClass('error').removeClass('success').removeClass('tip-highlight');
			var point = marker.getPosition(); 
			var lat = point.lat();
			var lng = point.lng();
			$('#latitude').attr('value',lat);
			$('#longitude').attr('value',lng);
			geocoder.geocode({
		    	latLng: marker.getPosition()
				}, function(responses, status) {
					if (responses && responses.length > 0) {
						$('#geocode').attr('value', responses[0].formatted_address);	
						setMap(responses[0]);
					}else{
						resetMap();
					}
				}
			);
		});
	};
	
	function setMap(resp){
		$(".errorgeoloc").html('&nbsp;').removeClass('error').removeClass('tip-highlight');
		$('#city').attr('value','');
		$('#street').attr('value','');
		$('#zipcode').attr('value','');
		$('#country').attr('value','');
		for (var i = 0; i < resp.address_components.length; i++)
		{
		    if (resp.address_components[i].types[0] == "street_number")
		    	$('#street').attr('value', $('#street').val()+', '+resp.address_components[i].long_name);
		    if (resp.address_components[i].types[0] == "route")
		    	$('#street').attr('value', resp.address_components[i].long_name+$('#street').val());
		    if (resp.address_components[i].types[0] == "postal_code")
		    	$('#zipcode').attr('value', resp.address_components[i].long_name);
		    if (resp.address_components[i].types[0] == "locality")
		    	$('#city').attr('value', resp.address_components[i].long_name);
		    if (resp.address_components[i].types[0] == "country")
		    	$('#country').attr('value', resp.address_components[i].short_name);
		}
		if(!$('#zipcode').attr('value')){
			$('#zipcode').attr('readonly',false);
			$('#zipcode').removeClass("trans");
			$('#edit_zip').css('display', 'block');
		}else{
			$('#zipcode').attr('readonly',true);
			$('#edit_zip').css('display', 'none');
			$('#zipcode').addClass("trans");
		}
	};
	
	function resetMap(){
		$('#city').attr('value','');
		$('#street').attr('value','');
		$('#zipcode').attr('value','');
		$('#country').attr('value','');
//		updateTips('KO' ,$(".errorgeoloc"));
	};
});
