var gbase = {};
var gbaseLinks = {};
var baseURL = '';
var baseTotal = '';
var gBaseMarkers = {'total' : 0};

gbase.controller =  function(suburb,state,proptype) { this.init(suburb,state,proptype) };
jQuery.extend(gbase.controller.prototype, {
	init : function(suburb,state,proptype) {
		this.suburb = suburb;
		this.state = state;
		this.proptype = proptype;
		this.country = 'australia';
		
		this.getData();
	},

	getData : function(){
		jQuery.ajax({
			url			: this.getURL(), 
			dataType	: "jsonp",
			jsonp		: "callback",
			contentType : "application/json; charset=utf-8",
			start		: function(){
				jQuery('#map_status').html("<span id='loading' style='min-width: 150px; width: 100%; background-color: #FFFFFF; color: #000000;'><img src='/images/loader_blue.gif' alt='Loading Data' /> Loading Base...<\/span>");
				jQuery('#map_status').show();
			},
			error		: function(xmlHttpRequest, textStatus, errorThrown){
				//console.log('error');
				//console.log(textStatus + " " + errorThrown);
				jQuery('#map_status').fadeOut();
				// just incase the base don't work, I still need to load the markers
				//but this code shouldn't be in here...
				//markerCluster = new MarkerClusterer(map, markerClusterMarkers, {gridSize: 20, maxZoom: 14});
			},
			success		: function(data){
				try{
					var total = data.feed.openSearch$totalResults.$t;
					baseTotal = total;
		//console.log("Total : "+total);
		//				jQuery('#foundText').append('total = ' + total);
					if(parseInt(total) > 0){
						gbase.controller.prototype.createGBaseLinks(data);
						gbase.controller.prototype.createMarker(data);
					}
					//markerCluster = new MarkerClusterer(map, markerClusterMarkers, {gridSize: 20, maxZoom: 14});
				}catch(e){}
			}

		});
	},
	
	createGBaseLinks : function(data){
		// create the GBase Links
		if(data && data.feed){
			jQuery.each(data.feed.entry, 
				function(i,entry){
					try{ 
						var location = entry.g$location[0].$t;
						var link = entry.link[0].href;
						var author = entry.author[0].name.$t;
						var broker,price;
						try{ broker = entry.g$broker[0].$t;}catch(e){}
						try{ price = entry.g$price[0].$t;}catch(e){}
						
						if(price != ""){
							price = "$"+price;
						}
						
						var displayLinkName = (author != "") ? author : broker;
						displayLinkName = (displayLinkName == "") ? link.substr(0,20) : displayLinkName;
						
						if ( gbaseLinks[location] instanceof Array ){
						}else{
							gbaseLinks[location] = new Array();
						}
						
						gbaseLinks[location].push({'link':link,'displayLinkName':displayLinkName,'price':price});
					}catch(e){}
				}
			);
		}
	},
	
	createMarker : function(data){
		if(data && data.feed){
			jQuery.each(data.feed.entry, 
				function(i,entry){
					jQuery('#foundText').append('<hr/>');
					
					var location;
					try{ location = entry.g$location[0].$t;}catch(e){}
					
					try{
						if(location != "" && gbaseLinks[location]){
							var id = entry.id.$t;
							var published = entry.published.$t;
							var updated = entry.updated.$t;
							var category = entry.category[0].term;
							var title = entry.title.$t;
							var content = entry.content.$t;
							var link = entry.link[0].href;
							var goolgeLink = entry.link[1].href;
							var author = entry.author[0].name.$t;
							
							var latitude,longitude,listing_type,contact_phone,bathrooms,bedrooms,parking,listing_status;
							var image_link,agent,property_type,displayprice,price,target_country,expiration_date,broker,customer_id,item_type;
							
							//try{ location = entry.g$location[0].$t;}catch(e){}
							try{ latitude = parseFloat(entry.g$location[0].g$latitude.$t);}catch(e){latitude="";}
							try{ longitude = parseFloat(entry.g$location[0].g$longitude.$t);}catch(e){longitude="";}
							try{ listing_type = entry.g$listing_type[0].$t;}catch(e){}
							try{ contact_phone = entry.g$contact_phone[0].$t;}catch(e){}
							try{ bathrooms = parseInt(entry.g$bathrooms[0].$t);}catch(e){}
							try{ bedrooms = parseInt(entry.g$bedrooms[0].$t);}catch(e){}
							try{ parking = parseInt(entry.g$parking[0].$t);}catch(e){}
							try{ listing_status = entry.g$listing_status[0].$t;}catch(e){}
							try{ image_link = entry.g$image_link[0].$t;}catch(e){}
							try{ agent = entry.g$agent[0].$t;}catch(e){}
							try{ property_type = entry.g$property_type[0].$t;}catch(e){}
							try{ price = entry.g$price[0].$t;}catch(e){}
							try{ target_country = entry.g$target_country[0].$t;}catch(e){}
							try{ expiration_date = entry.g$expiration_date[0].$t;}catch(e){}
							try{ broker = entry.g$broker[0].$t;}catch(e){}
							try{ customer_id = entry.g$customer_id[0].$t;}catch(e){}
							try{ item_type = entry.g$item_type[0].$t;}catch(e){}
							
							if(price != ""){
								displayprice = "$"+price;
							}

							var width = (parseInt(jQuery('#map').width()) < 400) ? "300px" : "400px"; 

							var categoryHtml = "<b>"+displayprice+"</b>";
							categoryHtml += (property_type != "") ? "<br/>Category: "+ property_type : "";
							categoryHtml += "<table><tr>";
							categoryHtml += (bedrooms != "" && bedrooms > 0)   ? "<td>"+bedrooms+"&nbsp;<img src='/images/bed.gif' alt='Bed' align='absmiddle'/></td>" : "";
							categoryHtml += (bathrooms != "" && bathrooms > 0) ? "<td>"+bathrooms+"&nbsp;<img src='/images/bath.gif' alt='Bath' align='absmiddle'/></td>": "";
							categoryHtml += (parking != "" && parking > 0)     ? "<td>"+parking+"&nbsp;<img src='/images/car.gif' alt='Bath' align='absmiddle'/></td>": "";
							categoryHtml += "</tr></table>";

							html = "<div class='mapdata";
							html += (image_link != "") ?  " mapdatapic" : "";
							html += "' style='width:"+width+"; height:300px; overflow:auto;'";
							html += ">";
							if(image_link != ""){
								var image_source = "<img src='"+ image_link + "' align='top' height='150' width='200'/>";
								html += "<table><tr><td>"
								html += image_source + "<br/>";
								html += "</td><td valign='middle'>";
								html += categoryHtml;
								html += "</table>";
							}
							html += "<b>"+location+"</b>";
							
							html += (image_link == "") ? "<br/>" +categoryHtml : "";

							html += "<div style='font-size:11px;line-height:95%'><b><i>Description : </i></b>";
							html += content;
							html += "</div>";

							try{
								jQuery.each(gbaseLinks[location], 
									function(i,theLink){
										html += "<br/><a href='" + theLink.link + "' target='_blank' rel='nofollow' onclick='gbase.controller.prototype.baselink(this)'>"+theLink.displayLinkName+"</a> "+theLink.price;
									}
								);
							}catch(e){}
							
							html += "</div>";
							html += "</div>";
							html += "<span style='font-size:8px;color:#C8C8C8;font-style:italic;'>Information supplied from Google Base</span>";
					
							if(latitude != "" && longitude != ""){
								var point = new GLatLng(latitude,longitude);
								var icon = gbase.controller.prototype.getIcon(property_type,bedrooms);
								var marker = createPropertyMarker(point,displayprice,html,icon);
								
								gBaseMarkers[gBaseMarkers.total] = {	'bedrooms' : bedrooms,
													'bathrooms' : bathrooms,
													'parking' : parking,
													'category' : property_type.toLowerCase(),
													'pricegroup' : gbase.controller.prototype.getPriceGroup(price).toUpperCase(),
													'marker' : marker,
													'icon' : icon,
													'point' : point
												};
												
								//category_markers[property_type][] = marker;
								map.addOverlay(gBaseMarkers[gBaseMarkers.total].marker);
								gBaseMarkers.total++;
								//markerClusterMarkers.push(marker);
							}
							delete gbaseLinks[location];
						}
					}catch(e){
						//console.log("Error");
						//console.log(e);
					}
				}
			);
		}
		jQuery('#map_status').fadeOut();
		gbase.controller.prototype.addClickEvents();
		//gbase.controller.prototype.toggleMarkers();
	},
	toggleMarkers : function(){
		jQuery.each(gBaseMarkers, 
			function(i){
				try{
					var id = parseInt(i);
					
					gBaseMarkers[id].marker.hide();
					map.removeOverlay(gBaseMarkers[id].marker);
						
					var displayCategory = gbase.controller.prototype.checkActionCategories(gBaseMarkers[id].category);
					var displayPrice = gbase.controller.prototype.checkActionPrice(gBaseMarkers[id].pricegroup);
					var displayBedrooms = gbase.controller.prototype.checkActionBedrooms(gBaseMarkers[id].bedrooms);
					
					if(displayCategory == true && displayPrice == true && displayBedrooms == true){
						if(gBaseMarkers[id].marker.isHidden()){
							gBaseMarkers[id].marker.show();
							map.addOverlay(gBaseMarkers[id].marker);
						}
					}else{
						gBaseMarkers[id].marker.hide();
						map.removeOverlay(gBaseMarkers[id].marker);
					}
					
				}catch(e){
					//console.log("Error");
					//console.log(e);
				}
			}
		);
	},

	checkActionCategories :  function(checkCategory){
		var found = false;
		jQuery.each(jQuery(document.map_form.cat).parents("td"), 
			function(i, td){
				var checked = td.childNodes[0].checked;
				var category = td.childNodes[3].wholeText;
				category = category.replace(/(^\s*|\s*$)/, "");
				category = category.toLowerCase()
				if(checkCategory == category && checked == true){
					found=true;
				}
			}
		);
		return found;
	},
	checkActionPrice : function(checkPrice){
		var found = false;
		jQuery.each(jQuery(document.map_price_form.display_price).parents("td"), 
			function(i, td){
				var checked = td.childNodes[0].checked;
				var pricegroup = td.childNodes[1].wholeText;
				pricegroup = pricegroup.replace(/(^\s*|\s*$)/, "");
				pricegroup = gbase.controller.prototype.getPriceText(pricegroup);
				if(checkPrice == pricegroup && checked == true){
					found=true;
				}
			}
		);
		return found;
	},
	checkActionBedrooms : function(checkBedrooms){
		var found = false;
		jQuery.each(jQuery(document.map_room_form.display_room).parents("td"), 
			function(i, td){
				var checked = td.childNodes[0].checked;
				var bedrooms = td.childNodes[1].wholeText;
				bedrooms = bedrooms.replace(/(^\s*|\s*$)/, "");
				if(checkBedrooms == bedrooms && checked == true){
					found=true;
				}
			}
		);
		return found;
	},

	addClickEvents : function (){
		jQuery.each(jQuery(document.map_form.cat),
			function(i, input){
				jQuery(input).click(function () { 
					gbase.controller.prototype.toggleMarkers();  
				});
			}
		);
		
		jQuery.each(jQuery(document.map_price_form.display_price),
			function(i, input){
				jQuery(input).click(function () { 
					gbase.controller.prototype.toggleMarkers(); 
				});
			}
		);
		
		jQuery.each(jQuery(document.map_room_form.display_room),
			function(i, input){
				jQuery(input).click(function () { 
					gbase.controller.prototype.toggleMarkers(); 
				});
			}
		);
	},
	
	getIcon : function(category,num_rooms){
		category = category.toLowerCase();

		var baseIcon = new GIcon();
		baseIcon.shadow = "/mapsicons/shadow50.png";
		baseIcon.iconSize = new GSize(23, 39);
		baseIcon.iconAnchor = new GPoint(9, 39);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);

		var star = "s";

		var display_num;
		// Create the coloured markers
		if(category == "house") 					{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/iconb"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/iconb" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "apartment") 			{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icong"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icong" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "unit") 				{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon1"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon1" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "townhouse") 			{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon2"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon2" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "land") 				{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon3"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon3" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "villa") 				{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon4"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon4" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "unit-apmt") 			{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon5"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon5" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "acreage-semi-rural")	{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon6"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon6" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "duplex-semi-detached"){ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon7"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon7" + star + ".png", null, baseIcon.shadow);}
		}else if(category == "rural") 				{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon8"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon8" + star + ".png", null, baseIcon.shadow);}
		}else 										{ if (num_rooms >= "1" && num_rooms <= "9"){ display_num = new GIcon(baseIcon, "/mapsicons/icon9"+ num_rooms + star +".png", null, baseIcon.shadow);	}else{ display_num = new GIcon(baseIcon, "/mapsicons/icon9" + star + ".png", null, baseIcon.shadow);}
		}

		return display_num;
	},

	baselink : function(value){
		var url = "/outgoingBase/"+value.href;
		urchinTracker(url);
	},

	getURL : function(){
		// there is still a difference between the API call and the google real estate at the moment
		var url = "http://www.google.com/base/feeds/snippets/?bq=";
		url += "[location:@\""+this.suburb+", "+this.state+", "+this.country+"\"]";
		if(this.proptype == "buy"){
			url += "[listing_type%3Asale]"
		}else if(this.proptype == "rent"){
			url += "[listing_type%3Arent]"
		}else{
			url += "[listing_type%3Aroom%20for%20rent]"
		}
		url += "[item%20type%3Ahousing]";
		url += "&content=geocodes&alt=json-in-script&max-results=250";
		//console.log(url);
		baseURL = url;
		return url;
	},
	
	getPriceGroup : function (price){
		var priceGroup = "A";
		price = parseInt(price);
		
		if(display_type == "buy"){
			//"A", "No Price Listed"
			if(price < 100000 && price > 0){				priceGroup = "B";//"B", "Under $100,000"
			}else if(price >= 100000 && price < 200000){	priceGroup = "C";//"C", "$100,000-$200,000"
			}else if(price >= 200000 && price < 300000){	priceGroup = "D";//"D", "$200,000-$300,000"
			}else if(price >= 300000 && price < 400000){	priceGroup = "E";//"E", "$300,000-$400,000"
			}else if(price >= 400000 && price < 500000){	priceGroup = "F";//"F", "$400,000-$500,000"
			}else if(price >= 500000 && price < 600000){	priceGroup = "G";//"G", "$500,000-$600,000"
			}else if(price >= 600000 && price < 700000){	priceGroup = "H";//"H", "$600,000-$700,000"
			}else if(price >= 700000 && price < 800000){	priceGroup = "I";//"I", "$700,000-$800,000"
			}else if(price >= 800000 && price < 900000){	priceGroup = "J";//"J", "$800,000-$900,000"
			}else if(price >= 900000 && price < 1000000){	priceGroup = "K";//"K", "$900,000-$1 Million"
			}else if(price >= 1000000){						priceGroup = "L";//"L", "Above $1 Million"
			}
		}else{
			"A", "No Price Listed"
			if(price < 100 && price > 0){				priceGroup = "B";//"B", "Under $100"
			}else if(price >= 100 && price < 200){		priceGroup = "C";//"C", "$100-$200"
			}else if(price >= 200 && price < 300){		priceGroup = "D";//"D", "$200-$300"
			}else if(price >= 300 && price < 400){		priceGroup = "E";//"E", "$300-$400"
			}else if(price >= 400 && price < 500){		priceGroup = "F";//"F", "$400-$500"
			}else if(price >= 500 && price < 600){		priceGroup = "G";//"G", "$500-$600"
			}else if(price >= 600 && price < 700){		priceGroup = "H";//"H", "$600-$700"
			}else if(price >= 700 && price < 800){		priceGroup = "I";//"I", "$700-$800"
			}else if(price >= 800 && price < 900){		priceGroup = "J";//"J", "$800-$900"
			}else if(price >= 900 && price < 1000){		priceGroup = "K";//"K", "$900-$1,000"
			}else if(price >= 1000){					priceGroup = "L";//"L", "Above $1,000"
			}
		}
		return priceGroup;
	},
	
	getPriceText : function (price){

		var priceGroup = "A";
		price = parseInt(price);
		
		if(display_type == "buy"){
			//"A", "No Price Listed"
			if(price == "Under $100,000"){				priceGroup = "B";//"B", "Under $100,000"
			}else if(price == "$100,000-$200,000"){		priceGroup = "C";//"C", "$100,000-$200,000"
			}else if(price == "$200,000-$300,000"){		priceGroup = "D";//"D", "$200,000-$300,000"
			}else if(price == "$300,000-$400,000"){		priceGroup = "E";//"E", "$300,000-$400,000"
			}else if(price == "$400,000-$500,000"){		priceGroup = "F";//"F", "$400,000-$500,000"
			}else if(price == "$500,000-$600,000"){		priceGroup = "G";//"G", "$500,000-$600,000"
			}else if(price == "$600,000-$700,000"){		priceGroup = "H";//"H", "$600,000-$700,000"
			}else if(price == "$700,000-$800,000"){		priceGroup = "I";//"I", "$700,000-$800,000"
			}else if(price == "$800,000-$900,000"){		priceGroup = "J";//"J", "$800,000-$900,000"
			}else if(price == "$900,000-$1 Million"){	priceGroup = "K";//"K", "$900,000-$1 Million"
			}else if(price == "Above $1 Million"){		priceGroup = "L";//"L", "Above $1 Million"
			}
		}else{
			"A", "No Price Listed"
			if(price == "Under $100"){			priceGroup = "B";//"B", "Under $100"
			}else if(price == "$100-$200"){		priceGroup = "C";//"C", "$100-$200"
			}else if(price == "$200-$300"){		priceGroup = "D";//"D", "$200-$300"
			}else if(price == "$300-$400"){		priceGroup = "E";//"E", "$300-$400"
			}else if(price == "$400-$500"){		priceGroup = "F";//"F", "$400-$500"
			}else if(price == "$500-$600"){		priceGroup = "G";//"G", "$500-$600"
			}else if(price == "$600-$700"){		priceGroup = "H";//"H", "$600-$700"
			}else if(price == "$700-$800"){		priceGroup = "I";//"I", "$700-$800"
			}else if(price == "$800-$900"){		priceGroup = "J";//"J", "$800-$900"
			}else if(price == "$900-$1,000"){	priceGroup = "K";//"K", "$900-$1,000"
			}else if(price == "Above $1,000"){	priceGroup = "L";//"L", "Above $1,000"
			}
		}
		return priceGroup;
	}
});
