/**
 * @author Matthew Foster
 * @date April 25th 2008
 */
 
 AccordionSearchPanel = function(cfg){		
		AccordionSearchPanel.superclass.constructor.call(this, 
													Ext.apply(cfg,{
														layout : "accordion",
														layoutConfig : {
															titleCollapse : false,
															animate : true
														},
														items : this.buildItems()
													}));
		this.addEvents([ "websearch", "videosearch", "localsearch", "imagesearch", "newssearch"]);
		
			
	};
	
	
    Ext.extend(AccordionSearchPanel, Ext.Panel, {
		initComponent : function(){
			AccordionSearchPanel.superclass.initComponent.apply(this, arguments);
		
		},
		handleWebForm : function(form, action){
			if(!this.isValidAction(action))
				return false;
			
			this.fireEvent("websearch", form.getValues());
			return false; //cancel the fing action!		
		},
		handleVideoForm : function(form, action){
			if(!this.isValidAction(action))
				return false;
			
			this.fireEvent("videosearch", form.getValues());			
			return false;
		},
		handleLocalForm : function(form, action){
			if(!this.isValidAction(action))
				return false;
			
			this.fireEvent("localsearch", form.getValues());		
			return false;
		},
		handleImageForm : function(form, action){
			if(!this.isValidAction(action))
				return false;
			
			this.fireEvent("imagesearch", form.getValues());			
			return false;
		},
		handleNewsForm : function(form, action){
			if(!this.isValidAction(action))
				return false;
			
			this.fireEvent("newssearch", form.getValues());			
			return false;
		},
		buildItems : function(){			
			return [this.buildWebSearch(), this.buildNewsSearch(), this.buildLocalSearch(), this.buildImageSearch(), this.buildVideoSearch()];
		},
		buildWebSearch : function(){		
			this.webForm = this.createForm("Web Search");
			
			this.webForm.on("beforeaction", this.handleWebForm, this);
						
			return this.webForm;		
		},		
		buildLocalSearch : function(){		
			this.localForm = this.createForm("Local Search");
			
			this.localForm.on("beforeaction", this.handleLocalForm, this);
						
			return this.localForm;
		},
		buildImageSearch : function(){
			this.imageForm = this.createForm("Image Search");
			
			this.imageForm.on("beforeaction", this.handleImageForm, this);
						
			return this.imageForm;
		},
		buildVideoSearch : function(){
			this.videoForm = this.createForm("Video Search");
			
			this.videoForm.on("beforeaction", this.handleVideoForm, this);
						
			return this.videoForm;
		},
		buildNewsSearch : function(){
			this.newsForm = this.createForm("News Search");
			
			this.newsForm.on("beforeaction", this.handleNewsForm, this);
						
			return this.newsForm;
		},			
		createForm : function(title){
			var btn = this.createSubmitButton();
			var p = new Ext.FormPanel({
				title : title,
				items : [this.createSearchField(), btn],
				titleCollapse : true				
			});
			p.on("expand", this.handlePanelExpand, this);
			btn.on("click", function(){ p.getForm().submit() });
						
			return p;
		},		
		createSearchField : function(){			
			return new Ext.form.Field({ name : "query", hideLabel : true, itemCls : "search-input" });
		},
		createSubmitButton : function(){			
			return new Ext.Button({ text : "Search", cls : "search-button", type : "submit" });
		},
		handlePanelExpand : function(fmPanel){
			fmPanel.getForm().findField("query").focus();
		},
		isValidAction : function(action){			
			return action.type == "submit";
		}
	});
   
	var TabPanelSearchDisplay = Ext.extend(Ext.TabPanel,{
		initComponent : function(){
			TabPanelSearchDisplay.superclass.initComponent.apply(this, arguments);
			this.display = {};
			
			this.display.web = this.createWeb();
			this.display.image = this.createImage();
			this.display.local = this.createLocal();
			this.display.video = this.createVideo();
			this.display.news = this.createNews();
			
			this.add(this.display.web);
			this.add(this.display.news);
			this.add(this.display.local);
			this.add(this.display.image);
			this.add(this.display.video);
			
		},
		renderWebResult : function(result){
			this.setActiveTab(this.display.web);
			this.display.web.renderResult(result);
		},
		renderImageResult : function(result){
			this.setActiveTab(this.display.image);
			this.display.image.renderResult(result);			
		},
		renderLocalResult : function(result){
			this.setActiveTab(this.display.local);
			this.display.local.renderResult(result);
		},
		renderVideoResult : function(result){
			this.setActiveTab(this.display.video);
			this.display.video.renderResult(result);
		},
		renderNewsResult : function(result){
			this.setActiveTab(this.display.news);
			this.display.news.renderResult(result);
		},
		createWeb : function(){
			return new WebSearchDisplay({ title : "Web Search",cls : "web-display" });
		},
		createLocal : function(){
			return new LocalSearchDisplay({ title : "Local Search", cls : "local-display", autoScroll : true });
		},
		createVideo : function(){
			return new VideoSearchDisplay({ title : "Video Search", cls : "video-display" });		
		},
		createImage : function(){		
			return new ImageSearchDisplay({ title : "Image Search", layout : "column", cls : "image-display"});		
		},
		createNews : function(){
			return new NewsSearchDisplay({ title : "News Search", cls : "news-display" });		
		}
	
	});
	var SearchDisplayBase = Ext.extend(Ext.Panel, {
		
		renderResult : function(){
			throw { message : "Subclass must override renderResult method" };
		},
		renderResultItem : function(obj){
			throw { message : "Subclass must override renderResult method", obj : obj };
		},
		renderResult : function(result){
			var collection = new Ext.util.MixedCollection();
			
			for(var i = 0, l = result.length; i < l; i++)
				collection.add(this.renderResultItem(result[i]));
				
			this.purgeBody();
			
			collection.each(this.appendItem.createDelegate(this));
			
			this.lastCollection = collection;
			
		},		
		purgeBody : function(){			
			this.getEl().dom.innerHTML = "";
		},
		appendItem : function(ele){			
			this.getEl().appendChild(ele);
		}
	
	});
	
	
	var NewsSearchDisplay = Ext.extend(SearchDisplayBase, {
		renderResultItem : function(obj){
			var container = new Ext.Element(document.createElement("div"));
			var link = new Ext.Element(document.createElement("a"));
			var content = new Ext.Element(document.createElement("p"));
			var title = new Ext.Element(document.createElement("h3"));
			var publisher = new Ext.Element(document.createElement("span"));
			var related = new Ext.Element(document.createElement("a"));
			
			link.dom.setAttribute("href", obj.unescapedUrl);
			link.dom.setAttribute("target", "_blank");
			title.dom.innerHTML = obj.title;
			publisher.dom.innerHTML = obj.publisher;
			content.dom.innerHTML = obj.content;
			content.appendChild(publisher);
			if(obj.clusterUrl){
				related.dom.innerHTML = "View Related Stories";
				related.dom.setAttribute("href", obj.clusterUrl);
				content.appendChild(related);
			}
			link.appendChild(title);
			
			
			container.appendChild(link);
			container.appendChild(content);
			
			return container;		
		}	
	});
	var VideoSearchDisplay = Ext.extend(SearchDisplayBase, {
		renderResultItem : function(obj){
			var container = new Ext.Element(document.createElement("div"));
			var thumb = new Ext.Element(document.createElement("img"));
			var link = new Ext.Element(document.createElement("a"));
			var titleLink = new Ext.Element(document.createElement("a"));
			var content = new Ext.Element(document.createElement("p"));
			var title = new Ext.Element(document.createElement("h3"));
			var duration = new Ext.Element(document.createElement("span"));
			
				
			title.dom.innerHTML = obj.title;
			content.dom.innerHTML = obj.content;
			thumb.dom.setAttribute("src", obj.tbUrl);
			link.dom.setAttribute("href", obj.url);
			link.dom.setAttribute("target", "_blank");
			titleLink.dom.setAttribute("href", obj.url);
			titleLink.dom.setAttribute("target", "_blank");
			link.addClass("thumb");
			//thumb dimensions are simply incorrect to the original image and more often than not way too large for the display.
			//thumb.dom.setAttribute("height", obj.tbHeight + "px");
			//thumb.dom.setAttribute("width", obj.tbWidth + "px");
			
			duration.dom.innerHTML = this.formatDuration(obj.duration);
			
			link.appendChild(thumb);
			content.appendChild(duration);
			titleLink.appendChild(title);
			
			container.appendChild(link);
			container.appendChild(titleLink);		
			container.appendChild(content);
			
			return container;		
		},
		formatDuration : function(sec){
			var h = Math.floor(sec / 3600);
			var r = sec % 3600;
			var m = Math.floor(r / 60);
			var s = r % 60;
			var str = "0" + h + ":" + ((m < 10) ? "0" + m : m) + ":"+ ((s < 10) ? "0" + s : s);
			return str;
		}	
	});
	
	var WebSearchDisplay = Ext.extend(SearchDisplayBase, {
			
		renderResultItem : function(obj){
			var container = new Ext.Element(document.createElement("div"));
			var title = new Ext.Element(document.createElement("h3"));
			var titleLink = new Ext.Element(document.createElement("a"));
			var description = new Ext.Element(document.createElement("p"));
			var viewLink = new Ext.Element(document.createElement("span"));
			
			title.dom.innerHTML = obj.title;
			titleLink.dom.setAttribute("href", obj.unescapedUrl);
			titleLink.dom.setAttribute("target", "_blank");
			description.dom.innerHTML = obj.content;
			
			viewLink.dom.innerHTML = obj.visibleUrl;
			
			titleLink.appendChild(title);
			container.appendChild(titleLink);
			container.appendChild(description);
			container.appendChild(viewLink);
			
			return container;	
		}
		
	});
	var ImageSearchDisplay = Ext.extend(SearchDisplayBase, {
			
		renderResultItem : function(obj){
			var container = new Ext.Element(document.createElement("div"));
			var titleLink = new Ext.Element(document.createElement("a"));
			var title = new Ext.Element(document.createElement("h3"));
			var description = new Ext.Element(document.createElement("p"));
			var image = new Ext.Element(document.createElement("img"));
			var imageLink = new Ext.Element(document.createElement("a"));
			
			title.dom.innerHTML = obj.title;
			titleLink.dom.setAttribute("href", obj.originalContextUrl);
			titleLink.dom.setAttribute("target", "_blank");
			imageLink.dom.setAttribute("href", obj.unescapedUrl);
			imageLink.dom.setAttribute("target", "_blank");
			imageLink.addClass("thumb");
			description.dom.innerHTML = obj.content;
			image.dom.setAttribute("src", obj.tbUrl);
			image.dom.setAttribute("height", obj.tbHeight + "px");
			image.dom.setAttribute("width", obj.tbWidth + "px");
			
			imageLink.appendChild(image);
			titleLink.appendChild(title);
						
			container.appendChild(titleLink);
			container.appendChild(imageLink);
			container.appendChild(description);			
			
			return container;	
		}
		
	});
	
	var LocalSearchDisplay = Ext.extend(SearchDisplayBase, {
		
		render : function(){
			LocalSearchDisplay.superclass.render.apply(this,arguments);
			
			this.body.appendChild(this.buildMapContainer());
			this.body.appendChild(this.buildList());
			this.buildGMap(this.mapContainer.dom);
		},
		buildMapContainer : function(){
			if(this.mapContainer)
				return this.mapContainer;
				
			this.mapContainer = new Ext.Element(document.createElement("div"));
			this.mapContainer.setStyle("width", "100%");
			this.mapContainer.setStyle("height", "300px");
		
			return this.mapContainer;
		},
		buildList : function(){
			if(this.list)
				return this.list;
				
			this.list = new Ext.Element(document.createElement("ul"));
			
			return this.list;			
		},
		buildGMap : function(dom){
			if(this.map)
				return this.map;
			
			this.map = new GMap2(dom);
			this.map.addControl(new GLargeMapControl());
			this.map.addControl(new GMapTypeControl());
								
			this.map.setCenter(new GLatLng(40.9799, -95.8008), 3);
			this.map.enableScrollWheelZoom();
			return this.map;
		},
		handleMarkerClick : function(li, marker){
			marker.openInfoWindow(li.dom.cloneNode(true));		
		},
		handleListItemClick : function(li, marker){
			marker.openInfoWindow(li.dom.cloneNode(true));		
		},
		renderResult : function(result){
			var listCollection = new Ext.util.MixedCollection();
			var markerCollection = new Ext.util.MixedCollection();
			var pointArr = [];
			
			for(var i = 0, l = result.length; i < l; i++){
				var listItem = this.renderListItem(result[i]);
				var marker = this.renderMarker(result[i]);
				pointArr.push(marker.getLatLng());
				listItem.on("click", this.handleListItemClick.createDelegate(this, [listItem, marker]));
				GEvent.addListener(marker, "click", this.handleMarkerClick.createDelegate(this, [listItem, marker]));		
				listCollection.add(listItem);
				markerCollection.add(marker);			
			}
			this.purge();
			listCollection.each(this.appendListItem.createDelegate(this));
			markerCollection.each(this.appendMarker.createDelegate(this));
			this.adjustMap(pointArr);
		},
		renderListItem : function(obj){
			var ele = new Ext.Element(document.createElement("li"));
			var titleSpan = new Ext.Element(document.createElement("h3"));
			var urlLink = new Ext.Element(document.createElement("a"));
			titleSpan.dom.innerHTML = obj.title;
			urlLink.dom.setAttribute("href", obj.url);
			urlLink.dom.setAttribute("target", "_blank");
			urlLink.dom.innerHTML = "View on Large Map";
			ele.appendChild(titleSpan);
			ele.appendChild(urlLink);
			return ele;		
		},
		adjustMap : function(points){
			if(points.length <= 0)
				return false;
			
			var bounds = new GBounds(points);
			
			var ne = new GLatLng(bounds.maxY, bounds.maxX);
			
			var sw = new GLatLng(bounds.minY, bounds.minX);			
			
			var latLng = new GLatLngBounds(sw, ne);
			
			var center = latLng.getCenter();
			
			var zoom = this.map.getBoundsZoomLevel(latLng);
			this.map.setCenter(center, zoom); 		
		},
		renderMarker : function(obj){
			return new GMarker(new GLatLng(obj.lat, obj.lng));
		},
		appendMarker : function(marker){
			this.map.addOverlay(marker);
		},
		appendListItem : function(ele){
			this.list.appendChild(ele);		
		},
		purgeMap : function(){
			this.map.clearOverlays();
		},
		purgeList : function(){
			this.list.dom.innerHTML = ""
		},
		purge : function(){
			this.purgeMap();
			this.purgeList();
		}
	});