/**
 * @author Piotr Kowalski <piotr.kowalski@piecioshka.pl>
 */
var googlelibapi = {
	
	//Library version
	version: 3,

	//center of Poland
	latitude: "52.000000000000001",
	longitude: "19.000000000000001",
	
	//map zoom
	zoom: 6,
	
	//radius kilometres from circles
	radiusKm: 10,
	enableCircleArea: true,
	placeToMap: null,
	addressConfiguration: 'best',
	
	//empty default google objects
	map: null,
	place: null,
	circle: null,
	geocoder: null,
	
	//default point
	defPoint: {},
	
	//array with markers and circles
	markersArray: [],
	markersSearchArray: [],
	markersInfoWindowContentArray: [],
	circlesArray: [],

    /**
     * Function waiting for Google Maps
     * 
     * @param {Object} callback
     */
	waitForGoogle: function( callback ) {
		var timer = null;
		var init = false;

		var checkForGmap = function() {
			if ( window.google != undefined && window.google.maps != undefined && window.google.maps.Geocoder != undefined && ! init) {
				init = true;
				clearTimeout( timer );
				callback();
			}
		};

		timer = setInterval( checkForGmap, 500 );
	},
	
	
	/**
	 * Set zoom
	 * 
	 * @param int param Number zoom
	 */
	setZoom: function( param ){
		if( param != undefined && typeof param == 'number' ){
			googlelibapi.zoom = param;
			return;
		}
	},
	
	/**
	 * Set place to map
	 * 
	 * @param string name Identification from html
	 */
	setPlaceToMap: function( name ){
		if( name == undefined ){
			return;
		}
		googlelibapi.placeToMap = name;
	},
	
	/**
	 * Set hidden configuration fields
	 * 
	 * @param float latitude 
	 * @param float longitude
	 */
	setHiddenConfFiels: function( latitude, longitude ){
		if( latitude == undefined ){
			latitude = googlelibapi.latitude;
		}
		if( longitude == undefined ){
			longitude = googlelibapi.longitude;			
		}
		document.getElementById( "group_coordinates_latitude" ).value = latitude;
		document.getElementById( "group_coordinates_longitude" ).value = longitude;
	},
	
	/**
	 * Get hidden configuration fields
	 */
	getHiddenConfFiels: function() {
		console.info( document.getElementById( "group_coordinates_latitude" ).value ); 
		console.info( document.getElementById( "group_coordinates_longitude" ).value ); 
	},
	
	/**
	 * Assign hidden fields
	 */
	assignHiddenConfFiels: function(){
		googlelibapi.defPoint.latitude = document.getElementById( "group_coordinates_latitude" ).value; 
		googlelibapi.defPoint.longitude = document.getElementById( "group_coordinates_longitude" ).value; 
	},
	
	/**
	 * Set address configuration
	 * 
	 * @param string param
	 */
	setAddressConfiguraion: function( param ){
		if( param == undefined ){
			return;
		}
		googlelibapi.addressConfiguration = param;
	},
	
	/**
	 * Disable circle area
	 */
	setDisableCircleArea: function(){
		googlelibapi.enableCircleArea = false;
	},
	
	/**
	 * Set default configuration
	 */
	setDefault: function(){
        if( typeof(googlelibapi.defPoint.latitude) == 'string' && typeof(googlelibapi.defPoint.longitude) == 'string' ){
            if( googlelibapi.defPoint.latitude != googlelibapi.latitude || googlelibapi.defPoint.longitude != googlelibapi.longitude ){

				var location = new google.maps.LatLng( googlelibapi.defPoint.latitude, googlelibapi.defPoint.longitude );
			  	var blueMarker = new google.maps.Marker({
			  		position: location, 
			  		map: googlelibapi.map,
			  		icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png'
			  	});
				
		        googlelibapi.markersSearchArray.push(blueMarker);
				
            }
        }
		
	},

	/**
	 * Set hidden address fields
	 * 
	 * @param string place 
	 */
	setHiddenAddressFields: function( place ){
        if( googlelibapi.addressConfiguration == 'best'){
	        //Dynamic fill detail form
        	if( place.province != undefined ){
        		document.getElementById("place_map_province_id").value = place.province;  // wojewodztwo 
        	}
        	if( place.city != undefined ){
        		document.getElementById("place_map_city_name").value = place.city;        // miejscowosc 
        	}
        	if( place.street != undefined ){
        		document.getElementById("place_map_street").value = place.street;         // ulica
        	}
	        if( place.post_code != undefined ){
	        	document.getElementById("place_map_post_code").value = place.post_code;   // kod pocztowy
	        }

	        var place_map_post_code = document.getElementById("place_map_house_nr");
	        if( place_map_post_code != undefined ){
	        	place_map_post_code.value = place.street_number;                          // numer domu
	        }
	        var place_map_section = document.getElementById("place_map_section");
	        if( place_map_section != undefined ){
	        	place_map_section.value = place.sublocality;	                          // dzielnica
	        }
        }
	},
	
	/**
	 * Get hidden address fields
	 */
	getHiddenAddressFields: function(){
        if( googlelibapi.addressConfiguration == 'best'){
	        //Dynamic fill detail form
	        console.info( document.getElementById("place_map_province_id").value ); 
	        console.info( document.getElementById("place_map_city_name").value ); 
	        console.info( document.getElementById("place_map_street").value ); 
	        console.info( document.getElementById("place_map_post_code").value );
        }
	},

	/**
	 * Main loader Google Maps with Geocoder
	 */
	initLoader: function(){
		
		if( googlelibapi.placeToMap == null ){
			return;
		}

		googlelibapi.geocoder = new google.maps.Geocoder();
	    var myOptions = {
	    	zoom: googlelibapi.zoom,
	    	center: new google.maps.LatLng( googlelibapi.latitude , googlelibapi.longitude ),
	    	mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
		
		googlelibapi.map = new google.maps.Map( document.getElementById( googlelibapi.placeToMap ), myOptions );
	    googlelibapi.infowindow = new google.maps.InfoWindow();
		
		google.maps.event.addListener(googlelibapi.map, 'click', function(event) {
			
			googlelibapi.clearMarkers();
			googlelibapi.clearMarkersInfoWindowContentArray();
			googlelibapi.addMarker(event.latLng);
			googlelibapi.geolocation(event.latLng);
			
	        if( googlelibapi.enableCircleArea ){
	    		googlelibapi.clearCircles();
	        	googlelibapi.drawCircle(event.latLng);
	        }

	        if( googlelibapi.addressConfiguration == "search" ){
				var searchGroupPlaces = new searchGroupPlacesHelper();
				searchGroupPlaces.showGroupForm();
				searchGroupPlaces.showPlacesForm();
	        }
	        
	    });

		googlelibapi.assignHiddenConfFiels();
		
	},
	
	/**
	 * Init loader for Google Maps plug
	 */
	initPlugGoogleMaps: function(){
		if( browserlib.getName() == 'msie' && browserlib.getVersion() == '6.0' ){
			if( googlelibapi.placeToMap != null ){
				
				var name = 'plug-google-maps';
				
				switch( googlelibapi.placeToMap ){
					case 'map-area': name = 'plug-google-maps-big'; break;
					case 'map-shell': name = 'plug-google-maps'; break;
					case 'map-present': name = 'plug-google-maps'; break;
				}
				
		        var plug = '<a href="' + DOMAIN + '" class="plug-google-maps" ><img src="images/' + name + '.gif" alt="" /></a>';
                $( "#" + googlelibapi.placeToMap ).html( plug );
			}
		}
	},

	/**
	 * Add place marker
	 * 
	 * @param object location Object with latitude and longitude
	 */
	addMarker: function( location, geolocation_button) {
		if( location == undefined ){
			return;
		}
		
		if(geolocation_button) {
			var icon_url = DOMAIN + 'images/buttons/blue.png';
		} else {
			var icon_url = DOMAIN + 'images/beachflag.png';
		}
		
		var clickedLocation = new google.maps.LatLng( location );
	  	var beachMarker = new google.maps.Marker({
	  		position: location, 
	  		map: googlelibapi.map,
	  		icon: icon_url
	  	});
	  	
	  	google.maps.event.addListener(beachMarker, 'click', function(event) {
	  		googlelibapi.geolocation(event.latLng);
	  		googlelibapi.infowindow.close();
	  		googlelibapi.infowindow.open(googlelibapi.map, beachMarker);
            pklib.outerlink();
	    });
	  
        googlelibapi.clearSearchMarkers();
        googlelibapi.infowindow.close();
	  	googlelibapi.markersArray.push(beachMarker);
	  	googlelibapi.map.setCenter(location);
	},
	
	/**
	 * Add search marker
	 * 
	 * @param object location Object with latitude and longitude
	 */
	addSearchMarker: function( location ) {
		if( location == undefined ){
            return;
        }
		
		var clickedLocation = new google.maps.LatLng( location );
	  	var blueMarker = new google.maps.Marker({
	  		position: location, 
	  		map: googlelibapi.map,
	  		icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png'
	  	});
	  	
	  	google.maps.event.addListener(blueMarker, 'click', function(event) {
	  		googlelibapi.infowindow.close();
			
			var a = blueMarker.position.lat();
			var b = blueMarker.position.lng();
			var i = googlelibapi.getIdSearchMarker(a, b);
			var msg = googlelibapi.markersInfoWindowContentArray[i];
			
			googlelibapi.infowindow.setContent( msg );
	  		googlelibapi.infowindow.open( googlelibapi.map, blueMarker );
            pklib.outerlink();
	    });
	  
	  	googlelibapi.markersSearchArray.push(blueMarker);
	  	googlelibapi.markersInfoWindowContentArray.push( googlelibapi.infowindow.getContent() );
	  	googlelibapi.map.setCenter(location);
	},
    
    /**
     * Get Message Martker
     * 
     * @param double x latitude 
     * @param double y longitude
     */
    getIdMarker: function( x, y ){
        if( x == undefined || y == undefined ){
            return;
        }
        
        var len = googlelibapi.markersArray.length;
        
        for(var i=0; i<len; ++i){
            var objx = googlelibapi.markersArray[i].position.lat();
            var objy = googlelibapi.markersArray[i].position.lng();
            
            if( objx == x && objy == y ){
                return i;
            }
        }
        return null;
        
    },
    
    /**
     * Get Search Message Martker
     * 
     * @param double x latitude
     * @param double y longitude
     */
    getIdSearchMarker: function( x, y ){
        if( x == undefined || y == undefined ){
            return;
        }
        
        var len = googlelibapi.markersSearchArray.length;
        
        for(var i=0; i<len; ++i){
            var objx = googlelibapi.markersSearchArray[i].position.lat();
            var objy = googlelibapi.markersSearchArray[i].position.lng();
            
            if( objx == x && objy == y ){
                return i;
            }
        }
        return null;
        
    },
	
	/**
	 * Google Maps Geo Localization
	 * 
	 * @param object latlng 
	 */
	geolocation: function( latlng ){
        if( latlng == undefined ){
            return;
        }

        if ( googlelibapi.geocoder ) {
			googlelibapi.geocoder.geocode({'latLng': latlng}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					if ( results[0] != undefined ) {
						googlelibapi.showAddress(results[0]);
						googlelibapi.infowindow.setContent(results[0].formatted_address);
					}
				} else {
//					alert("Geocoder failed due to: " + status);
				}
			});
        }
	},

	setDefaultToAddress: function( address, flag ) {

        if ( ! googlelibapi.geocoder ) {
        	googlelibapi.map.setZoom( 15 );
        	googlelibapi.setDefault();
        	return;
        }
        
		googlelibapi.geocoder.geocode({ 'address' : address }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				googlelibapi.showAddress( results[0] );
				googlelibapi.assignHiddenConfFiels();
				googlelibapi.map.setZoom( 15 );

				var lat = results[0].geometry.location.lat();
				var lng = results[0].geometry.location.lng(); 
				point = new google.maps.LatLng( lat, lng );
				googlelibapi.map.setCenter( point );
				googlelibapi.addMarker( point );
			}
            else if(flag == undefined){
                googlelibapi.setDefault();
            }
		});

	},
	
    /**
     * Clear all overlays 
     */
    clearMarkers: function(){
        if ( googlelibapi.markersArray ) {
            for (i in googlelibapi.markersArray) {
                googlelibapi.markersArray[i].setMap(null);
            }
            googlelibapi.markersArray = [];
        }
    },
    
    /**
     * Clear all overlays 
     */
    clearSearchMarkers: function() {
        if ( googlelibapi.markersSearchArray ) {
            for (i in googlelibapi.markersSearchArray) {
                googlelibapi.markersSearchArray[i].setMap(null);
            }
            googlelibapi.markersSearchArray = [];
        }
    },
	
	/**
	 * Clear info about markers from google map
	 */
	clearMarkersInfoWindowContentArray: function(){
		googlelibapi.markersInfoWindowContentArray = [];
	},
	
	/**
	 * Parser to address from place return by Google Maps
	 * 
	 * @return object place Object formatter with place
	 */
	parseGoogleMapsAddressComponenets: function(){
		
		var len = googlelibapi.place.length;
		var place = {};
		var useName = null;
		
		for( var i = 0; i < len; ++i){
			
			useName = googlelibapi.place[i].long_name;
		
			switch( googlelibapi.place[i].types[0] ){

			case 'postal_code': //kod pocztowy
				place.post_code = useName;
				break;
			case 'administrative_area_level_1': //wojewodztwo
				place.province = useName;
				break;
			case 'administrative_area_level_2': //powiat
				place.district = useName;
				break;
			case 'administrative_area_level_3': //miasto
				place.city = useName;
				break;
			case 'sublocality': //dzielnica
				place.sublocality = useName;
				break;
			case 'street_address': //ulica
				place.street = useName;
				break;
			case 'street_number':
				place.street_number = useName;
				break;
			}
			
		}

		if( place.city == undefined ){
			if( place.post_code != '' && place.post_code != undefined ){
				place.city = googlelibapi.cityPostCode( place.post_code );
				if( place.city[0] != undefined ){
					place.city = place.city[0][0]['name'];
				}
	        }
		}
		
		if( googlelibapi.addressConfiguration == "main" || googlelibapi.addressConfiguration == "search" ){
	        if( place.city != '' && place.city != undefined ){
	        	googlelibapi.setCityName( place.city );
	        } else if( place.post_code != '' && place.post_code != undefined ){
	        	googlelibapi.bindCityPostCodeSuccess( googlelibapi.cityPostCode( place.post_code ));
	        }
		}
		
		return place;
	},
	
	/**
	 * Show address
	 * 
	 * @param object response
	 */
	showAddress: function( response ) {
		
		googlelibapi.place = response.address_components;
		googlelibapi.setHiddenAddressFields( googlelibapi.parseGoogleMapsAddressComponenets() );
		
		var lat = response.geometry.location.lat();
		var lng = response.geometry.location.lng(); 
		
		googlelibapi.setHiddenConfFiels( lat, lng );
	},

	/**
	 * Get points to circle
	 * 
	 * @param object latLng Object with latitiude and latuange
	 * @return array points Array with geometry points to circle
	 */
	circlePath: function( latLng ) {
		var radiusLat = googlelibapi.radiusKm / (40008 / 360);
		var radiusLng = googlelibapi.radiusKm / (40075 * Math.cos(latLng.lat() * Math.PI / 180) / 360);
		var points = new Array();
		var pointsNumber = 40;
		var step = 2 * Math.PI / pointsNumber; 
		for (var alfa = 2 * Math.PI + step; alfa > 0; alfa -= step) {
			var x = latLng.lat() + radiusLat * Math.cos(alfa);
			var y = latLng.lng() + radiusLng * Math.sin(alfa);
			points.push(new google.maps.LatLng(x,y));
		}
		return points;
	},
	
	/**
	 * Draw circle from array points
	 * 
	 * @param array curPos Array with circle points
	 */
	drawCircle: function ( curPos ) {
		
		var vertexes = googlelibapi.circlePath( curPos, googlelibapi.radiusKm );
		googlelibapi.circle = new google.maps.Polygon({
			paths: vertexes,
		    strokeColor: "#DA9B00",
		    strokeOpacity: 0.8,
		    strokeWeight: 5,
		    fillColor: "#F8F0B1",
		    fillOpacity: 0.35
		});
		
		googlelibapi.circlesArray.push( googlelibapi.circle );
		googlelibapi.circle.setMap( googlelibapi.map );
	},

	/**
	 * Clear all circles from map
	 */
	clearCircles: function() {
		if ( googlelibapi.circlesArray ) {
			for (i in googlelibapi.circlesArray) {
				googlelibapi.circlesArray[i].setMap(null);
			}
		}
	},
	
	//jQuery elements

	bindTabs: function(){
		$("#tab-address-tabs .tabs-panel a").bind('click', function(){
			googlelibapi.getBrowseView();
		});
	},
	
	getBrowseView: function(){
		switch( $("div.single-tab:visible").attr("id") ){
		case 'tab-address-google-maps':
			$("#tab-address input.edit_view").val('m');
			break;
		case 'tab-address-detail':
			$("#tab-address input.edit_view").val('d');
		}
	},
	
	setProvince: function( province ) {
		if( province == undefined ){
			return;
		}
		if( province == '' ){
			$(".place_province_id").empty();
		}
		$(".place_province_id").val( province );
	},

	setStreet: function( street ) {
		return;
		/*
		if( street == undefined ){
			return;
		}
		$(".place_street").replaceWith( '<input type="text" value="'+street+'" class="place_street" name="place[street]" /> ' );
		*/
	},

	setPostCode: function( post_code ) {
		if( post_code == undefined ){
			return;
		}
		if( post_code == '' ){
			$(".place_post_code").empty();
		}
		$(".place_post_code").val( post_code );
	},
	
	setHouseNr: function( house_nr ) {
		if( house_nr == undefined ){
			return;
		}
		if( house_nr == '' ){
			$(".place_house_nr").empty();
		}
		$(".place_house_nr").val( house_nr );
	},
	
	setFlatNr: function( flat_nr ) {
		if( flat_nr == undefined ){
			return;
		}
		if( flat_nr == '' ){
			$(".place_flat_nr").empty();
		}
		$(".place_flat_nr").val( flat_nr );
	},

	setCityName: function( city ){
		return;
		/* 
		if( city == undefined ){
			return;
		}
		var inputListOfCity = $('<input type="text" name="place[city_name]" class="place_city_name" value="'+city+'" />');
		
		if ( $(".selectInput.dynamics").length != 0 ){
			$(".selectInput.dynamics").replaceWith( inputListOfCity );
		} else {
			$(".place_city_name").replaceWith( inputListOfCity );	
		} */
	},
	
	setSection: function( section ) {
		if( section != undefined && section != '' && section != $(".place_city_name").val() ){
			$(".place_city_name").val( $(".place_city_name").val() + " (" + section + ")" );
		}
	},
    
    setSendingStreet: function( param ){
        if( param  == undefined ){
            return;
        }
        document.getElementById( "sending_street").value = param;
    },
	
	clearMiniAddres: function(){
		googlelibapi.setStreet('');
		googlelibapi.setPostCode('');
		googlelibapi.setHouseNr('');
		googlelibapi.setFlatNr('');
	},
	
	clearElementBySelect: function(){
		$(".place_province_id").bind('change', function(){
			googlelibapi.setCityName('');
			googlelibapi.cityUnMarkError();
			googlelibapi.bindByKeypress();
			googlelibapi.clearMiniAddres();
			$(".city_info_manipulation").empty();
			$(".street_info_manipulation").empty();
			$(".place_city_name").focus();
		});
		
		$(".place_city_name").bind('change', function(){
			googlelibapi.clearMiniAddres();
		});
		
	},
	
	getCityFromProvinceByAjax: function( province_id, city_key ){
		googlelibapi.setHouseNr('');
		googlelibapi.setFlatNr('');
		googlelibapi.setPostCode('');
		googlelibapi.cityUnMarkError();
		
		city_key = encodeURI(city_key);
		
		if( city_key == '' || city_key == undefined || typeof city_key != "string" || province_id == '' || province_id == undefined || typeof province_id != "string" ){
			return;
		}
		
		$.ajax({
			async: false,
			url: DOMAIN + "ajax,city-province-id.html",
			data: "province_id=" + province_id + "&city_key=" + city_key,
			type: "get",
			dataType: "json",
			error: function(error){
//				alert("getCityFromProvinceByAjax("+province_id+","+city_key+")");
//				alert(error);
			},	
			success: function( data, textStatus, XMLHttpRequest ){
				
				var response = data;
				
				var len = response.length;
				var selectCities = $('<select name="place[city_name]" class="place_city_name" />');
				
				for(var i=0; i<len; ++i){
					if( response[i].municipality == response[i].name ){
						selectCities.append('<option value="'+response[i].city_id+'">'+response[i].name+'</option>');
					} else {
						selectCities.append('<option value="'+response[i].city_id+'">'+response[i].name+' ('+response[i].municipality+')</option>');
					}
				}
				
				if( len >= 1){
					$(".place_city_name").replaceWith( selectCities )
					if( $(".erase.city").length == 0 ){
						$(".place_city_name").parent().find(".city_info_manipulation").empty().append( $(googlelibapi.eraseButtonHtml).addClass('city') );
					}
					googlelibapi.eraseCityButton();
					
					selectCities.change( function(){
						googlelibapi.getStreetFromCityByAjax ( $(this).val() );
					});
					
					googlelibapi.cityUnMarkError();
					googlelibapi.getStreetFromCityByAjax( $(".place_city_name").val() );
					
				} else {
					googlelibapi.cityMarkError();
				}
			}
		})
	},
	
	cityPostCode: function( code ){
		
		$(".selectInput.dynamics").eq(0).after('<input type="text" name="place[city_name]" class="place_city_name" value="" />');
		$(".selectInput.dynamics").remove();

		if( code == undefined ){
			return;
		}
		
		var result = null;
		
		$.ajax({
			async: false,
			url: DOMAIN + "ajax,city-post-code.html",
			data: "code=" + code,
			type: "get",
			dataType: "json",
			error: function(error){
//				alert("cityPostCode ("+ code +")");
//				alert(error);
			},
			success: function( data, textStatus, XMLHttpRequest ){
				result = data;
			}
		});
		
		return result;
	},
	
	
	bindCityPostCodeSuccess: function( response ){

		var length = response.length;
		var selectListOfCity = $('<select name="place[city_name]" class="place_city_name"></select>');
		
		for(var i=0; i<length; ++i){
			if( response[i][0].municipality == response[i][0].name ){
				selectListOfCity.append('<option value="'+response[i][0].name+'">'+response[i][0].name+'</option>');
			} else {
				selectListOfCity.append('<option value="'+response[i][0].name+'">'+response[i][0].name+' ('+response[i][0].municipality+')</option>');
			}
		}
		
		if( length > 1){
			$(".place_city_name").eq(0).wrapAll( '<div class="selectInput dynamics" />' );
			$(".place_city_name").replaceWith( selectListOfCity );
			if( $(".erase.city").length == 0 ){
				$(".place_city_name").parent().find(".city_info_manipulation").empty().append( $(googlelibapi.eraseButtonHtml).addClass('city') );
			}
			googlelibapi.eraseCityButton();
		} else {
			if( response[0] != undefined ){
				googlelibapi.setCityName( response[0][0].name  );
			}
		}
	},
	
	getStreetFromCityByAjax: function( city_id ){
		if( city_id == '' || city_id == undefined || typeof city_id != "string" ){
			return;
		}
		
		$.ajax({
			async: false,
			url: DOMAIN + "ajax,city-id.html",
			data: "city_id=" + city_id,
			type: "get",
			dataType: "json",
			error: function(error){
//				alert("getStreetFromCityByAjax ("+name+")");
//				alert(error);
			},	
			success: function( data, textStatus, XMLHttpRequest  ){

				var response = data;
				
				googlelibapi.clearMiniAddres();
				
				var length = response.length;
				
				if( length > 0){
					
					var ifStreetNull = 0;
					var selectStreet = $('<select name="place[street]" class="place_street" />');
					var inputStreet = $('<input type="text" name="place[street]" class="place_street" />');
					
					for(var i=0; i<length; ++i){
						if( response[i].street != null ){
	                        if( response[i].numbers != null || response[i].numbers != undefined ) {
	                            selectStreet.append('<option value="'+response[i].street+'" title="'+response[i].post_code+'" >'+response[i].street+' ('+response[i].numbers+')</option>');
	                        } else {
	                            selectStreet.append('<option value="'+response[i].street+'" title="'+response[i].post_code+'" >'+response[i].street+'</option>');
	                        }
						} else {
							ifStreetNull = 1;
						}
					}
					
					if( ifStreetNull != 1 ){
						googlelibapi.setSendingStreet('select');
						$(".place_street").replaceWith( selectStreet );
						if( response[0].post_code != undefined ){
							googlelibapi.setPostCode( response[0].post_code );
						}
						if( $(".erase.street").length == 0 ){
							$(".place_street").parent().find('.street_info_manipulation').html( $(googlelibapi.eraseButtonHtml).addClass('street') );
						}
						googlelibapi.eraseStreetButton();
					}

				} else {
					if( response[0].name != undefined ){
						googlelibapi.setStreet( response[0].name );
						googlelibapi.bindByKeypress();
					}
				}

				selectStreet.change(function () {
					var post_code = "";
					$(selectStreet).find("option:selected").each(function(){
						post_code += $(this).attr("title") + "";
					});
					googlelibapi.setPostCode( post_code );
		        }).change();
			}
		})
		
	},
	
	deleteCityEraseButton: function(){
		$(".city_info_manipulation").empty();
		$(".place_city_name").focus();
	},
	
	deleteStreetEraseButton: function(){
		$(".street_info_manipulation").empty();
		$(".place_street").focus();
	},
	
	timeToWait: 2000,
	
	bindByKeypress: function(){
		var timer;
		$(".place_city_name").bind('keyup', function(){
			if( timer ) {
                clearTimeout(timer);
			} 
			timer = setTimeout(function(){
				googlelibapi.getCityFromProvinceByAjax ( $(".place_province_id").find("option:selected").attr("value"), decodeURI($(".place_city_name").attr("value")) );
			}, googlelibapi.timeToWait);
		});
		 
	},
	
	eraseButtonHtml:('<a href="#" class="erase">Skasuj</a>'),
	
	eraseCityButton: function(){
		$(".erase.city").unbind('click');
		$(".erase.city").bind('click', function(){
			googlelibapi.setCityName('');
			googlelibapi.bindByKeypress();
			googlelibapi.clearMiniAddres();
			googlelibapi.deleteStreetEraseButton();
			googlelibapi.deleteCityEraseButton();
			return false;
		});
	},
	
	eraseStreetButton: function(){
		$(".erase.street").unbind('click');
		$(".erase.street").bind('click', function(){
			googlelibapi.bindByKeypress();
			googlelibapi.clearMiniAddres();
			googlelibapi.deleteStreetEraseButton();
			googlelibapi.setSendingStreet('input');
			return false;
		});
	},
	
	cityMarkError: function(){
		$(".place_city_name").css("color", "#aaaaaa");
		$(".place_city_name").parent().find(".error").remove();
		$('.place_city_name').parent().find('.city_info_manipulation').empty().append('<span class="error">Brak miasta!</span>');
	},
	
	cityUnMarkError: function(){
		$(".place_city_name").css("color", "#000000");
		$(".place_city_name").parent().find(".error").remove();
	}
	
};

