
/*
*	Model component: Item lists
*/

var Items = {
	
	//Markers array
	markers : new Array(),
	
	//number of items in view
	numberOfRows : 0,
	displayMode : 0, //1 for just cities
	
	//list of loaded items
	//Hashtable item (static list)
	items : new Array(),
	
	//Item lookup by item id
	itemLookup : new Array(),  
	
	//List of tags
	tags : new Object(),
	
	//Last comments to be loaded (cached)
	last_comments : new Array(), 
	
	/***************************************************************************************
	****************	INIT SECTION
	***************************************************************************************/
	init : function() {
		
		//Init markers  -- create markers and add to map
		var MAX_MARKERS = 60;
		
		Items.markers = new Array(MAX_MARKERS);
		for (var i = 0; i < MAX_MARKERS; i++){
			
			var label = new SpeechMarker(0, new GLatLng (180,180) );
			label.id = i;
			label.ms_item_id = -1;
			Items.markers[i] = label;

			MS.map.addOverlay(label);
		}
	},
	
	/***************************************************************************************
	****************	LOAD SECTION
	***************************************************************************************/

	/*
	*  Make api call to load data... given bounds and tags
	*/
	load_data : function(x1, y1, x2, y2, tags){
		var page = Items.page;
		
		var request = {
			'x1' : x1,
			'x2' : x2,
			'y1' : y1,
			'y2' : y2,
			'tags' : tags,
			'zoom' : MS.map.getZoom()
		};
		//If finding bounds. Need to scan entire globe
		if ((State.autobounds) || (State.autocenter)){
			request.zoom = 1;
			request.x1 = -180;
			request.x2 = 180;
			request.y1 = -90;
			request.y2 = 90;
		}
		
		var url = '/interface/get.php';
		MS.setStatus('Loading new markers...', true);
		Conn.doGet(url, request, Items.load_data_finished);
	},
	
	/*
	*  Callback function when loading data
	*  Process items, geoplaces
	*/
	load_data_finished : function(jsonText){
				
		MS.setStatus(Status.showStatusMessage);
		Status.showStatusMessage = '';
		//MS.debug(jsonText);
		var response = eval('(' + jsonText + ')');
		//MS.debug(jsonText);
		//Get items
		Items.items = response['items'];
		Items.numberOfRows = response['rows'];
		
		Status.setNumNewMessages(response['newMessages']);
		
		//Clear the item_id -> item array lookup
		delete Items.itemLookup;
		Items.itemLookup = new Array();
		
		var itemIndex = Items.items.length-1;  	//Count backwards on loaded items. 
		
		displayMode = 1;
		//Puts most commented ones at top		
		//for each item
		for (var i = 0; (itemIndex >= 0) && (i < Items.markers.length) ; i++){
			var itm = Items.items[itemIndex];
			
			displayMode = displayMode * itm['type'];
			
			var img = (itm['tmb_path'] == null) ? '' : itm['tmb_path'];

			if (itm['type'] == 1) img = '';
			
			Markers.updateMarker(Items.markers[i], itm['item_id'], itm['title'], itm['lng'], itm['lat'], img, itm['type'], itm['cat']);	
			
			//Pre split tags
			itm.stags = itm.tags.split(" ,");
			itm.tags = ','+itm.tags + ' ,';

			if (itm.mycon_url == null) itm.mycon_url = '/images/icons/unknownuser.gif';

			//Add to lookup
			Items.itemLookup[itm['item_id']] = itemIndex;
			
			itm.inTags = true; //Need to check?
			itm.inBounds = true; 
			
			//index of item (self id)
			itm.iIndex = itemIndex;
			//index of related marker
			itm.mIndex = i;
			
			itemIndex--;
		}
		
		Items.displayMode = displayMode;
		
		for (i =i; i< Items.markers.length; i++){
			Markers.updateMarker(Items.markers[i], -1 , '', 1000,1000, '', 0, 0);
		}
		
		//If I am not dragging, then update the map
		//(if I am dragging, assume the drag event will do this fo us)
		if (!Explore.dragging){
			Items.filterBounds();
			Items.calcTags();
			
			UI.updateAsContentChanged();	

		}
		
		//Autopopup
		if (State.autopopid > 0){
			var autopopid = State.autopopid;
			var marker_id = Items.getMarkerIndex(autopopid);
			Markers.openWindow(marker_id, ItemInfo.getInfowindowHTML(autopopid));
			State.autopopid = null;
		}
		
		//Autobonuds and autocenter
		if (State.autocenter || State.autobounds){
			var bounds = Items.getBoundsAndCenter();
			var center = MS.map.getCenter();
			var zoom = MS.map.getZoom();
			//alert(zoom);
			if (State.autocenter) center = new GLatLng(bounds.lat, bounds.lng);
			
			if (State.autobounds){
				var minP = new GLatLng(bounds['minlat'], bounds['minlng']);
				var maxP = new GLatLng(bounds['maxlat'], bounds['maxlng']);
				var gb = new GLatLngBounds(minP, maxP);
				zoom = Math.max(MS.map.getBoundsZoomLevel(gb)-1, 1);
			}
			
			State.autobounds = false;
			State.autocenter = false;
			
			Explore.suppressLoading();
			MS.map.setCenter(center, zoom);
			Explore.allowLoading();
		} 
	},
	
	/*
	*	Work out which items are in viewport
	*/
	filterBounds : function(){
		var bounds = MS.map.getBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		
		var x1 = sw.lng();
		var y1 = sw.lat();
		var x2 = ne.lng();
		var y2 = ne.lat();
		var sum = 0;
		
		for (var  i = Items.items.length-1; i >= 0; i--){
			var itm = Items.items[i];
			var px = itm.lng;
			var py = itm.lat;
			
			itm.inBounds = inside(px,py, x1, x2, y1, y2);
			
			if (itm.inBounds) sum += itm.item_id;
		}

		return sum;
	},
	
	/***************************************************************************************
	****************	LOOKUPS SECTION
	***************************************************************************************/
	
	getItemById : function(item_id){
		return Items.items[Items.itemLookup[item_id]];
	},
	
	getMarkerIndex : function(item_id){
		var itm = Items.getItemById(item_id);
		return itm.mIndex;
	},
	
	getMarkerForItem : function(item_id){
		return Items.markers[Items.getMarkerIndex(item_id)];
	},
	
	/***************************************************************************************
	****************	DATA PROCESSING SECTION
	***************************************************************************************/
	
	/*
	* 	Calculate tags and scores from item list
	*	Group tags by tagname and score... For each item in viewport
	*/
	calcTags : function() {
		var outTags = new Object();

		for (var i = Items.items.length-1; i >= 0 ; i--){
			var itm = Items.items[i];

			if ((itm.inBounds) && (itm.type==0)){ //&& itm.inTags
				var tags = itm.stags;
				
				for (var j = tags.length-1; j >=0 ;j--){
					var tag = tags[j];	
					
					if (typeof outTags[tag] == 'undefined'){
						outTags[tag] = 1;
					} else {
						outTags[tag] ++; 
					}
				}
			}
		}
		/*
		for (headertag in UIconfig.tagLookup){	
			outTags[headertag] = -1;
		}
		*/	
		Items.tags = outTags;
		delete outTags;
		delete tagLookup;	
	},
	
	/*
	*	Return center point and bounds for current items
	*/
	getBoundsAndCenter : function(){
		
		var ret = {
			lat : 0,
			lng : 0,
			maxlat: -1000,
			minlat: 1000,
			maxlng: -1000,
			minlng: 1000
		}
		
		for (var i = Items.items.length-1; i >= 0 ; i--){
			var item = Items.items[i];
			var lat = parseFloat(item.lat);
			var lng = parseFloat(item.lng);
			
			ret.lat += lat;
			ret.lng += lng;
			
			ret.minlng = Math.min(lng, ret.minlng);
			ret.maxlng = Math.max(lng, ret.maxlng);
			ret.minlat = Math.min(lat, ret.minlat);
			ret.maxlat = Math.max(lat, ret.maxlat);
		}
		
		ret.lat = ret.lat / Items.items.length;
		ret.lng = ret.lng / Items.items.length;
		
		
		return ret;
	},
	
	/***************************************************************************************
	****************	AJAX SECTION
	***************************************************************************************/
	
	moveItem : function(item_id, point){

		
		var lat = point.lat();
		var lng = point.lng();
		
		var itm = Items.getItemById(item_id);
		itm.lat = lat;
		itm.lng = lng;
		
		var marker = Items.getMarkerForItem(item_id);
		marker.setPosition(point);
		Markers.postionAllMarkers();
		
		Items.saveItem(itm);
		
		Explore.allowLoading();
		State.mode = State.MODE_EXPLORE;
		MS.setStatus('');
	},
	
	saveItem : function(itm){
		
		var url = '/interface/set.php?mssource='+MS.source;
		
		var data = 
		{
			"id": itm['item_id'], "title": itm['title'],"body": itm['body'],
			"tags" : itm['tags'], "systags" : itm['systags'], "lng": itm['lng'], "lat": itm['lat'], "link" : itm['link']
		};

		//Stop adding two or more!
		if ($('add_item_button')) 
				$('add_item_button').setAttribute('onclick', 'return false;');

		MS.setStatus("Saving...", true);
		
		Conn.doPost(url, data,
			function(text){
				//Markers.closeWindow();

				if (State.mode == State.MODE_ADD){
					Explore.clearAllTags();
					SearchBox.searchCleared();
					CategoryList.closeAll();
					
					//Explore.doload(true);
					var id = eval(text);

					State.autopopid = id; //Popup speech bubble after posting

					UI.setTab(UIConfig.getAddItemTab());

					Explore.cancelAddItem();
				}
			}
		);
	}
};
