window.addEvent('domready', function () {

	var state = $('state');
	if (state) {
		new StateChange($('state'), $('city-wrap'));
	}
	
	var sicinput = $('category_search-input') || $('category');
	if (sicinput) {
		new Autocompleter.Request.JSON(sicinput, 'sics.php', {
			'selectMode': 'type-ahead',
			'minLength': 2,
			'width': 400
		});
	}
	
	var map = $('map');
	if (map) {
		
		if (typeof companies != 'undefined') {
			window.bwpmap = new BWPMap(companies, map);
	
			var mappos = map.getCoordinates();
			var mapsize = map.getSize();
			var toppadding = 16;
			var innerContent = $('inner-content').getSize();
			
			if (mapsize.y > innerContent.y) {
				var height = innerContent.y - (2 * parseInt(map.getStyle('border-top-width')));
				map.setStyle('height', height);
				window.bwpmap.resize(height);
			} else {
				function moveMap () {
					var scroll = $(document.body).getScroll();
					var top = 0;
					
					if (scroll.y > mappos.top) {
						if (mapsize.y + scroll.y - mappos.top + toppadding > innerContent.y) {
							top = innerContent.y - mapsize.y;
						} else {
							top = scroll.y - mappos.top + toppadding;
						}
					} else {
						top = 0 
					}
					map.tween('top', top);
				}
				
				window.addEvent('scroll', moveMap);
				moveMap();
			}
		}
	}
	
	SqueezeBox.initialize({
        size: {x: 500, y: 500}
    });
    SqueezeBox.assign($$('a.more'), {
    	handler: 'iframe'
    });

});

function StateChange (select, citiesContainer) {
	var _this = this;
	
	this.select = $(select);
	this.citiesContainer = $(citiesContainer);
	var request = this.citiesContainer.set('load', [,]);
	request.addEvent('success', function () { alert('here') });
	
	$(select).addEvent('change', this.onStateChange.bind(this));
};

StateChange.prototype = {
	requestURL: '/cities.php',
	onStateChange: function (event) {
		var citySelect = null;
		if ( citySelect = this.citiesContainer.getElement('select') ) {
			citySelect.disabled = true;
			// this.citiesContainer.adopt( new Element( 'span', {'class': 'loading', 'html': 'Loading'} ) );
		}
		var _this = this;
		var cityRequest = new Request({
			method: 'get',
			url: this.requestURL + '?state=' + this.select.value,
			onSuccess: function (responseText) { _this.updateCities( responseText ) }
		});
		cityRequest.send();
	},
	updateCities: function (html) {
		this.citiesContainer.innerHTML = html;
	}
};

// from the solution on http://homepage.ntlworld.com/bobosola/pnginfo.htm, thanks
(function () { 
window.arVersion = navigator.appVersion.split("MSIE")
window.version = parseFloat(window.arVersion[1])

window.fixPNG = function(myImage) 
{
    if ((window.version >= 5.5) && (window.version < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
	   var imgTitle = (myImage.title) ? 
		             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' ";
	   var imgStyle = "display:inline-block;" + myImage.style.cssText;
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>";
	   myImage.outerHTML = strNewHTML;
    }
}
})();

var BWPMapInstance = null;
var checkGMapsTrysLeft = 5;
var checkGMapsTimeout  = 2000;

/**
 * Builds a map
 */
function BWPMap (companies, container) {
	this.container = $(container);
	this.separator = '<hr style="width:250px" />';
	this.markers   = [];
	this.companies = companies;
	
	BWPMapInstance = this;
	
	var checkGMaps = function () {
		if (checkGMapsTrysLeft == 0) {
			BWPMapInstance.container.set('html', 'Could not load GMaps. We are sorry for the inconvenience.');
		} else if (typeof GBrowserIsCompatible == 'undefined') {
			BWPMapInstance.container.set('html', 'Loading GMap, please wait...');
			checkGMapsTrysLeft--;
			setTimeout( checkGMaps, checkGMapsTimeout );
		} else if (GBrowserIsCompatible()) {
			BWPMapInstance.init();
		}
	};
	checkGMaps();
}
BWPMap.prototype = {
	bounds: null,
	map: null,
	/**
	 * Initializes the map with the company markers
	 */
	init: function() {
		if (this.companies.length < 1) return;
		
		var map = this.map = new GMap2(document.getElementById(this.container.id));
		map.addControl(new GSmallMapControl());
		
		var bounds = this.getBounds();
		var zoom    = map.getBoundsZoomLevel(bounds) > 14 ? 14 : map.getBoundsZoomLevel(bounds); 
		map.setCenter(bounds.getCenter(), zoom);
		
		this.markers = [];
		
		var selected = null;
		for (var i = 0, c = this.companies.length; i < c; i++) {
			var company = this.companies[i];
			var marker  = this.addMarker(
				'<h3><a href="/description.php?id=' + company.id + '">' + company.lastname + '</a></h3>' + '<p>' + company.street + '<br />' + company.city + ', ' + company.state + '</p>',
				company.latitude,
				company.longitude);
			var cname  = $$('#company-' + company.id + ' .name');
			
			if (cname.length) {
				cname[0].appendChild(this.createLink(marker));
			}
			if (company.selected) {
				selected = marker;
			}
		}
		if (selected != null) {
			this.centerOn(selected);
		}
		
		this.map = map;
	},
	/**
	 * Resize the map
	 */
	resize: function (size) {
		this.map.setCenter(this.getBounds().getCenter());
	},
	/**
	 * Returns the bounds of the companies
	 */
	getBounds: function() {
		var bounds = new GLatLngBounds(0, 0);
		for (var i = 0, c = this.companies.length; i < c; i++) {
			bounds.extend(new GLatLng(this.companies[i].latitude, this.companies[i].longitude));
		}
		if (!this.bounds) {
			this.bounds = bounds;
		}
		return bounds;
	},
	/**
	 * Add marker to the map.
	 *
	 * Returns the marker added. May be the same
	 * marker as another if the latitude and longitude
	 * are the same.
	 */
	addMarker: function (text, latitude, longitude) {
		if (!this.genericIcon) {
			this.genericIcon = new GIcon();
			this.genericIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			this.genericIcon.iconSize = new GSize(20, 34);
			this.genericIcon.shadowSize = new GSize(37, 34);
			this.genericIcon.iconAnchor = new GPoint(9, 34);
			this.genericIcon.infoWindowAnchor = new GPoint(9, 2);
			this.genericIcon.infoShadowAnchor = new GPoint(18, 25);
		}
		// finds a marker at this position
		var marker = null;
		for (var i = 0, c = this.markers.length; i < c && marker == null; i++) {
			var ll = this.markers[i].getLatLng();
			if (ll.lat() == latitude && ll.lng() == longitude) {
				marker = this.markers[i];
				marker.popuptext += this.separator + text;
			}
		}
		if (marker == null) {
			// creates it
			var icon = new GIcon(this.genericIcon);
			icon.image = 'http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/marker' + (this.markers.length + 1) + '.png';
			marker = new GMarker(new GLatLng(latitude, longitude), {icon: icon});
			marker.popuptext = text;
			GEvent.addListener(marker, 'click', function () {
				this.openInfoWindow(this.popuptext);
			});
			this.map.addOverlay(marker);
			this.markers.push(marker);
		}
		return marker;
	},
	/** 
	 * Creates a link to the marker on the map.
	 *
	 * Clicking the returned anchor centers the map
	 * on the node and opens the info panel.
	 * 
	 * @param GMarker maker
	 * @return Node The anochor HTML node.
	 */
	createLink: function (marker) {
		var a = document.createElement('a');
		a.href='#';
		a.className = 'marker';
		
		var img = document.createElement('img');
		img.src = marker.getIcon().image;
		a.appendChild(img);
		
		$(a).addEvent('click', function () {
			this.centerOn(marker);
			return false;
		}.bindWithEvent(this));
		
		return a;
	},
	/**
	 * Function centers the map on the given
	 * marker.
	 *
	 * @param GMaker marker The marker to center on
	 */
	centerOn: function (marker) {
		this.map.setCenter(marker.getLatLng());
		marker.openInfoWindow(marker.popuptext);
	}
}

