/*
 * design and program by deny fauzi
 * copyright 2011 PT Infomedia Nusantara - Data Management
 * program version b0.1
 */
var markers = [];
var map;
var origin;
var destination;
var waypoints;
var markersDir;
var directionsDisplay;
var directionsService;
var directionsVisible;

$(function(){
	Ext.QuickTips.init();
	var infoPanel = new Ext.Panel({id:'infoPanel', border:false, width:310, autoHeight:true, bodyStyle:'background:none', applyTo:'infoContent', html:''});
	var detilPanel = new Ext.Panel({id:'detilPanel', border:false, width:310, autoHeight:true, bodyStyle:'background:none', applyTo:'detilContent', html:''});
	
	var hs = new Ext.form.TextField({
		enableKeyEvents:true, hideLabel:true, id:'homeSearch', width:298, emptyText:'Type keywords here...', minLength:3, margins:'0 0 0 0',
		listeners:{
			'specialkey':function(f, e){
				if(e.getKey()==e.ENTER){
					if(this.getValue().length >= 3){
						ozieStore.load({params:{start:0, limit:10, 'req':'search', 'freeText':this.getValue()}});
						ozieStore.setDefaultSort('a', 'asc');
					}else{
						Ext.Msg.alert('value', 'Minimum key atleast must be three character');
					}
				}
			}
		}
	});
	hs.on('focus', function(){
		Ext.getCmp('dirPanel').collapse();
		Ext.getCmp('nearPanel').collapse();
		Ext.getCmp('navPanel').expand();
	});
	//=================================================================================================================================================== Buttons
	var goButton = {
		xtype:'button', iconCls:'goSearch', id:'goButton', tooltip:'<b>Search</b> info',
		handler:function(){
			if(hs.getValue().length>=3){
				ozieStore.load({params:{start:0, limit:10, 'req':'search', 'freeText':Ext.getCmp('homeSearch').getValue()}});
				ozieStore.setDefaultSort('a', 'desc');
			}
		}
	};
	var reButton = {xtype:'button', iconCls:'refreshBtn', id:'reButton', tooltip:'<b>Refresh</b><br />Clear all search info and options',
		handler:function(){
			clearAll();
			ozieStore.reload({params:{'req':'clear'}});
		}
	};
	var advButton = {
		xtype:'button', iconCls:'btnAdvSrc', id:'advButton', enableToggle:true, tooltip:'<b>Advance Search</b><br />Search info with more options',
		listeners:{
			'click':function(){
				if(this.pressed==true){
					Ext.getCmp('navPanel').collapse(); Ext.getCmp('dirPanel').collapse(); Ext.getCmp('nearPanel').expand();
					clearAll();
					
				}else{
					Ext.getCmp('nearPanel').collapse();
				}
			}
		}
	};
	var nearButton = {
		xtype:'button', id:'nearButton', text:'Nearby', iconCls:'nearByBtn', enableToggle:true, tooltip:'<b>Quick Nearby</b><br />Search info based on entire lon/lat point',
		listeners:{
			'click':function(){
				if(this.pressed==true){
					Ext.getCmp('navPanel').collapse();
					Ext.getCmp('dirPanel').collapse();
					Ext.getCmp('nearPanel').expand();
					google.maps.event.addListener(map, 'click', function(event){
						Ext.getCmp('nX').setValue(event.latLng.lng()); Ext.getCmp('nY').setValue(event.latLng.lat());
						ozieAddMarker(event.latLng);
						google.maps.event.clearListeners(map, 'click');
					});
				}else{
					google.maps.event.clearListeners(map, 'click');
					Ext.getCmp('nearPanel').collapse();
				}
			}
		}
	};
	var dirButton = {
		xtype:'button', id:'dirButton', text:'Direction', iconCls:'direction', enableToggle:true, tooltip:'Find way wich the shortest path',
		listeners:{
			'click':function(){
				if(this.pressed==true){
					Ext.getCmp('navPanel').collapse();
					Ext.getCmp('nearPanel').collapse();
					Ext.getCmp('dirPanel').expand();
					
					google.maps.event.addListener(map, 'click', function(event){
						if (origin == null) {
					        origin = event.latLng;
					        addMarker(origin);
					      } else if (destination == null) {
					        destination = event.latLng;
					        addMarker(destination);
					      } else {
					        if(waypoints.length < 9){
					          	waypoints.push({ location: destination, stopover: true });
					          	destination = event.latLng;
					          	addMarker(destination);
					        }else{
					          	Ext.Msg.alert('  ', 'Maximum number of way points reached');
					        }
					      }
					});
				}else{
					Ext.getCmp('dirPanel').collapse();
				}
			}
		}
	};
	
	var nX = new Ext.form.Hidden({id:'nX', name:'x'});
	var nY = new Ext.form.Hidden({id:'nY', name:'y'});
	var ns = new Ext.form.Hidden({id:'ns'});
	var nv = new Ext.form.Hidden({id:'nv'});
	var srcAdvance = {
		text:'Search', id:'advanceSearch', iconCls:'btnAdvSrc',
		handler:function(){
			ozieStore.load({params:{'req':'search', 'x':Ext.getCmp('nX').getValue(), 'y':Ext.getCmp('nY').getValue(), 's':Ext.getCmp('ns').getValue(), 'sv':Ext.getCmp('nv').getValue(), 'freeText':Ext.getCmp('homeSearch').getValue()}});
			ozieStore.setDefaultSort('a', 'desc');
			Ext.getCmp('nearPanel').collapse();
			Ext.getCmp('navPanel').expand();
		}
	};
	var rfsAdvance = {
		text:'Reset', iconCls:'refreshBtn', tooltip:'Refresh form',
		handler:function(){
			//clearAll()
			alert('x:'+Ext.getCmp('nX').getValue()+' y:'+Ext.getCmp('nY').getValue()+' s:'+Ext.getCmp('ns').getValue()+' sv:'+Ext.getCmp('nv').getValue());
		}
	};
	
	var mapShare = {
			xtype:'buttongroup', id:'socialNetwork', title:'Share',
			items:[{text:'Social Networks', iconCls:'netso', scale: 'small', tooltip:'<b>Share</b><br />Share map to your social network',
	            	menu:[{
	            			text:'Facebook', iconCls:'fb'
	            		  },{
	            	        text:'Twitter', iconCls:'tw',
	            	        handler:function(){
	            	        	//winshare('twitter');
	            	        }
	            	      }
	            	]
	        	},{
					text:'eMail', iconCls:'mail', tooltip:'<b>eMail</b><br />Mail this map',
					handler:function(){
						Ext.MessageBox.prompt('Mail to', 'Example: yourfriend@mail.com. Separated by ;', function(btn, text){
							if(btn == 'ok'){
								location.href = 'mailto:'+text;
							}
						});
					}
			}]
	};
	//=========================================================================================================== store
	var selector = new Ext.data.JsonStore({
		proxy: new Ext.data.HttpProxy({
			url:myurl()+'/control/Search.php?req=select', method:'GET'
		}),
	    root:'users', totalProperty:'total', fields:['params']
	});
	
	var ozieStore = new Ext.data.GroupingStore({
		id:'ozieStore',
		proxy: new Ext.data.HttpProxy({
			url:myurl()+'/control/Search.php', method: 'POST'
		}), //defaultParamNames 
		groupField:'g',
		baseParams:{req:'search', start:0, limit:10},
		reader: new Ext.data.JsonReader(
				{root:'object', totalProperty:'count'},
				  [ 
				    {name:'a', type:'string'}, {name:'b', type:'string'}, {name:'c', type:'string'},
				    {name:'d', type:'string'}, {name:'e', type:'string'}, {name:'f', type:'string'},
				    {name:'g', type:'string'}, {name:'h', type:'string'}, {name:'i', type:'string'},
				    {name:'j', type:'string'}, {name:'k', type:'string'}, {name:'l', type:'string'},
				    {name:'m', type:'string'}, {name:'n', type:'string'}, {name:'o', type:'string'},
				    {name:'p', type:'string'}, {name:'q', type:'string'}, {name:'r', type:'string'},
				    {name:'s', type:'string'}, {name:'t', type:'string'}, {name:'u', type:'string'},
				    {name:'v', type:'string'}, {name:'w', type:'string'}
			      ]
		)
	});
	
	var barOzie = new Ext.PagingToolbar({
		id:'barOzie', pageSize:10, store:ozieStore, displayInfo:true, anchor:'100%'
	});

	var catModel = new Ext.grid.ColumnModel([
		{header:'Name', dataIndex: 'a', width:290},
		{header:'M', dataIndex: 'e', align:'center', width:65, renderer:km, hidden:true},
		{header:'Alamat', dataIndex: 'b', hidden:true},
		{header:'Categorie', dataIndex: 'g', hidden:true}
	]);
	catModel.defaultSortable= true;
	
	var gridOzie = { id:'gridOzie', xtype:'grid', anchow:'100%', ds:ozieStore, cm:catModel, anchor:'100%', height:310, border:false, autoScroll:true,
		view:new Ext.grid.GroupingView({
		    forceFit:true,
		    groupTextTpl:'{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
		}),
		sm:new Ext.grid.RowSelectionModel({singleSelect:true})
	};
	//========================================================================================================= Search Panel
	new Ext.Panel({
		id:'navPanel', applyTo:'searchPanel', width:400, split:true, autoHeight:true, frame:true, border:false, bodyStyle:'z-index:2;',
		collapsed:true,
		items:new Ext.TabPanel({
		    activeTab:0, id:'tabSearch',
		    items:[{
		    	id:'result', title:'Result', autoHeight:true, items:[barOzie, gridOzie]
		    }]
		}),
		buttons:[{iconCls:'hideIt', tooltip:'Hide panel', handler:function(){Ext.getCmp('navPanel').collapse();}}]
	});
	//========================================================================================================= Nearby and advance Panel
	var advSearchPanel = new Ext.FormPanel({
	    id:'advSearchPanel', bodyStyle:'padding:2px 2px 0;', frame:true, autoHeight:true, defaults:{minLength:3, anchor:'100%'}, labelAlign:'top', border:false,
	    items:[advCat1, advCat2, advCat3],
	    buttons:[srcAdvance, rfsAdvance, {iconCls:'hideIt', tooltip:'Hide panel', handler:function(){Ext.getCmp('advSearchPanel').collapse();}}],
	    listeners:{
	    	'expand':function(){
	    		Ext.getCmp('navPanel').collapse();
	    	}
	    }
	});
	
	new Ext.Panel({
	    id:'nearPanel', applyTo:'nearPanel', width:350, split:true, autoHeight:true, margins:'0 0 0 0', bodyStyle:'z-index:3;', collapsed:true, border:false,
	    items:advSearchPanel
    });
	//========================================================================================================= Direction Panel
	new Ext.Panel({
		id:'dirPanel', applyTo:'dirPanel', width:350, autoHeight:true, margins:'0 0 0 0', collapsed:true, 
		bodyStyle:'z-index:3', border:false,
		items:new Ext.Panel({
			bodyStyle:'z-index:3', anchor:'100%', autoHeight:true,  border:false,
			items:[
				new Ext.FormPanel({
					frame:true, anchor:'100%', autoHeight:true, bodyStyle:'z-index:3',
					items:[{
						xtype:'fieldset', title:'Optimize',
						items:[{
							xtype:'hidden', id:'hidVal'
						},{
							xtype:'combo', id:'goWith', store:dirStore, hideLabel:true, anchor:'100%', displayField:'dir', valueField:'id',
						    typeAhead:true, forceSelection:true, triggerAction:'all', emptyText:'drive with [default by car]', selectOnFocus:true, mode:'local',
						    listeners:{
						    	'select':function(){
						    		Ext.getCmp('hidVal').setValue(this.getValue());
						    	}
						    }
						},{
							xtype:'checkbox', id:'optimize', boxLabel:'Optimalkan', checked:true, value:'optimize', hideLabel:true
						},{
							xtype:'checkbox', id:'highWays', boxLabel:'Hindari jalan raya', checked:true, value:'highways', hideLabel:true
						},{
							xtype:'checkbox', id:'tolls', boxLabel:'Hindari jalan toll', checked:true, value:'tolls', hideLabel:true
						}]//fieldset
					}, new Ext.Panel({
						anchor:'100%', height:250, autoScroll:true, bodyStyle:'z-index:3', items:[{contentEl:'directionsPanel', border:false, title:'Direction'}]
					})],
					buttons:[{
						text:'Get Direction', iconCls:'direction',
						handler:calcRoute
					},{
						text:'Reset', handler:reset, iconCls:'refreshBtn'
					},{iconCls:'hideIt', tooltip:'Hide panel', handler:function(){Ext.getCmp('dirPanel').collapse();Ext.getCmp('dirPanelToggle').toggle(false);google.maps.event.clearListeners(map, 'click');}
					}]
				})//form panel
			]//items
		})
	});
	//============================================================================================================================= TOOLBAR
	new Ext.FormPanel({
	    border:false, applyTo:'toolbar', anchor:'100%', height:48,
	    bbar:[{
	    	xtype:'buttongroup', title:'Search', border:false,
	    	items:[hs, goButton, reButton, advButton]
	    },{
	    	xtype:'buttongroup', title:'Tools', border:false,
	    	items:[nearButton, dirButton]
	    },mapShare]
	});
  //================================================================================================================================= SET MAP
  map = new google.maps.Map($('#map')[0],{
      zoom:myZoom,
      center:latLng,
      disableDefaultUI:true,
      mapTypeControl:true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  
  shareMap(ozieStore);
  
  //==============
  origin = null;
	destination = null;
	waypoints = [];
	markersDir = [];
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsService = new google.maps.DirectionsService();
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById("directionsPanel"));
	directionsVisible = false;
  
	//=========
  ozieStore.addListener('beforeload', function(){
	  this.setBaseParam('freeText', hs.getValue());
	  this.setBaseParam('x', Ext.getCmp('nX').getValue());
	  this.setBaseParam('y', Ext.getCmp('nY').getValue());
	  this.setBaseParam('s', Ext.getCmp('ns').getValue());
	  this.setBaseParam('sv', Ext.getCmp('nv').getValue());
	  
	  $(iconHTML("close")).click(function(){$div.fadeOut();});
	  clearMarkers();
  }); 

  ozieStore.addListener('load', function(){
	  if(this.getCount()>0){
		  if(this.getAt(0).data.e !='') catModel.setHidden(1, false); else catModel.setHidden(1, true);
		  if((this.getAt(0).data.c && this.getAt(0).data.d)!=''){
			  var marker;
			  var ozieModel = Ext.getCmp('gridOzie').getSelectionModel();
			  for(var i=0; i<this.getCount();i++){
				  marker = new google.maps.Marker({position:new google.maps.LatLng(this.getAt(i).data.d, this.getAt(i).data.c), icon:getIcon('icn'), shadow:getIcon('oji'), title:this.getAt(i).data.a, animation:google.maps.Animation.DROP, map:map});
				  markers.push(marker);
			  }//for
			  
			  $(markers).each(function(i, marker){
		  		  google.maps.event.addListener(marker, "click", function(){
		  			ozieModel.selectRow(i);
		  			$(".nearWin").live('click', function(){
					    Ext.getCmp('navPanel').collapse(); Ext.getCmp('nearPanel').expand(); Ext.getCmp('homeSearch').setValue('');
					    Ext.getCmp('nX').setValue(ozieStore.getAt(i).data.c); Ext.getCmp('nY').setValue(ozieStore.getAt(i).data.d);
					    ozieStore.load({params:{'req':'clear'}});
					}).end();
					$(".fbWin").live('click', function(){
					    window.open('http://www.facebook.com/sharer.php?u='+myurl()+'/?v='+ozieStore.getAt(i).data.w+ozieStore.getAt(i).data.r+ozieStore.getAt(i).data.q, 'Facebook share', 'copyhistory=no, menubar=no, statusbar=no, addressbar=no, location=no, menubar=no, toolbar=no, resizable=yes');
					}).end();
					$(".twWin").live('click', function(){
					    window.open('http://twitter.com/home?status='+myurl()+'/?v='+ozieStore.getAt(i).data.w+ozieStore.getAt(i).data.r+ozieStore.getAt(i).data.q, 'Twitter share', 'copyhistory=no, menubar=no, statusbar=no, addressbar=no, location=no, menubar=no, toolbar=no, resizable=yes');
					}).end();
					$(".mailWin").live('click', function(){
						Ext.MessageBox.prompt('Mail to', 'Example: yourfriend@mail.com. Separated by ;', function(btn, text){
							if(btn == 'ok'){
								location.href = 'mailto:'+text+'?body='+myurl()+'/?v='+ozieStore.getAt(i).data.w+ozieStore.getAt(i).data.r+ozieStore.getAt(i).data.q+'&subject=Recomended';
							}
						});
					}).end();
					$(".dirWin").live('click', function(){
						origin = new google.maps.LatLng(ozieStore.getAt(i).data.d, ozieStore.getAt(i).data.c);
						addMarker(origin);
						Ext.getCmp('navPanel').collapse(); Ext.getCmp('nearPanel').collapse(); Ext.getCmp('dirPanel').expand();
						google.maps.event.addListener(map, 'click', function(event){
							if (origin == null) {
								origin = event.latLng;
								addMarker(origin);
							} else if (destination == null) {
								destination = event.latLng;
								addMarker(destination);
							} else {
								if(waypoints.length < 9){
									waypoints.push({ location: destination, stopover: true });
									destination = event.latLng;
									addMarker(destination);
								}else{
									Ext.Msg.alert('Warning', 'Maximum number of way points reached');
								}
							}
						});//google.maps.event.addListener
					}).end();
					
		  		  });
		  	  });
			 
			  ozieModel.addListener('rowselect', function(sm, row, rec){
				  var info = '<div class="prop"><div class="propName">Name</div><div class="propVal">'+rec.get('a')+'</div></div>'+
		        	'<div class="prop"><div class="propName">Popular</div><div class="propVal">'+rec.get('m')+'</div></div>'+
		        	'<div class="prop"><div class="propName">Address</div><div class="propVal">'+rec.get('b')+'</div></div>'+
		        	'<div class="prop"><div class="propName">Region</div><div class="propVal">'+rec.get('f')+'</div></div>'+
		        	'<div class="prop"><div class="propName">Business line</div><div class="propVal">'+rec.get('g')+'</div></div>';
				  Ext.getCmp('infoPanel').update(info.replace(/NULL/g, ' '));
				  var detil = '<div class="prop"><div class="propName">Product</div><div class="propVal">'+rec.get('p')+'</div></div>'+
		    		'<div class="prop"><div class="propName">Telphone</div><div class="propVal">'+rec.get('h')+'-'+rec.get('i')+'</div></div>'+
		        	'<div class="prop"><div class="propName">Fax</div><div class="propVal">'+rec.get('j')+'</div></div>'+
		        	'<div class="prop"><div class="propName">Home Page</div><div class="propVal">'+rec.get('k')+'</div></div>'+
		        	'<div class="prop"><div class="propName">EMail</div><div class="propVal">'+rec.get('l')+'</div></div>';
				  Ext.getCmp('detilPanel').update(detil.replace(/NULL/g, ' '));
				  //ozieStore.load({params:{'req':'clear'}});
				  selector.load({params:{'a':rec.get('q'), 'b':rec.get('r'), 'c':rec.get('a'), 'd':rec.get('f'), 'e':rec.get('s'), 'f':rec.get('t'), 'g':rec.get('u'), 'h':rec.get('v'), 'x':rec.get('c'), 'y':rec.get('d'), 'i':rec.get('b')}});
				  
				  var rowMarker = new google.maps.Marker({position:new google.maps.LatLng(rec.get('d'), rec.get('c'))});
				  message.open(rowMarker, i);
			  });
			map.panTo(new google.maps.LatLng(ozieStore.getAt(0).data.d, ozieStore.getAt(0).data.c));
			map.setZoom(15);
		  }//getAt(0)!= ''
	  }//count > 0
  });
  
  function MessageWindow(){this.setMap(map);}
  MessageWindow.prototype = new google.maps.OverlayView();
  MessageWindow.prototype.onAdd = function(){
	  this.$div_ = $('<div id="message" />').appendTo(this.getPanes().floatPane);
  };
  MessageWindow.prototype.draw = function(){
	  var me = this;
      var $div = this.$div_;
      var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
      if(point) {
    	  $div.css({ left: point.x, top: point.y });
      }
  };
  MessageWindow.prototype.remove = function() {
	  if(this.$div_){
		  this.$div_.remove();
          this.$div_ = null;
      }
  };
  MessageWindow.prototype.getPosition = function(){
     return this.latlng_;
  };
        
  var openTimeout;
  
  MessageWindow.prototype.open = function(marker, index){
	  clearTimeout(openTimeout);
	  $div = this.$div_.stop().css('opacity',1).hide().empty();
	  this.latlng_ = marker.position;
      this.draw();
      var closeButton = $(iconHTML("close")).click(function(){$div.fadeOut();}).css({ top:'5px', right:'5px'});
      $("#tabs-template").clone().show().attr("id","").appendTo($div).find(".index").html(index.toString()).end().tabs().find(".ui-tabs-nav").append(closeButton);
      var left = map.getBounds().getSouthWest().lat();
      var right = map.getBounds().getNorthEast().lat();
      var offset = (right - left) * .25;
      var newCenter = new google.maps.LatLng(marker.position.lat(), marker.position.lng()+offset);
      map.panTo(newCenter);
      openTimeout = setTimeout(function(){
    	  $div.show("drop", { direction:"right" });
      }, 500);
  }; //MessageWindow.prototype.open
  
  var message = new MessageWindow();
  $("#dialog").show().dialog({
	  autoOpen:false, modal:true, overlay:{background:"#000", opacity:0.7 }, width:300, height:300
  });
				
  $(".dialog").live('click', function(){ 
	  $("#dialog").dialog("open"); 
  }).end();
});//root

	

