/**
 * @author bad seed
 */
	
	
	function setCookie(c_name, value, exdays) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
		document.cookie = c_name + "=" + c_value;
	}

	function getCookie(c_name) {
		var i, x, y, ARRcookies = document.cookie.split(";");
		for( i = 0; i < ARRcookies.length; i++) {
			x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
			y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
			x = x.replace(/^\s+|\s+$/g, "");
			if(x == c_name) {
				return unescape(y);
			}
		}
	}


	var reloadLastAd = function() {};
	function showAdDetails(Id) {
		$('#detail_canvas').html("<br/><br/><center><img alt='loading' width='200' height='192' src='assets/loading.gif'/></center>");
		reloadLastAd = function() {showAdDetails(Id);};
		$.get('ilandetaylari.php?adId=' + Id, function(data) {
			$('#detail_canvas').html(data);			
		});
		
		//window.frames["adsense_anasayfa_iframe"].location.reload();
		var url = $('#adsense_anasayfa_iframe').attr('src');
		$('#adsense_anasayfa_iframe').attr('src', url);
		

		
	}

	function downloadAdData() {

		var strCityName = $('#adCity').val();
		myGeocoder.geocode({
			'address' : strCityName,
			'country' : 'TR'
		}, function(results, status) {
			if(status == google.maps.GeocoderStatus.OK) {
				var tempLocation = results[0].geometry.location + ' ';
				tempLocation = tempLocation.slice(1, -2);

				var latlng;
				eval("latlng = new google.maps.LatLng(" + tempLocation + ")")
				myMap.panTo(latlng);

				//After centering the map let's retrieve data
				var nAdType = $('#adType').val();
				$.ajax({
					type : "POST",
					url : "ilangetir.php",
					dataType : "json",
					data : {
						lat : myMap.getCenter().lat(),
						lng : myMap.getCenter().lng(),
					},

					success : function(data) {
						for(i in data) {
							var tempAd = new ad(data[i].id, data[i].adType, data[i].lat, data[i].lng, data[i].price);

							if(myAdsArray[data[i].id] == undefined || myAdsArray[data[i].id] == null)
								myAdsArray[data[i].id] = tempAd;
						}
						
						reloadLastAd();
						filterMarkers2();
					},
					error : function(jqXHR, textStatus, errorThrown) {
						//alert(textStatus +'\n' + errorThrown)
					}
				});

			} else {
				//alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}

	function resetDropdownValueToMax(selector) {
		try {
			$(selector + ' option:last').attr('selected', 'selected');
			return $(selector).val();
		} catch(err) {
			alert(err.Description)
		}

	}

	function filterMarkers2() {
		
		var adType = $('#adType').val();
		var minPrice = 0;
		var maxPrice = 0;

		minPrice = parseInt($('#minRentPrice').val());
		maxPrice = parseInt($('#maxRentPrice').val());

		if(maxPrice < minPrice) {
			maxPrice = resetDropdownValueToMax('#maxRentPrice');
		}
			
		if(myAdsArray) {
			for(i in myAdsArray) {
				if( myAdsArray[i].type == adType && myAdsArray[i].price >= minPrice && myAdsArray[i].price <= maxPrice) {
					myAdsArray[i].marker.setMap(myMap);
				} else {
					myAdsArray[i].marker.setMap(null);
				}
			}
		}

	}

	function formatPrice(nPrice) {
		return Math.floor(nPrice / 1000);
	}

	var lastOpenedInfoWindow = null;
	var lastClickedMarker = null;
	function ad(Id, Type, Lat, Lng, Price) {
		this.id = Id;
		this.type = Type;
		this.lat = Lat;
		this.lng = Lng;
		this.price = Price;

		this.location = new google.maps.LatLng(this.lat, this.lng);

		var isVisited = false;

		var iconUrl = "assets/condominium-green.png";
		var activeIconUrl = "assets/condominium-red.png";
		var visitedIconUrl = "assets/condominium-grey.png";
		//activeMarker

		var visitedAdIds = " " + getCookie('visitedAdIds');
		if(visitedAdIds.indexOf("," + Id + ",") > 0) {
			iconUrl = visitedIconUrl;
			isVisited = true;
		}

		this.marker = new google.maps.Marker({
			position : this.location,
			map : null,
			icon : iconUrl
		});


		var tempInfoWindow = this.AdInfoWindow;
		var tempMarker = this.marker;
		var tempAd = this;

		google.maps.event.addListener(this.marker, 'click', function() {
			
			//set previous active icon to pasif
			if(activeMarker!=null)
				activeMarker.setIcon(visitedIconUrl);
				
			//set active marker to current marker
			activeMarker = tempMarker;
			
			//set current icon to active
			activeMarker.setIcon(activeIconUrl);
			
			showAdDetails(Id);

			//only add if it is not already in the list
			if(isVisited == false) {
				var visitedAdIds = getCookie('visitedAdIds');
				if(visitedAdIds == undefined || visitedAdIds == "")
					visitedAdIds = ",";
				visitedAdIds += Id + ",";
				setCookie('visitedAdIds', visitedAdIds, 365);
			}
			//setCookie('visitedAdIds', '', 0);
			return;
			
			
			if(lastOpenedInfoWindow)
				lastOpenedInfoWindow.close();

			if(tempInfoWindow != lastOpenedInfoWindow) {
				tempInfoWindow.open(myMap, tempMarker);
				lastOpenedInfoWindow = tempInfoWindow;
			} else {
				lastOpenedInfoWindow = null;
			}
		});
		return;
		
		this.CreateInfoWindowContent = function() {
			var strOut = '';
			strOut += "id:" + this.id + "<br/>";
			strOut += "type:" + this.type + "<br/>";
			strOut += "price:" + this.price + "<br/>";
			strOut += "area:" + this.area + "<br/>";
			strOut += "rooms:" + this.rooms + "<br/>";
			strOut += "bathrooms:" + this.bathrooms + "<br/>";
			strOut += "labels:" + this.labels + "<br/>";

			return strOut;
		}
		this.AdInfoWindow = new google.maps.InfoWindow({
			content : this.CreateInfoWindowContent(),
			disableAutoPan : true
		});
		
		/*
		 google.maps.event.addListener(this.marker, 'mouseover', function() {
		 return;
		 if(tempInfoWindow != lastOpenedInfoWindow) {
		 tempInfoWindow.open(myMap, tempMarker);
		 lastOpenedInfoWindow = tempInfoWindow;
		 } else {
		 lastOpenedInfoWindow = null;
		 }
		 });

		 google.maps.event.addListener(this.marker, 'mouseout', function() {
		 return;
		 if(lastOpenedInfoWindow)
		 lastOpenedInfoWindow.close();
		 });
		 */
		var strOut = '';
		strOut += "id:" + this.id + "<br/>";
		strOut += "type:" + this.type + "<br/>";
		strOut += "price:" + this.price + "<br/>";
		strOut += "area:" + this.area + "<br/>";
		strOut += "rooms:" + this.rooms + "<br/>";
		strOut += "bathrooms:" + this.bathrooms + "<br/>";
		strOut += "labels:" + this.labels + "<br/>";

		google.maps.event.addListener(this.marker, 'click', function() {
			showAdDetails(Id);
		});
	}
