var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/
browser = "";
if (Prototype.Browser.IE && parseFloat(navigator.appVersion.split(';')[1].strip().split(' ')[1]) == 6) browser = "Internet Explorer";

var EBizLightBox = Class.create();

EBizLightBox.prototype = {

	yPos : 0,
	xPos : 0,
	onComplete : "",
	options: {width:500, 
			  height: 400,
			  url: 'about:blank',
			  message: ''},
	
	initialize: function(options) {
    	this.content     = options.url;
		this.txt_message = options.message;
		this.onComplete  = options.onComplete;
		
		bod 			 = document.getElementsByTagName('body')[0];
		overlay 		 = document.createElement('div');
		overlay.id		 = 'overlay';
		lb				 = document.createElement('div');
		lb.style.width	 = options.width;
		lb.style.height	 = options.height;
		lb.id			 = 'lightbox';
		lb.className 	 = 'lb_content';
		lb.innerHTML	 = '';
						
		bod.appendChild(overlay);
		bod.appendChild(lb);

		if (browser == "Internet Explorer"){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		
		this.displayLightbox("block");
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
 
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none') this.loadInfo();
	},
		loadInfo: function() {
		if (typeof(this.txt_message) == "undefined") {
  			var myAjax = new Ajax.Request(this.content, {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)});			
		} else {
			this.updateLighbox(this.txt_message);
		}
		this.centerBox();
	},
	
	centerBox: function() {
		$('lightbox').style.top = ((Element.getHeight(document.body) - Element.getHeight('lightbox')) / 2 ) + 'px';
		$('lightbox').style.left = ((Element.getWidth(document.body) - Element.getWidth('lightbox')) / 2 ) + 'px';
	},
	
	processInfo: function(response){
		this.updateLighbox(response.responseText);
	},
	
	updateLighbox: function(content) {
		info = "<div id='lbContent'><h2 id=\"lbHeader\" style=\"display:none;\"></h2>\
				<a href=\"#\" onclick=\"return false;\" id=\"lbClose\"></a>" +  content + "</div>";
        $('lightbox').update(info);
		Event.observe($('lbClose'), 'click', function() {wind.deactivate();});
		if (typeof(this.onComplete) == "function") this.onComplete();
	},
	header: function(title) {
		$('lbHeader').update(title);
		Element.show('lbHeader');
	},
	deactivate: function(){	
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displayLightbox("none");
		Element.remove($('lbContent'));
		Element.remove('lightbox');
		Element.remove('overlay');
	}
}

var ResizableTextbox = Class.create({
  
  options: $H({
    min: 5,
    max: 500,
    step: 7
  }),
  
  initialize: function(element, options) {
    var that = this;
    this.options.update(options);
    this.el = $(element);
    this.width = this.el.offsetWidth;
    this.el.observe(
      'keyup', function() {
        var newsize = that.options.get('step') * $F(this).length;
        if(newsize <= that.options.get('min')) newsize = that.width;
        if(! ($F(this).length == this.retrieveData('rt-value') || newsize <= that.options.min || newsize >= that.options.max))
          this.setStyle({'width': newsize});
      }).observe('keydown', function() {
        this.cacheData('rt-value', $F(this).length);
      });
  }
});

function showmap(lat, lng, zoom) {
	lat = parseFloat(lat); 
	lng = parseFloat(lng);
	
	pos = new GLatLng(lat,lng)
	bizmap = new GMap2(document.getElementById("canvas"));
	bizmap.setCenter(pos, zoom);
	addcontrols();
}
function createMarker(mmap, point, info) {
  var marker = new GMarker(point);
  if (info != '') {
	  GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml(info);
	  });	
  }
  mmap.addOverlay(marker);;
}
function addcontrols() {
	bizmap.addControl(new GSmallMapControl());
	bizmap.addControl(new GMapTypeControl());
	
	// GEvent.addListener(bizmap,"dragend", function(){findNews();});
	// GEvent.addListener(bizmap,"zoomend", function(){findNews();});
}
function geo_one(addr, info, cid, token) {
	geocoder = new GClientGeocoder();
	var point;
	var geo;	
	geo = geocoder.getLatLng(addr, function (pos) {
		if (!pos) return false;
		createMarker(bizmap, pos, info);
		u_addr(pos,cid, token);
	});
}

function u_addr(pos, cid, token) {new Ajax.Request('/util/ug?lt=' + pos.lat() + '&lg=' + pos.lng()+'&cid='+cid+'&authenticity_token='+token, {method:'post'});}

function get_dir_pop(addr, cname, wtitle, token) {
	var url = '/util/get_dir?authenticity_token='+token+'&addr='+addr+'&cname='+cname;
	wind = new EBizLightBox({url:url, width: '300px', height: '200px', 
							onComplete: function() {wind.header(wtitle);}
							 });
}
function show_change_location(wtitle, token, lat, lng) {
	var url = '/util/change_location?authenticity_token='+token;
	wind = new EBizLightBox({url:url, width: '320px', height: '450px', 
							onComplete: function() {
									wind.header(wtitle);
									pos = new GLatLng(lat,lng);
									cur_loc = new GMap2(document.getElementById("cur_location"));
									cur_loc.setCenter(pos, 13);
									cur_loc.addControl(new GSmallMapControl());
									createMarker(cur_loc, new GLatLng(lat,lng), '');
								}
							 });
}
function searchCurrentAddr(a, not_found, invalid_addr, default_v) {
	if (a == '' || a == default_v) {
		alert(invalid_addr);
		return;
	}
	$('new_loc_container').hide();
	geocoder = new GClientGeocoder();
	try {
	pos = geocoder.getLatLng(a, function (pos) {
		
		if (!pos) {alert(not_found);return}
		cur_loc.setCenter(pos, 13);
		cur_loc.clearOverlays();
		createMarker(cur_loc, pos, '');
		$('temp_lat').value = pos.lat();
		$('temp_lng').value = pos.lng();
		geocoder.getLocations(pos, function(e) {
			try {
				if (typeof(e.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) != "undefined") {
					var city    = e.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
					$('temp_city').value = city;
		 			var state   = e.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
					$('temp_state').value = state;
					var zipcode = e.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
					$('temp_zipcode').value = zipcode;
				} else if (typeof(e.Placemark[0].AddressDetails.Country.AdministrativeArea) != "undefined") {
					var city    = e.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
					$('temp_city').value = city;
					var state   = e.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
					$('temp_state').value = state;
					var zipcode = e.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
					$('temp_zipcode').value = zipcode;
				}
				$('new_location').update(city + ', ' + state + ' ' + zipcode );
				$('new_loc_container').show();
			} catch(e) {
				$('temp_zipcode').value = '';
				$('new_location').update(city + ', ' + state);
				$('new_loc_container').show();
			};
		});
	});
	} catch(e) {
		alert(not_found + e);
	};
}
function save_cur_location(token) {
	var params  = 'city=' + $F('temp_city') + '&state=' + $F('temp_state') + '&zipcode=' + $F('temp_zipcode');
	    params += '&lat=' + $F('temp_lat') + '&lng=' + $F('temp_lng') + '&authenticity_token=' + token;
	new Ajax.Request('/util/save_cur_loc?' + params);
	wind.deactivate()
}

function inputClear(f, text) {
	if(f.value==text) f.value='';
}
function inputRecall(f, text) {
	if(f.value=='') f.value=text;
}
function near_location() {
	var temp_key = $F('search-location');
	if (temp_key != '') {
		new Ajax.Request('/util/location_complete?loc=' + temp_key + '&authenticity_token=' + $F('auth_token'), {
			onSuccess: function(resp) {
				var sugg_links = '';
				var suggestions = resp.responseJSON;
				if (suggestions.length > 0) {
					suggestions.each(function(suggestion) {
						sugg_links += '<div><a href="#" onclick="update_serarch_loc(\'' + suggestion[0] + '\');return false;">' + suggestion[1] + '</a></div>';
					})
					$('near_suggestions').show();
					$('near_suggestions').update(sugg_links);
				} else {
					$('near_suggestions').update('');
				}
			},
			onFailure: function(resp) {
				// $('near_suggestions').update('');
				alert('failure');
			}
		});
	}		
}
function update_serarch_loc(city_state) {
	$('search-location').value = city_state;
	$('near_suggestions').hide();
}
var wind;