//*********** Google GeoCoder: Client side  ***************//

// var GeoCode = {	
// 	geocode: function(address){
// 			if(!address) return;
// 			var geocoder = new GClientGeocoder();
// 		  geocoder.getLatLng( address + ', United Kingdom', new SearchProducts(pointfunction(point) 
// 			{ 
// 				return(point);
// 			}.bind(this)
// 		 );		
// 		return;
// 	}
// 	
// }

// var SearchProducts = {
//  run: function(lat, lng, query, p) {   
//    SearchProducts.fetch(lat, lng, query, p)
//  },
//  
//  fetch: function(lat, lng, q, p) {
//    var params = {};
//    var url = '/search_products';
//    if(lat && lng) {
//      params['lng'] = lng;
//      params['lat'] = lat;
//    }
//    params['page'] = p;
//    params['query'] = q;
//    new Ajax.Request(url, 
//        { method:'get',
//          parameters: params,
//          onCreate:  function() {$('loadingStatus').show();},
//          onComplete: function() {$('loadingStatus').hide()},
//          onSuccess:  function(transport) {     
//          }.bind(this)
//        });
//    
//  }
//  
// }
// 

//*********** END  ***************//

function getProductIDfromHref(){
	var x = location.href.split('/products/')[1]
	var id = null;
	
	if(x && !isNaN(id)){
		id = x.split('/')[0];
	}
	
	return id;
}


function ajaxLink(e){
	var _method = 'delete';
	url = e.href;
	new Ajax.Request(url, {
		method: _method
	});		
}

function deleteItem(el){
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	this.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = el.href;
	var m = document.createElement('input'); 
	m.setAttribute('type', 'hidden'); 
	m.setAttribute('name', '_method'); 
	m.setAttribute('value', 'delete'); 
	f.appendChild(m);
	f.submit();
	return false;
}

//*********** About Text for Supplier  ***************//
// 
// 
//

function supplierAboutText(e) {
	var box = $('about_full');
	if(box.getHeight() > 200) {
		box.style.height = 100 + "px"
		$('blind').show();
	}
}

// Reveals or conceals about text for supplier
function reveal() {
	var box = $('about_full');
	var totalHeight = $$('#about_full div').first().getHeight();
	var percentage, endHeight, blindControlText;
	if(box.getHeight() > 100) {
			percentage = (93/totalHeight) * 100;
			endHeight = 100; // %
			blindControlText = 'more&raquo;';
			$('blind_control').innerHTML = blindControlText;
	} else {
			percentage = (totalHeight / $('about_full').getHeight()	* 100) + 20
			endHeight = totalHeight + 20;
			blindControlText = '&laquo;less';
			$('blind_control').innerHTML = blindControlText;
	}
		
	new Effect.BlindDown('about_full', {scaleFrom: 100, scaleTo: percentage,
	afterFinish: function() { 
		if (endHeight)
			$('about_full').style.height = endHeight + 'px';

	}})
} // reveal

// ** //

function updateCollection(collection, product_id) {
	if(collection.checked) {
		var url = '/admin/collection_items';
		var _method = 'POST';
	}
	else {
		var url = '/admin/collection_items/' + collection.value;
		var _method = 'DELETE';
	}		
	new Ajax.Request(url, {
		method: _method,
		parameters: {'product_collection_id': collection.value, 'value': collection.checked, 'product_id': product_id}
	});	
}


function switchResults(e) {

	var rS = $('resultsSupplier');
	var rP = $('resultsProduct');

	if(rS.visible()) {
		rS.hide();
		rP.show();
		$('productsSwitch').addClassName('active');
		$('suppliersSwitch').removeClassName('active');
	} else {
		rS.show();
		rP.hide();
		$('productsSwitch').removeClassName('active');
		$('suppliersSwitch').addClassName('active');
	}
	
	e.stop();
}
//*********** Messenger Functions ***************//
// Taken from shopify.com.
// Messenger is used to manage notices.


var Indicator = Class.create();
Indicator.prototype = {
  initialize: function(offsetX, offsetY) {
    this.offsetX = offsetX || 8;
    this.offsetY = offsetY || 5;
    
    var body = document.getElementsByTagName('body')[0];
    
    new Insertion.Bottom(
      body, 
      '<div id="indicator" style="z-index: 1000; position:absolute; width:20px; height:20px; padding:6px; display: none; "><img src="/images/spinner.gif" border="0"></div>' 
    );
    
    this.indicator = $('indicator');
        
    Ajax.Responders.register({
      onLoading:  this.indicate.bind(this, true),
      onComplete: this.indicate.bind(this, false) 
    });  
    
    Event.observe(body, "mousemove", this.onMouseMove.bind(this));
  },
  
  onMouseMove: function(event) {
    try {
    this.indicator.style.top    = Event.pointerY(event) + this.offsetY + "px";         
    this.indicator.style.left   = Event.pointerX(event) + this.offsetX + "px"; 
    } catch(e) {}
  },
      
  indicate: function(visible) {
    if(visible) { this.indicator.show(); }
    else        { this.indicator.hide(); }
  }
};

var Messenger = {
  autohide_error: null,
  autohide_notice: null,
  // When given an error message, wrap it in a list 
  // and show it on the screen.  This message will auto-hide 
  // after a specified amount of miliseconds
  error: function(message) {
    $('flasherrors').innerHTML = "<li>" + message + "</li>";
    new Effect.Appear('flasherrors', {duration: 0.3});
    
    if (this.autohide_error != null) {clearTimeout(this.autohide_error);}
    this.autohide_error = setTimeout(Messenger.fadeError.bind(this), 5000);
  },

  // Notice-level messages.  See Messenger.error for full details.
  notice: function(message) {
    $$('.ajaxNoticeValid').each(function(div){
			div.innerHTML = "<p>" + message + "</p>";		
		});
	  
		new Effect.Appear('flashWrapper', {duration: 0.3});	

    if (this.autohide_notice != null) {clearTimeout(this.autohide_notice);}
    this.autohide_notice = setTimeout(Messenger.fadeNotice.bind(this), 5000);
  },
  
  // Responsible for fading notices level messages in the dom    
  fadeNotice: function() {
    new Effect.Fade('flashWrapper', {duration: 0.3});
    this.autohide_notice = null;
  },
  
  // Responsible for fading error messages in the DOM
  fadeError: function() {
    new Effect.Fade('flasherrors', {duration: 0.3});
    this.autohide_error = null;
  }
};



//***** SIGNUP RELATED CODE *****//
//*******************************//

var Signup = {
	
	registerHooks: function() {		
		$('handle_update_view').update($('handle_input').value);				
    if($('handle_input')) {
      new Form.Element.Observer('handle_input', 1, this.process.bind(this) );
    }
	},
  
  process: function(element, value) {

		$('invalid').hide();
		$('valid').hide();
		if(element.value == '') {
			$('handle_update_view').up().hide();
			$('invalid').hide();
			$('valid').hide();			
		} else {
			$('handle_update_view').up().show();
		}
			
		$('handle_update_view').update(element.value.strip());

    if (value.length >= 4 ) {
      	new Ajax.Request('/suppliers/check_handle', {parameters: "handle="+value});
    	} 
    else {
      $('invalid').update("Subdomain must be at least 4 characters.");
			if(element.value != '')
				$('invalid').show();
    }
  }
    
};



//***** MAP RELATED CODE *****//
//****************************//









// 
// 
// 
// var map = ''
// function updateProductVisibleHome(product) {	
// 	alert(product.value + ' ' + product.checked);
//  	var url = '/products/' + product.value + '/visible_home'; 
// 	var _method = 'PUT'
// 	new Ajax.Request(url, {
// 					method: _method,
// 					parameters: {'product_id': product.value, 'value': product.checked}
// 					// onSuccess: highlight
// 									});
// }
// 
// 
// function expand_collapse() {
// 	if ($('format_box').visible()) {
// 		$('format_box').hide();
// 		$('format_box_link').update('show');	
// 	} else {
// 		$('format_box').show();
// 		$('format_box_link').update('hide');			
// 	}
// 	
// }
// 
// 
// 
// 
// function help_button(id, self) {
// 	if ($('tip_' + id).visible()) {
// 		$('tip_' + id).hide();
// 		$('tip_link_' + id).update('help!');	
// 	} else {
// 		$('tip_' + id).show();
// 		$('tip_link_' + id).update('helped');			
// 	}
// 	
// }
// 
// function load_map(id, lat, lng, map_, url) {
// 
// 		if ($('extra_' + id).visible()) {
// 			$('extra_' + id).hide();
// 
// 			$$('#indexItem_' + id + ' dd.moreLess a.right').first().update('more');
// 		 	$('point_' + id).src = '/images/pointClose.gif';
// 			if(map_){
// 				GUnload();
// 			}
// 		// }
// 		// else {
// //			$$('#supplier_' + id + ' a.right').first().update('hide');
// //			$$('#supplier_' + id + ' img.point_arrow').first().src = '/images/pointOpen.gif';
// //			$$('#supplier_' + id + ' div.extra_info').first().show();			
// 
// //			if(map_) {
// 	} else {
// 		$('extra_' + id).show();
// 		$('point_' + id).src = '/images/pointOpen.gif';
// 		$$('#indexItem_' + id + ' dd.moreLess a.right').first().update('less');
// 		map = new GMap($("map_" + id));
// 		map.addControl(new GSmallMapControl());
// 		var location = new GLatLng(lng, lat);
// 		map.setCenter(location, 15);
// 		var marker = new GMarker(location);
// 	   	GEvent.addListener(marker, "click", function() {
// 	    	window.location =  url;			
// 			});		
// 		map.addOverlay(marker);
// 	}
// }
// 
// 
// function updateCollection(collection, product_id) {
// //	alert(collection.value + ' ' + collection.checked);
// 
// 	var highlight = function()	{ 
// 				new Effect.Highlight('collection_'+collection.value, {endcolor: '#F4F9FB'}); 
// 				};
// 
// // if(linkage) {
// //   new Ajax.Request('/admin/collects', {method: 'POST', parameters: 'collect[product_id]='+this.product_id+'&collect[collection_id]='+collection_id, onSuccess: highlight} );
// // }
// // else {    
// //   new Ajax.Request('/admin/collects/'+this.product_id+'-'+collection_id, {method: 'DELETE', onSuccess: highlight});
// 
// 
// 
// 		
// 		if(collection.checked) {
// 			var url = '/collection_items';
// 			var _method = 'POST';
// 		}
// 		else {
// 			var url = '/collection_items/' + collection.value + '-' + product_id;
// 			var _method = 'DELETE';
// 		}
// 		
// 		new Ajax.Request(url, {
// 		  						method: _method,
// 									parameters: {'product_collection_id': collection.value, 'value': collection.checked, 'product_id': product_id},
// 		  						onSuccess: highlight
// 										});
// 
// 				
// 
// 		// , 
// 		// 			{
// 		// 				parameters: {'id': collection.value}
// 		// 			},
// 		// 			{ method: 'post'}
// 		// 		);
// 	
// }
// 
// function displayMiniMap(id, lat, lng) {
// 	if (GBrowserIsCompatible()) {
// 		map = new GMap2(document.getElementById("map_" + id));
// 		var location = new GLatLng(lat, lng);
// 		map.setCenter(location, 14);
// 		var marker = new GMarker(location);		 
// 		map.addOverlay(marker);	
// 
// 			
// 	}	
// }
// 
// function initMap() {
// 	if (GBrowserIsCompatible()) {
// 		map = new GMap2(document.getElementById("map"));
// 		// map.addControl(new GLargeMapControl());
// 		var location = new GLatLng(lat, lng);
// 		map.setCenter(location, zoom);
// 		var marker = new GMarker(location, {draggable:editMap});		 
// 	}
// }
// 
// 
// function load() {
// 	if (GBrowserIsCompatible()) {
// 		map = new GMap2(document.getElementById("supplier_map"));
// 		// map.addControl(new GLargeMapControl());
// 		var location = new GLatLng(lat, lng);
// 		map.setCenter(location, zoom);
// 		map.addControl(new GSmallMapControl());		
// 		var Icon = new GIcon();
// 		Icon.image = "/images/markers/pin_black.png";
// 		Icon.iconSize = new GSize(24, 34);
// 		     // Icon.shadow = "myshadow.png";
// 		     // Icon.shadowSize = new GSize(36, 34);
// 		 Icon.iconAnchor = new GPoint(5, 34);
// 		 Icon.infoWindowAnchor = new GPoint(5, 2);
// 		if(editMap) {
// 			var marker = new GMarker(location,  {draggable:editMap});						
// 		} else {
// 			var marker = new GMarker(location, Icon);						
// 		   	GEvent.addListener(marker, "click", function() {
// 		    	window.location = "/map?s=" + supplier_id;			
// 				});	
// 			
// 		}
// 
// 		// edit
// 		if (editMap) {
// 		GEvent.addListener(marker, "dragend", function() {
// 				insertLatLng(marker.getPoint().lat(),marker.getPoint().lng());				 				
// 		 })
// 		}
// 		
// 
// 		
// 		map.addOverlay(marker);
// 	}
// }
// 
// function adjustLocation(lat, lng) {
// 	var location = new GLatLng(lat, lng);	
// 	map.setCenter(location, 10);
// 	var marker = new GMarker(location, {draggable:editMap});
// 	map.addOverlay(marker);		
// }
// 
// 
// function createMarker(latlng, html) {
// 	var marker = new GMarker(latlng);
//  	GEvent.addListener(marker, 'click', function() {
//  		var markerHTML = html;
//  		marker.openInfoWindowHtml(markerHTML);
// 	});
//  	return marker;
// }
// 
// function initializeInvitee(iv) {
// 	var invitee = new GLatLng(iv.lat, iv.lng);
// 	var html = '<div class=\'prop-cloud\'>'
// 		+ '<h3>' + iv.name + '</h3>' 
// 		+ '</div>';
// 	var marker = createMarker(invitee, html);
// 	map.addOverlay(marker);
// }
// 
// 
// 
// 
// function initData() {
// 	//clear markers currently on the map
// 	map.clearOverlays();	
// //  handleResize();
// 	xyz();
// 	//loop through markers
// 	for (var i = 0 ; i < markers.length ; i++) {
// 		var marker=markers[i].attributes
// 		
// 		// send marker to be displayed
// 		initializeInvitee(marker)
// 	}
// }
// 
// function xyz() {
// 	var cords = new GLatLng(latCentre, lngCentre);
// 	var marker = new GMarker(cords);
// 	
// 	map.addOverlay(marker);
// }
// 
// 
// function fetchMarkers(category) {
// 	var request = GXmlHttp.create();
// 	// tell the request where to retrieve data from.
// 	request.open('GET', 'list_map?category=' + category, true);
// 	
// 	//tell the request what to do when the state changes.
// 	request.onreadystatechange = function() {
// 		if (request.readyState == 4) {
// 			//parse the result to JSON by eval-ing it.
// 			//The response is an array of markes
// 			markers=eval( "(" + request.responseText + ")" );
// 			initData();
// 		}	
//     }
//     request.send(null);	
// }
// 
// 
// 
// 
// function init(category) {
// //	handleResize();
// 	//if (latCentre) {
// 		
// //	}
// 	
// 	// create new map object, and grab map div.
// 	map = new GMap(document.getElementById("map"));
// 	// add controller plus set centre
// 	// map.addControl(new GSmallMapControl());
// 	map.setCenter(new GLatLng(latCentre, lngCentre), mapCentre);
// 	
// 	// open Ajax object
// 	var request = GXmlHttp.create();
// 	
// 	// tell the request where to retrieve data from.
// 	request.open('GET', 'list_map?category=' + category, true);
// 	
// 	//tell the request what to do when the state changes.
// 	request.onreadystatechange = function() {
// 		if (request.readyState == 4) {
// 			//parse the result to JSON by eval-ing it.
// 			//The response is an array of markes
// 			markers=eval( "(" + request.responseText + ")" );
// 			initData();
// 		}	
//     }
//     request.send(null);
// }
// // Simple function that controls the display 
// 
// 
// 
// // Place your application-specific JavaScript functions and classes here
// // This file is automatically included by javascript_include_tag :defaults
// 
// 
// // Place your application-specific JavaScript functions and classes here
// // This file is automatically included by javascript_include_tag :defaults
// function insertLatLng(lat, lng){
// 	$('latEdit').value = lat;
// 	$('lngEdit').value = lng;
// }
// 
// function geo_code() {
//   if ($F('postCode').blank()) {
//     // Do nothing
//   } else {
//     new Ajax.Request('/geo_code', {
//       parameters:'post_code=' + $F('postCode'),
// 			method:'post',
//       onSuccess: function(transport) {
//         var json = transport.responseText.evalJSON();
// 				insertLatLng(json.lat, json.lng)
// 				adjustLocation(json.lat, json.lng)
//       },
//       onFailure: function(transport) {
//         var response = transport.responseText || "Sorry, there was an error.";
//         alert(response);
//       }
//     });
//   }
//   return false;		
// }
// 
// // Event.addBehavior({	
// // 	'textarea#writeComment' : function(){
// // 			this.observe('focus', function() { 
// // 				if (this.value=='write something...') {
// // 						this.value=''
// // 					}
// // 					 });			
// // 			this.observe('blur', function() { 
// // 				if (this.value == '') {
// // 					this.value='write something...' 
// // 					}
// // 				});						
// // 	}
// // 	
// // });
// 
// 
// 


document.observe("dom:loaded", function() {
  new Indicator(); 

  if($('productSearch')) {
    // new ProductRemote();    
    // if(!location.href.indexOf('products') == -1) {
    //    new SearchProducts();
    // }

  }
  
});

