

var ACCOMSEARCH = {};
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
ACCOMSEARCH.gui = (function () {
	// private variables
    var _xScroll, _yScroll;
    
    // private methods
    
    // public methods
    return {
    	getPageSize: function() {
    
		    if (window.innerHeight && window.scrollMaxY) {    
		        xScroll = document.body.scrollWidth;
		        yScroll = window.innerHeight + window.scrollMaxY;
		    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		        xScroll = document.body.scrollWidth;
		        yScroll = document.body.scrollHeight;
		    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		        xScroll = document.body.offsetWidth;
		        yScroll = document.body.offsetHeight;
		    }
		    
		    var windowWidth, windowHeight;
		    if (self.innerHeight) {    // all except Explorer
		        windowWidth = self.innerWidth;
		        windowHeight = self.innerHeight;
		    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		        windowWidth = document.documentElement.clientWidth;
		        windowHeight = document.documentElement.clientHeight;
		    } else if (document.body) { // other Explorers
		        windowWidth = document.body.clientWidth;
		        windowHeight = document.body.clientHeight;
		    }    
		    
		    // for small pages with total height less then height of the viewport
		    if(yScroll < windowHeight){
		        pageHeight = windowHeight;
		    } else { 
		        pageHeight = yScroll;
		    }
		
		    // for small pages with total width less then width of the viewport
		    if(xScroll < windowWidth){    
		        pageWidth = windowWidth;
		    } else {
		        pageWidth = xScroll;
		    }
		
		    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		    return arrayPageSize;
		},
		checkBookLinks: function (location_id) {
			calendar = $('vnBookingCalendar');
			if (calendar.getHeight() < 100) {
				$('booking-calendar').hide();
				$$('#listing-view a.booking-link').each(function(e) {
					e.href="/search/cantbook?location_id="+location_id;
					e.location_id = location_id
					e.onclick = function() {	window.open('/search/cantbook?location_id='+e.location_id, 'popup', 'location=no, toolbar=no, menubar=no, scrollbars, resizable, width=600, height=400');
												return false};
					});
				//update the visit counts to not include these visits
				new Ajax.Request('/search/cantbook?location_id='+location_id, {asynchronous:true, evalScripts:false})
			}
		},
		checkProductBookableFromCalendar: function () {
			$$('iframe.booking-calendar').each(function(e) {
				if (e.getHeight() < 100) {
					e.hide();
					id_parts = e.id.split('-');
					//update the visit counts to not include these visits
					new Ajax.Request('/search/cantbook?product_id='+id_parts[1], {asynchronous:true, evalScripts:false})
				}
			});
		}
    };
})();



ACCOMSEARCH.searchMap = (function () {
    // private variables
    var _divIdSmall, _divIdLarge, _pinImage, _pinShadow, _zoomLevel, _map, _bounds, _mgr, _page, _limit;
	var _markers = Array;
	var _markersNew = Array;
	var _markersFinal = Array;
	
    _divId     = 'search-map';
    _zoomLevel = 16;
    
    // private methods
    var _createIcon;

    _createIcon = function () {
        var icon;
        icon = new GIcon();
        return icon;
    };
    
    // public methods
    return {
        lat: undefined,
        lon: undefined,
        current_highlight: null,
        updateList: false,
        defaultExampleKeywords: '',
        /**
         * Initialise the state of the map
         */
        init: function () {
            var latLng, icon, marker;
            if (GBrowserIsCompatible()) {
                _map = new GMap2($(_divId));
                _map.addControl(new GLargeMapControl());
                _map.enableContinuousZoom();
                _map.addControl(new GHierarchicalMapTypeControl());
		        _map.addMapType(G_PHYSICAL_MAP);
            }
        },
        initMini: function () {
            var latLng, icon, marker;
            if (GBrowserIsCompatible()) {
                _map = new GMap2($(_divId));
                _map.addControl(new GSmallMapControl());
                _map.enableContinuousZoom();
            }
        },
        gotoExtents: function () {
        	if (null != ACCOMSEARCH.searchMap.bounds) {
               	_map.setCenter(ACCOMSEARCH.searchMap.bounds.getCenter());
				_map.setZoom(_map.getBoundsZoomLevel(ACCOMSEARCH.searchMap.bounds));	
			}else{
				latLng = new GLatLng(ACCOMSEARCH.searchMap.lat, ACCOMSEARCH.searchMap.lng);
				_map.setCenter(latLng, ACCOMSEARCH.searchMap.zoom);
			}
        
        },
        
        queueSearch: function (reset) {
        	 _searchEventQueue = new ACCOMSEARCH.searchMap.extentsChanged( {position:'front', queue:{position: 'start', scope: 'getSearch'}, limit:1, delay:0.5, fps:1.0}, reset );
        },
        listenForMapChange: function () {
        	GEvent.addListener(_map, "moveend", function() {
				ACCOMSEARCH.searchMap.queueSearch();
				ACCOMSEARCH.searchMap.setListViewParams();
				$('ex').value = ACCOMSEARCH.searchMap.getExtents();
	        });
	        
        },
        
        
        /**
        * Set the values for lat and lon
        *
        * @param object coords Hash containing lat and lon values
        */
        setLatLon: function (coords) {
            ACCOMSEARCH.searchMap.lat = coords.lat;
            ACCOMSEARCH.searchMap.lng = coords.lng;
        },
        
        updateList: function (update) {
        	ACCOMSEARCH.searchMap.updateList = update;
        },
        /**
        * Set the value for the zoom
        *
        * @param int zoom level
        */
        setZoom: function (zoom) {
            ACCOMSEARCH.searchMap.zoom = zoom;
        },
        
        getExtents: function () {
        	bounds = _map.getBounds();
            return (bounds.getSouthWest().lng()+','+bounds.getSouthWest().lat()+','+bounds.getNorthEast().lng()+','+bounds.getNorthEast().lat())
        },
        clearResults: function () {
        	_markers = [];
        	$('search-list-results').innerHTML = '';
            _map.clearOverlays();
           // _mgr.clearMarkers();
        },
        processXml: function (t) {
	        var ajaxResponse = Try.these(
	            function() { return new DOMParser().parseFromString(t, 'text/xml'); },
	            function() { var xmldom = new ActiveXObject('Microsoft.XMLDOM'); xmldom.loadXML(t); return xmldom;}
	        );
	        if (ajaxResponse){
	            var cards = ajaxResponse.getElementsByTagName('listing');
	            if (ACCOMSEARCH.searchMap.updateList) {
		            var paginator = ajaxResponse.getElementsByTagName('pagination')[0];
		            paginator_cdata=paginator.childNodes;
					for (j=0;j<paginator_cdata.length;j++)
					{ 
						
						if(paginator_cdata[j].nodeName == '#cdata-section'){
							paginator_html = paginator_cdata[j].data; 
						}
	            	}
	            	$('paginator').innerHTML =paginator_html;
		        }
				var current_highlight = null;
				_markersNew = [];
				_markersFinal = [];
				
				$('search-list-results').innerHTML = '';
	            for (var i=0;i<cards.length;i++)
	            {
	            	
	            	//Get the coordinates, name etc
	            	Placemark = cards[i].getElementsByTagName('Placemark')[0];
	            	Placemark_desc = Placemark.getElementsByTagName('description')[0];
	            	
	            	Placemark_title = Placemark.getElementsByTagName('name')[0].firstChild.nodeValue;
	            	
	            	location_id = Placemark.getAttribute('id');
	            	
            		cdata=Placemark_desc.childNodes;
					for (j=0;j<cdata.length;j++)
					{ 
						
						if(cdata[j].nodeName == '#cdata-section'){
							card_blurb = cdata[j].data; 
						}
	            	}
	            	if (ACCOMSEARCH.searchMap.updateList) {
		                var div_wrapper = document.createElement('div');
		            	div_wrapper.innerHTML = card_blurb;
		            	div_wrapper.id = location_id;
		            	div_wrapper.original_class = '';
		            	div_wrapper.onmouseover = function () {
		            		if (current_highlight != _markers[this.id]) {
			            		current_highlight = _markers[this.id];
		            		}
		            		current_highlight.setImage('/images/markeryellow.png');
		            		this.className = 'card_hover';
		            	}
		            	div_wrapper.onmouseout = function () {
		            		this.className = this.original_class;
		            		current_highlight.setImage(G_DEFAULT_ICON.image);
		            	}
		            	$('search-list-results').appendChild(div_wrapper);
	            	}
	            	latlng = Placemark.getElementsByTagName('Point')[0].getElementsByTagName('coordinates')[0].firstChild.nodeValue;
	                alatlng = latlng.split(",");
	                glatLng = new GLatLng(alatlng[0], alatlng[1]);
	                 _markersNew[location_id] = ACCOMSEARCH.searchMap.addMarker(location_id, div_wrapper.id, glatLng, Placemark_title, card_blurb );
	            }
	            
				for ( keyVar in _markers ) {
					match = false;
					for ( keyVarNew in _markersNew ) {
	            		if (keyVarNew == keyVar){
	            			match = true;
	            		}
	            	}
	            	if (match) {
	            		_markersFinal[keyVar] = _markers[keyVar];
	            	}else{
	            		_map.removeOverlay(_markers[keyVar]);
	            	}
	            }
	            _markers = _markersFinal;

	        }
	        
	        
        },
        zoomTo : function (latlng, zoom) {
        	_map.setCenter(latlng, zoom);
        },
        zoomToMarker: function (id) {
        	if (this.current_highlight != _markers[id] || this.current_highlight == null) {
          		this.current_highlight = _markers[id];
         	}
         	ACCOMSEARCH.searchMap.zoomTo(this.current_highlight.getPoint(), 16);
         	
        },
        highlightMarker: function (id, unset_others, zoom_to) {
        	if (unset_others && !(undefined == this.current_highlight || this.current_highlight == null)) {
         		this.current_highlight.setImage(G_DEFAULT_ICON.image);
        		this.current_highlight == null
         	}
        	if (this.current_highlight != _markers[id] || this.current_highlight == null) {
          		this.current_highlight = _markers[id];
         	}
         	this.current_highlight.setImage('/images/markeryellow.png');
         	if (zoom_to) {
         		_map.setCenter(this.current_highlight.getPoint());
         		
         	}
         	
        },
        unHighlightMarker: function (id) {
         	if (this.current_highlight != _markers[id] || this.current_highlight == null) {
          		this.current_highlight = _markers[id];
         	}
         	this.current_highlight.setImage(G_DEFAULT_ICON.image);
        	this.current_highlight == null
        },
        addMarker: function (location_id, div_wrapper_id, glatLng, Placemark_title, card_blurb) {
            options = {
                title     : Placemark_title
            };
           	if (undefined == _markers[location_id]) {
                marker  = new GMarker(glatLng, options);
                if(div_wrapper_id != null){
	                //link back to the marker
	            	marker.div_wrapper_id = div_wrapper_id;
	                GEvent.addListener(marker,"mouseover", function() {
	        				$(this.div_wrapper_id).addClassName('card_hover');
	                        this.setImage('/images/markeryellow.png');
	                }); 
	                GEvent.addListener(marker,"mouseout", function() {
	                        $(this.div_wrapper_id).removeClassName('card_hover');
	                        this.setImage(G_DEFAULT_ICON.image);
	                }); 
	            }
                if (null != card_blurb) {
            		marker.bindInfoWindowHtml(card_blurb, {maxWidth: '400'});
            	}
           		_markers[location_id] = marker;
           		_map.addOverlay(marker);
           	}
           	return marker;
        },
        /**
        * Sets up the list view link
    	*
    	**/
    	setListViewParams: function () {
    		listLink = $('a-list-view');
    		rl = $F('rl');
    		ru = $F('ru');
    		kw = $F('kw');
    		sd = $F('sd');
    		fd = $F('fd');
    		
    		if (kw == ACCOMSEARCH.searchMap.defaultExampleKeywords) {
    			kw = '';
    		}
    		q = $F('q');
    		sortby = $F('sb');
    		currentExtents = ACCOMSEARCH.searchMap.getExtents();
    		listLink.href = '/accommodation?kw='+kw + '&sd=' + sd + '&fd='+ fd + '&ru='+ rl + '&ru=' + ru + '&sb=' + sortby + '&ex=' + currentExtents
    		
    	},
        resizePageElements: function () {
        	mapHeightAdjust = 109;
        	listHeightAdjust = 125;
	        mapWidthAdjust = $('search-list').getStyle('width');
	        bodyPaddingLeft = $('map-view').getStyle('padding-left');
	        bodyPaddingRight = $('map-view').getStyle('padding-right');
	        
	        mapWidthAdjust = mapWidthAdjust.replace(/px/,'');
	        bodyPaddingLeft = bodyPaddingLeft.replace(/px/,'');
	        bodyPaddingRight = bodyPaddingRight.replace(/px/,'');
	        
	        var aWindowDim = ACCOMSEARCH.gui.getPageSize();
	        $('search-map').style.height=aWindowDim[3] - mapHeightAdjust +'px';
	        $('search-map').style.width=aWindowDim[2] - mapWidthAdjust -2 +'px';
	        $('search-list').style.height = aWindowDim[3] - 8 - listHeightAdjust  +'px'
        },
        windowResize: function () {
	        ACCOMSEARCH.searchMap.resizePageElements();
	        _map.checkResize();
	        GEvent.trigger(_map, "moveend");
	    },
	    setBounds: function (bounds) {
	    	
	    	ACCOMSEARCH.searchMap.bounds = new GLatLngBounds();
	    	var bounds_array = bounds.split(',');
	    	swlatlng = new GLatLng(bounds_array[1],  bounds_array[0], true);
	    	nelatlng = new GLatLng(bounds_array[3],  bounds_array[2], true);
			ACCOMSEARCH.searchMap.bounds.extend(nelatlng);
			ACCOMSEARCH.searchMap.bounds.extend(swlatlng);
			
	    },
        setPage: function (page) {
        	_page = page;
        },
        setLimit: function (limit) {
        	_limit = limit;
        },
        requestListings: function (reset) {
		    extents = ACCOMSEARCH.searchMap.getExtents();
		    new Ajax.Request('/search/results',
			    {
		            method:'post',
		            parameters: 'ex='+extents+'&kw='+$F('kw')+'&sd='+$F('sd') + '&fd='+$F('fd') + '&rl='+$F('rl') +'&ru='+$F('ru')+'&sb='+$F('sb')+'&page='+_page+'&limit='+_limit,
		            asynchronous:true,
		            evalScripts:false,
		            onSuccess:function(request)
		            {
		            	
		                ACCOMSEARCH.searchMap.processXml(request.responseText)
		            }
		        });
		}
    };
})();

ACCOMSEARCH.searchMap.extentsChanged = Class.create();

Object.extend(Object.extend(ACCOMSEARCH.searchMap.extentsChanged.prototype, Effect.Base.prototype), {
  initialize: function() {
    Effect.Queues.get('getSearch').each(function(e){ e.cancelled = true; e.cancel('cancelled by another event') });
    this.resetSearch = arguments[1];
    this.start(arguments[0]);
    
  },
  setup: function() {
    this.cancelled = false;
  },
  loop: function(timePos){
        if(timePos >= this.startOn) {
            this.cancel("cancelled from loop");
            this.finish();
        }
  },
  cancel: function(msg) {
    Effect.Queues.get('getSearch').remove(this);
    this.state = 'finished';
  },

  update: function(position) {
  },

  finish: function() {
    if (this.cancelled != true) {
        ACCOMSEARCH.searchMap.requestListings(this.resetSearch);
    }
  }
});


