var GeoPot = Class.create();

GeoPot.prototype = {

  initialize: function(_address) {
    this.address = _address;
    this.placemarkAddress = '';
    this.lat = '';
    this.lng = '';
    this.searchForm = $('productSearch');
    this.url = location.href;

    this.watchForm(this);
    
  },
  
  locate: function() {
    if(this.address && this.address != '') {
      var geocoder = new GClientGeocoder();
      geocoder.getLocations(self.address + ', United Kingdom', function(response) {
        var place = response.Placemark[0];
        this.placemarkAddress = place.address.gsub(', UK', '');
        this.lat = place.Point.coordinates[1];
        this.lng = place.Point.coordinates[0];
        // self.updateCriteriaDisplay();
        // self.search();
      }.bind(this));
    } else {
      this.lat = null;
      this.lng = null;
      this.placemarkAddress = null;
      // self.updateCriteriaDisplay();      
      // self.search();
    }

  }

}


var SearchProducts = Class.create();
SearchProducts.prototype = {
  initialize: function() {
    this.paramLocation = '';
    this.paramQuery = '';
    this.placemarkAddress = '';
    this.lat = '';
    this.lng = '';
    this.page = '';
    this.searchForm = $('productSearch');
    this.url = location.href;
  
    this.locationDisplay = 'locationText';
    this.criteriaPanel = $('title');
    this.watchPaginate(this);
    this.watchForm(this);
    this.checkURL();
  },
  
  watchForm: function(self) {
    self.searchForm.observe('submit', function(event) {
        var form = event.element();
        self.paramLocation = form['location'].value;
        self.paramQuery = form['query'].value;
        self.page = '';
        self.updateURL();
        self.geoLocateAndSearch(self);
        event.stop();
    });
  },
  
  watchPaginate: function(self) {
    if(!$('paginate'))
      return; 
    $('paginate').observe('click', (
      function(event) { 
        if ((event.element().tagName == 'A' ) && (location.href.split('?')[1].indexOf('cat=') == -1)) {
          
          // alert(location.href.split('?')[1].indexOf('cat=') > -1)
          var element = event.element();          
          self.page = element.href.toQueryParams().page;
          self.updateURL();
          self.geoLocateAndSearch(self);
          event.stop();
        }
      })
    )  	
    
  },
  
  updateURL: function() {
     var hash  = "location=" + escape(this.paramLocation) + "&query=" + escape(this.paramQuery);
         hash += "&page=" + this.page;
     // if(p)
     //   hash += "&page=" + p;
     location.hash = hash;
  },

  updateCriteriaDisplay: function() {    
    if(this.placemarkAddress) 
      var location =  " around " + this.placemarkAddress;
    else
      var location = '';
    
    // this.criteriaPanel.update("Searching: " + this.paramQuery + location);
  },

  checkURL: function() {
    if(location.hash) {
      var params = location.hash.gsub('#', '').toQueryParams();
			this.paramQuery = params.query;
			this.paramLocation = params.location;
			this.searchForm['location'].value = params.location;
      this.searchForm['query'].value = params.query;
      this.page = params.page;
			this.geoLocateAndSearch(this);
    }
  },
  
  geoLocateAndSearch: function(self) {
    if(self.paramLocation && self.paramLocation != '') {
      var geocoder = new GClientGeocoder();
      geocoder.getLocations(self.paramLocation + ', United Kingdom', function(response) {
        var place = response.Placemark[0];
        self.placemarkAddress = place.address.gsub(', UK', '');
        self.lat = place.Point.coordinates[1];
        self.lng = place.Point.coordinates[0];
        self.updateCriteriaDisplay();
        self.search();
      });
    } else {
      self.lat = null;
      self.lng = null;
      self.placemarkAddress = null;
      self.updateCriteriaDisplay();      
      self.search();
    }

  },
  
  search: function() {
    var params = {};
    var url = '/search_products';
    if(this.lat && this.lng) {
      params['lng'] = this.lng;
      params['lat'] = this.lat;
    }

    if(this.page)
      params['page'] = this.page;

    params['query'] = this.paramQuery;

    new Ajax.Request(url, 
    { method:'get',
      parameters: params,
      onCreate:  function() {
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 3 );
        var lightboxLeft = arrayPageScroll[0];
        $('loadingNotice').setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();
      },      
      onComplete: function() {
        Effect.ScrollTo('productSearch');
        new Effect.Fade('loadingNotice', {duration: 0.5});
      }
    });
  }
} // END Class


  // extractParamsFromHref: function() {
  //  var params = location.hash.gsub('#', '').toQueryParams();
  // 
  // }
  



// geocode: function(address, move) {
// 		var geocoder = new GClientGeocoder();
// 
// 	  // geocoder.getLatLng( address + ', United Kingdom', function(point) 
// 	  geocoder.getLocations( address + ', United Kingdom', function(response)
// 			{ 
// 				place = response.Placemark[0];
// 
// 				var lat = place.Point.coordinates[1];
// 				var lng = place.Point.coordinates[0];
//       	var accuracy = place.AddressDetails.Accuracy;
// 				this.zoom = tabAccuracy[accuracy];
// 				this.newPoint = new GLatLng(lat, lng);					
// 				MapControl.map.setCenter(MapControl.newPoint, MapControl.zoom);
// 				// if(move) 
// 				// 	this.moveToNewPoint();
// 			}.bind(this)
// 	  );
// 	}


// function post_search(q,l,p) {
// 
//  var hash  = "location=" + escape(l) + "&query=" + escape(q);
//  if(p)
//    hash += "&page=" + p;
// 
//  location.hash = hash;
//  var geocoder = new GClientGeocoder();
// 
//   geocoder.getLocations(l + ', United Kingdom', function(response) {
//    var place = response.Placemark[0];
//    var address = place.address;
//    var lat = place.Point.coordinates[1];
//    var lng = place.Point.coordinates[0];
// 
//    $('locationText').update(address);
//    SearchProducts.run(lat, lng, q, p);
//  });
// }

function location_host() {
	var parts = location.host.split('/');
	
	if(parts.size() == 4)
		parts.shift()		

	var url = "http://" + parts.join('.');
	return url;
}

function ajaxLink(e){
	elt = e.element();
	new Ajax.Request(elt.href, 
	{asynchronous:true, 
		method: 'delete',
		evalScripts:true}); 

	e.stop();
}

function closeForm(form) {
	Event.stopObserving(form);
	form.remove();
}

function setForm(idString, _name) { // id, name
	$$('.product_collection_form').each(function(f){
		f.previous().show();
		closeForm(f);
	});
	var _id = idString.split('_')[2]

	var collection = {id: _id, name : _name};

	var tpl = new Template("<form id='edit_product_collection_form_#{id}' class='product_collection_form standard' action='/admin/product_collections/#{id}'>" +
	"<input id='product_collection_name' class='text inline' type='text' value='#{name}' size='30' name='product_collection[name]'/>" +
	"<input id='product_collection_submit' class='btn' type='submit' value='save' />&nbsp;" +
	"<a href='#' class='cancel_form'>cancel</a>" +
	"</form>");

 	var elt = tpl.evaluate(collection);
	var el = $(idString).insert({bottom: elt});
	Event.observe('edit_product_collection_form_' + _id, "submit", function(e){ 
		ajaxHelperProductCollection(e.element());
		e.stop();
	 });
}

function ajaxHelperProductCollection(form, _method) {
	var url = form.action;
	if(_method == null)
			_method = 'put';
			
	var _parameters = $H(Form.serialize(form,true));
	var _product_id = getProductIDfromHref();
	if(_product_id)
			_parameters = _parameters.merge($H({product_id:_product_id}))
	
	new Ajax.Request(url, 
		{	asynchronous:true, 
			evalScripts:true, 
			method: _method,
			onComplete: function(){form.enable();},
			onCreate: 	function(){form.disable();},
			parameters:_parameters.toQueryString()
		});	
}

function remoteForm(form){
	new Ajax.Request(form.action, 
	{	asynchronous:true, 
		evalScripts:true, 
		
		onComplete: function(){
			form.enable();
		},
		onCreate: 	function(){
			form.disable();
		},
		parameters:Form.serialize(form)
	});	
}

Event.addBehavior({
		
	
	'#joinRegular:submit' : function(e) {
		remoteForm(e.element());
		e.stop();
	},
	
	'.changer:click' : Event.delegate({
		'#productsSwitch':function(e) {
			switchResults(e);
		},
		'#suppliersSwitch':function(e) {
			switchResults(e);
		}
	}),
	
	'#searchForm:click' : Event.delegate({
		'#toggleFor' : function(e){
			$('searchForm').action = location_host() + '/search';
			$('toggleFor').toggle();
			$('toggleWhere').toggle();
			// $('searchForm').title = 'Search for?';
			$$('#searchForm label')[0].innerHTML = '<strong class="search">Search for?</strong>';
			e.stop();
		},
		'#toggleWhere' : function(e){
			$('searchForm').action = location_host() + '/map';
			// $('searchForm').title = 'Search where?';			
			$('toggleFor').toggle();
			$('toggleWhere').toggle();
			$$('#searchForm label')[0].innerHTML = '<strong class="search">Search where?</strong>';
			e.stop();			
		}
		
	}),
	'#ajaxNoticeValid':function(){
		// if($('ajaxNoticeValid').visible())
		// setTimeout(Messenger.fadeNotice.bind(this), 5000);
	},
	'#markupLess a:click':function(e){
		$('markupLess').hide();
		$('markupMore').show();
		e.stop();
	},
	'#markupMore a:click':function(e){
		$('markupLess').show();
		$('markupMore').hide();		
		e.stop();		
	},
		
	'#byMap:click':function(e){
		$('suppliers_table').hide();
		$('suppliers_map').show();
		e.element().addClassName('active');
		$('byList').removeClassName('active');
		$('browse_by').show();
		$('supplierWindow').show();
		$('categories').hide();
		e.stop();		
	},	
	
	'#byList:click':function(e){
		e.element().addClassName('active');
		$('byMap').removeClassName('active');
		$('suppliers_table').show();
		$('suppliers_map').hide();
		$('browse_by').hide();
		$('supplierWindow').hide();
		$('categories').show();		
		e.stop();		
	},
	'#supplierWindow:click': Event.delegate({
		'#closePreview':function(e) {
			previewBlind.close();
		}
	}),
	
	
	'input#handle_input' : function() {
		Signup.registerHooks();
	},
		
	// set height of supplier about text if present
	'div#about_full' : function(e) {
		supplierAboutText();
	},

	// shrink/expand supplier about text	
	'#blind_control:click' : function(e) {
		reveal();
		e.stop();
	},
	
	'#new_collection_item': function() {
		$('new_collection_item').hide();
	},
	
	'#new_collection_switch:click': function(e) {
		$('new_collection_item').toggle();
		e.stop();
	},
	
	'#cancel_collection:click': function(e) {
		$('new_collection_item').toggle();
		e.stop();		
	},
	
	
		
	//****** ADMIN:: Product Collection Management ******//
	
	'#new_product_collection:submit' : function(e) {
 		ajaxHelperProductCollection(e.element(), 'post');
		e.stop();
	},

	'#collections_index:click': Event.delegate({
    'input.checkbox': function(e) {
				// Works only for URL format http://shop.look4local.co.uk/admin/products/XXX/collections
			 updateCollection(e.element(),  location.href.split('/products/')[1].split('/')[0]);
		},
				
		'a.edit': function(e) {
			var elt = e.element();
			setForm(elt.up(1).id, elt.title)			
			elt.up('div').hide();
			// elt.up('div').next('form').show();
			e.stop();
		},
		
		'a.del':function(e){

				if(confirm('Are you sure?'))
					ajaxLink(e);				
		},		
		'a.cancel_form': function(e) {
			var elt = e.element();
			elt.up().up().down().show();
			var form = elt.up();
			closeForm(form);
			e.stop();
		}
  }),	
	
		// location map for profile
	'#admin_supplier_map' : function() {
		MapControl.loadMap($('admin_supplier_map'));
	},
	
	'#searchLocation:submit' : function(e) {
		var form = e.element();
		MapControl.geocode(form['location'].value, true);		
		e.stop();
	},
	
	
	
	'#suppliers_map #map': function() {
		var map = new MapSearch();
	},
	
	// '#searchAddress:submit' : function(e) {
	// 	form = e.element();
	// 	map.geocode(form['address'].value, true);
	// 	e.stop();		
	// },

	'#centrePin:click' : function(e) {
		MapControl.centerPin();
		e.stop();
	},
	
	'#savePin:click' : function(e) {
		MapControl.savePin();
		e.stop();
	}	
	
})