//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.

MooTools.More={version:"1.2.5.1",build:"254884f2b83651bf95260eed5c6cceb838e22d8e"};(function(){var c=this;var b=function(){if(c.console&&console.log){try{console.log.apply(console,arguments);
}catch(d){console.log(Array.slice(arguments));}}else{Log.logged.push(arguments);}return this;};var a=function(){this.logged.push(arguments);return this;
};this.Log=new Class({logged:[],log:a,resetLog:function(){this.logged.empty();return this;},enableLog:function(){this.log=b;this.logged.each(function(d){this.log.apply(this,d);
},this);return this.resetLog();},disableLog:function(){this.log=a;return this;}});Log.extend(new Log).enableLog();Log.logger=function(){return this.log.apply(this,arguments);
};})();String.implement({parseQueryString:function(d,a){if(d==null){d=true;}if(a==null){a=true;}var c=this.split(/[&;]/),b={};if(c.length){c.each(function(i){var e=i.indexOf("="),f=e<0?[""]:i.substr(0,e).match(/([^\]\[]+|(\B)(?=\]))/g),g=a?decodeURIComponent(i.substr(e+1)):i.substr(e+1),h=b;
f.each(function(k,j){if(d){k=decodeURIComponent(k);}var l=h[k];if(j<f.length-1){h=h[k]=l||{};}else{if($type(l)=="array"){l.push(g);}else{h[k]=$defined(l)?[l,g]:g;
}}});});}return b;},cleanQueryString:function(a){return this.split("&").filter(function(e){var b=e.indexOf("="),c=b<0?"":e.substr(0,b),d=e.substr(b+1);
return a?a.run([c,d]):$chk(d);}).join("&");}});var URI=new Class({Implements:Options,options:{},regex:/^(?:(\w+):)?(?:\/\/(?:(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)?(\.\.?$|(?:[^?#\/]*\/)*)([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,parts:["scheme","user","password","host","port","directory","file","query","fragment"],schemes:{http:80,https:443,ftp:21,rtsp:554,mms:1755,file:0},initialize:function(b,a){this.setOptions(a);
var c=this.options.base||URI.base;if(!b){b=c;}if(b&&b.parsed){this.parsed=$unlink(b.parsed);}else{this.set("value",b.href||b.toString(),c?new URI(c):false);
}},parse:function(c,b){var a=c.match(this.regex);if(!a){return false;}a.shift();return this.merge(a.associate(this.parts),b);},merge:function(b,a){if((!b||!b.scheme)&&(!a||!a.scheme)){return false;
}if(a){this.parts.every(function(c){if(b[c]){return false;}b[c]=a[c]||"";return true;});}b.port=b.port||this.schemes[b.scheme.toLowerCase()];b.directory=b.directory?this.parseDirectory(b.directory,a?a.directory:""):"/";
return b;},parseDirectory:function(b,c){b=(b.substr(0,1)=="/"?"":(c||"/"))+b;if(!b.test(URI.regs.directoryDot)){return b;}var a=[];b.replace(URI.regs.endSlash,"").split("/").each(function(d){if(d==".."&&a.length>0){a.pop();
}else{if(d!="."){a.push(d);}}});return a.join("/")+"/";},combine:function(a){return a.value||a.scheme+"://"+(a.user?a.user+(a.password?":"+a.password:"")+"@":"")+(a.host||"")+(a.port&&a.port!=this.schemes[a.scheme]?":"+a.port:"")+(a.directory||"/")+(a.file||"")+(a.query?"?"+a.query:"")+(a.fragment?"#"+a.fragment:"");
},set:function(b,d,c){if(b=="value"){var a=d.match(URI.regs.scheme);if(a){a=a[1];}if(a&&!$defined(this.schemes[a.toLowerCase()])){this.parsed={scheme:a,value:d};
}else{this.parsed=this.parse(d,(c||this).parsed)||(a?{scheme:a,value:d}:{value:d});}}else{if(b=="data"){this.setData(d);}else{this.parsed[b]=d;}}return this;
},get:function(a,b){switch(a){case"value":return this.combine(this.parsed,b?b.parsed:false);case"data":return this.getData();}return this.parsed[a]||"";
},go:function(){document.location.href=this.toString();},toURI:function(){return this;},getData:function(c,b){var a=this.get(b||"query");if(!$chk(a)){return c?null:{};
}var d=a.parseQueryString();return c?d[c]:d;},setData:function(a,c,b){if(typeof a=="string"){data=this.getData();data[arguments[0]]=arguments[1];a=data;
}else{if(c){a=$merge(this.getData(),a);}}return this.set(b||"query",Hash.toQueryString(a));},clearData:function(a){return this.set(a||"query","");}});URI.prototype.toString=URI.prototype.valueOf=function(){return this.get("value");
};URI.regs={endSlash:/\/$/,scheme:/^(\w+):/,directoryDot:/\.\/|\.$/};URI.base=new URI(document.getElements("base[href]",true).getLast(),{base:document.location});
String.implement({toURI:function(a){return new URI(this,a);}});Element.implement({tidy:function(){this.set("value",this.get("value").tidy());},getTextInRange:function(b,a){return this.get("value").substring(b,a);
},getSelectedText:function(){if(this.setSelectionRange){return this.getTextInRange(this.getSelectionStart(),this.getSelectionEnd());}return document.selection.createRange().text;
},getSelectedRange:function(){if($defined(this.selectionStart)){return{start:this.selectionStart,end:this.selectionEnd};}var e={start:0,end:0};var a=this.getDocument().selection.createRange();
if(!a||a.parentElement()!=this){return e;}var c=a.duplicate();if(this.type=="text"){e.start=0-c.moveStart("character",-100000);e.end=e.start+a.text.length;
}else{var b=this.get("value");var d=b.length;c.moveToElementText(this);c.setEndPoint("StartToEnd",a);if(c.text.length){d-=b.match(/[\n\r]*$/)[0].length;
}e.end=d-c.text.length;c.setEndPoint("StartToStart",a);e.start=d-c.text.length;}return e;},getSelectionStart:function(){return this.getSelectedRange().start;
},getSelectionEnd:function(){return this.getSelectedRange().end;},setCaretPosition:function(a){if(a=="end"){a=this.get("value").length;}this.selectRange(a,a);
return this;},getCaretPosition:function(){return this.getSelectedRange().start;},selectRange:function(e,a){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,a);
}else{var c=this.get("value");var d=c.substr(e,a-e).replace(/\r/g,"").length;e=c.substr(0,e).replace(/\r/g,"").length;var b=this.createTextRange();b.collapse(true);
b.moveEnd("character",e+d);b.moveStart("character",e);b.select();}return this;},insertAtCursor:function(b,a){var d=this.getSelectedRange();var c=this.get("value");
this.set("value",c.substring(0,d.start)+b+c.substring(d.end,c.length));if($pick(a,true)){this.selectRange(d.start,d.start+b.length);}else{this.setCaretPosition(d.start+b.length);
}return this;},insertAroundCursor:function(b,a){b=$extend({before:"",defaultMiddle:"",after:""},b);var c=this.getSelectedText()||b.defaultMiddle;var g=this.getSelectedRange();
var f=this.get("value");if(g.start==g.end){this.set("value",f.substring(0,g.start)+b.before+c+b.after+f.substring(g.end,f.length));this.selectRange(g.start+b.before.length,g.end+b.before.length+c.length);
}else{var d=f.substring(g.start,g.end);this.set("value",f.substring(0,g.start)+b.before+d+b.after+f.substring(g.end,f.length));var e=g.start+b.before.length;
if($pick(a,true)){this.selectRange(e,e+d.length);}else{this.setCaretPosition(e+f.length);}}return this;}});Request.JSONP=new Class({Implements:[Chain,Events,Options,Log],options:{url:"",data:{},retries:0,timeout:0,link:"ignore",callbackKey:"callback",injectScript:document.head},initialize:function(a){this.setOptions(a);
if(this.options.log){this.enableLog();}this.running=false;this.requests=0;this.triesRemaining=[];},check:function(){if(!this.running){return true;}switch(this.options.link){case"cancel":this.cancel();
return true;case"chain":this.chain(this.caller.bind(this,arguments));return false;}return false;},send:function(c){if(!$chk(arguments[1])&&!this.check(c)){return this;
}var e=$type(c),a=this.options,b=$chk(arguments[1])?arguments[1]:this.requests++;if(e=="string"||e=="element"){c={data:c};}c=$extend({data:a.data,url:a.url},c);
if(!$chk(this.triesRemaining[b])){this.triesRemaining[b]=this.options.retries;}var d=this.triesRemaining[b];(function(){var f=this.getScript(c);this.log("JSONP retrieving script with url: "+f.get("src"));
this.fireEvent("request",f);this.running=true;(function(){if(d){this.triesRemaining[b]=d-1;if(f){f.destroy();this.send(c,b).fireEvent("retry",this.triesRemaining[b]);
}}else{if(this.running&&f&&this.options.timeout){f.destroy();this.cancel().fireEvent("failure");}}}).delay(this.options.timeout,this);}).delay(Browser.Engine.trident?50:0,this);
return this;},cancel:function(){if(!this.running){return this;}this.running=false;this.fireEvent("cancel");return this;},getScript:function(c){var b=Request.JSONP.counter,d;
Request.JSONP.counter++;switch($type(c.data)){case"element":d=document.id(c.data).toQueryString();break;case"object":case"hash":d=Hash.toQueryString(c.data);
}var e=c.url+(c.url.test("\\?")?"&":"?")+(c.callbackKey||this.options.callbackKey)+"=Request.JSONP.request_map.request_"+b+(d?"&"+d:"");if(e.length>2083){this.log("JSONP "+e+" will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs");
}var a=new Element("script",{type:"text/javascript",src:e});Request.JSONP.request_map["request_"+b]=function(){this.success(arguments,a);}.bind(this);return a.inject(this.options.injectScript);
},success:function(b,a){if(!this.running){return false;}if(a){a.destroy();}this.running=false;this.log("JSONP successfully retrieved: ",b);this.fireEvent("complete",b).fireEvent("success",b).callChain();
}});Request.JSONP.counter=0;Request.JSONP.request_map={};Hash.Cookie=new Class({Extends:Cookie,options:{autoSave:true},initialize:function(b,a){this.parent(b,a);
this.load();},save:function(){var a=JSON.encode(this.hash);if(!a||a.length>4096){return false;}if(a=="{}"){this.dispose();}else{this.write(a);}return true;
},load:function(){this.hash=new Hash(JSON.decode(this.read(),true));return this;}});Hash.each(Hash.prototype,function(b,a){if(typeof b=="function"){Hash.Cookie.implement(a,function(){var c=b.apply(this.hash,arguments);
if(this.options.autoSave){this.save();}return c;});}});

(function(){var a=function(c,b){return(c)?($type(c)=="function"?c(b):b.get(c)):"";
};this.Tips=new Class({Implements:[Events,Options],options:{onShow:function(){this.tip.setStyle("display","block");},onHide:function(){this.tip.setStyle("display","none");
},title:"title",text:function(b){return b.get("rel")||b.get("href");},showDelay:100,hideDelay:100,className:"tip-wrap",offset:{x:16,y:16},windowPadding:{x:0,y:0},fixed:false},initialize:function(){var b=Array.link(arguments,{options:Object.type,elements:$defined});
this.setOptions(b.options);if(b.elements){this.attach(b.elements);}this.container=new Element("div",{"class":"tip"});},toElement:function(){if(this.tip){return this.tip;
}return this.tip=new Element("div",{"class":this.options.className,styles:{position:"absolute",top:0,left:0}}).adopt(new Element("div",{"class":"tip-top"}),this.container,new Element("div",{"class":"tip-bottom"}));
},attach:function(b){$$(b).each(function(d){var f=a(this.options.title,d),e=a(this.options.text,d);d.erase("title").store("tip:native",f).retrieve("tip:title",f);
d.retrieve("tip:text",e);this.fireEvent("attach",[d]);var c=["enter","leave"];if(!this.options.fixed){c.push("move");}c.each(function(h){var g=d.retrieve("tip:"+h);
if(!g){g=this["element"+h.capitalize()].bindWithEvent(this,d);}d.store("tip:"+h,g).addEvent("mouse"+h,g);},this);},this);return this;},detach:function(b){$$(b).each(function(d){["enter","leave","move"].each(function(e){d.removeEvent("mouse"+e,d.retrieve("tip:"+e)).eliminate("tip:"+e);
});this.fireEvent("detach",[d]);if(this.options.title=="title"){var c=d.retrieve("tip:native");if(c){d.set("title",c);}}},this);return this;},elementEnter:function(c,b){this.container.empty();
["title","text"].each(function(e){var d=b.retrieve("tip:"+e);if(d){this.fill(new Element("div",{"class":"tip-"+e}).inject(this.container),d);}},this);$clear(this.timer);
this.timer=(function(){this.show(b);this.position((this.options.fixed)?{page:b.getPosition()}:c);}).delay(this.options.showDelay,this);},elementLeave:function(c,b){$clear(this.timer);
this.timer=this.hide.delay(this.options.hideDelay,this,b);this.fireForParent(c,b);},fireForParent:function(c,b){b=b.getParent();if(!b||b==document.body){return;
}if(b.retrieve("tip:enter")){b.fireEvent("mouseenter",c);}else{this.fireForParent(c,b);}},elementMove:function(c,b){this.position(c);},position:function(e){if(!this.tip){document.id(this);
}var c=window.getSize(),b=window.getScroll(),f={x:this.tip.offsetWidth,y:this.tip.offsetHeight},d={x:"left",y:"top"},g={};for(var h in d){g[d[h]]=e.page[h]+this.options.offset[h];
if((g[d[h]]+f[h]-b[h])>c[h]-this.options.windowPadding[h]){g[d[h]]=e.page[h]-this.options.offset[h]-f[h];}}this.tip.setStyles(g);},fill:function(b,c){if(typeof c=="string"){b.set("html",c);
}else{b.adopt(c);}},show:function(b){if(!this.tip){document.id(this);}if(!this.tip.getParent()){this.tip.inject(document.body);}this.fireEvent("show",[this.tip,b]);
},hide:function(b){if(!this.tip){document.id(this);}this.fireEvent("hide",[this.tip,b]);}});})();

var siteURL;
var staticURL;
var t;
var ga_UACC;
var paramsURI = new URI(window.location).get('data');
var map;
var catid = paramsURI.catid;
var query = paramsURI.query || false;
var loc = paramsURI.loc || false;
var zoom = paramsURI.z || false;
var static_marker = null;
var tooltip;
var pageid;
var actiontip = [];
var actionnum = 0;
var markerGroups = { "searchresults": [] };
var search_bounds = null;

var Site = {
    // Init and bind events to DOM
    start: function(){
	    var isInited = false;
	    Site.Cookie = new Hash.Cookie('user_prefs', {duration: 365});
	    if ($('search') || $('map') || $('review_search_results')) {
		    Site.resizeMapDiv();
		    window.addEvent('resize', function(){
			  Site.resizeMapDiv();
		    });
	    }
	    if ($('locationSet')) {
		$('locationSet').addEvent('submit', function(e) {
			//Prevents the default submit event from loading a new page.
			e.stop();
			Site.setLocation($('Location').value);
		});
		$('locationSet').removeEvent('submit');
	    }
	    if ($('detailed')){
	        $$('#map_canvas img').addEvent('click',function(e) {
	          e.stop();
	          Site.loadMap();
	          _gaq.push(['_trackEvent', 'MapClick', document.title ]);
	        });
	        $('map_canvas').setStyle('cursor','pointer');
	    }
        if ($('search') || $('review_search_results')) {
            Site.slideSearchMap();
        }
    },
    
    // Init google map
    loadMap: function() {
    	    // Creating an object literal containing the properties we want to pass to the map
	    var mapOptions = {
            zoom: 4,
            scrollwheel: false,
            mapTypeControlOptions: {
	            mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE,],
	        },
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
    	map = new google.maps.Map($('map_canvas'),mapOptions);
        if ($('map')) {
              directionsService = new google.maps.DirectionsService();
              directionsDisplay = new google.maps.DirectionsRenderer();
              directionsDisplay.setMap(map);
              directionsDisplay.setPanel(document.getElementById("results_container"));
        }
	    // Try to determine user location in diferent ways
	    // by url link, by saved location from previous useor  by google clientLocation
	    if (loc && zoom) {
			var ll = new Array();
			ll = loc.split(',');
			var z = zoom;
			var latlng = new google.maps.LatLng(ll[0],ll[1]);
			map.setCenter(latlng);
			map.setZoom(zoom);

			if (catid) Site.getGeoResults(catid);

	    } else if (Cookie.read('_location') && static_marker == null && !$('modify') && !$('add') && !$('review_search_results')) {
            Site.setLocation(Cookie.read('_location'));
	    } else if ($('Location')) {
            Site.setLocation($('Location').value);
	    } else if (google.loader.ClientLocation && !$('detailed')) {
            var currentLocation;
            currentLocation = google.loader.ClientLocation;
            var clientLatlng = new google.maps.LatLng (currentLocation.latitude, currentLocation.longitude);
            var found_locc = currentLocation.address.city+', '+currentLocation.address.country;
		    Cookie.write('_location', found_loc, {duration: 365, path: '/'});
			if ($('Location')) {
			    $('Location').set('value',found_loc);
			}
	    } else {
	        var latlng = new google.maps.LatLng(42.730874, 25.488281);
			map.setCenter(latlng);
			map.setZoom(6);
	    }	    
	    // ====== set up marker mouseover tooltip div ======
//	    tooltip = new Element('div');
//	    tooltip.set({style:'visibility:hidden'});
//	    $('map_canvas').grab(tooltip);

	    // after you initially setCenter() your map use
	    map._lastCenter=map.getCenter();

	    // then add the event listeners
 	    google.maps.event.addListener(map, 'dragend', function() {
			map._lastCenter = map.getCenter();
	    });

	    // then add the event listeners
 	    google.maps.event.addListener(map, 'zoom_changed', function() {
			map._lastCenter = map.getCenter();
	    });


	    google.maps.event.addListener(map, 'resize', function() { map.setCenter(map._lastCenter); }); 

	    var bounds = new google.maps.LatLngBounds();
	    if (static_marker && static_marker != null) {
        	// Set up single marker with info window
		    var point = new google.maps.LatLng(parseFloat(static_marker.latitude), parseFloat(static_marker.longitude));
		    Site.CreateMarker(point,1);
		    map.setCenter(point);
		    map.setZoom(15);
	    }
	    // Add ability to users to modify their bussiness position on the map
	    if ($('modify') || $('add') ) {

	        document.spot_details.Title.focus();
	    
		    if ($('Lat').value && $('Lng').value) {
				var point = new google.maps.LatLng($('Lat').value, $('Lng').value)
				map.setCenter(point);
				map.setZoom(15);
				var marker = new google.maps.Marker({ position: point, draggable: true, dragCrossMove: "False", bouncy: "False", bounceGravity: 1 });
				google.maps.event.addListener(marker, "dragend", function() {
				    var lat = new Number(marker.getPosition().lat());
				    var lng = new Number(marker.getPosition().lng());
				    $('Lat').value = lat.toFixed(7);
				    $('Lng').value = lng.toFixed(7);
				});
				marker.setMap(map);
			}
		
			$$('.gmap_field').each(function(el) {
			    el.addEvent('change', function() {
				// Get address elements
				var country = $('Country').value;
				var city = $('City').value;
				var address = $('Address').value;
				var zip = $('Zip').value;
				// Create new geocoding object
	        	geocoder = new google.maps.Geocoder();
	        	geocoder.geocode( {'address': address + ', ' + city + ' ' + zip+', ' + country}, function(response, status) {
			    if (status == google.maps.GeocoderStatus.OK) {
					var place = response[0].geometry;
					map.fitBounds(place.viewport);
                    if (marker) { marker.setMap(null); }
	                	marker = new google.maps.Marker({ position: place.location, draggable: true, map: map});
	                	map.setCenter(place.location);
	                	new google.maps.Marker(response[0].geometry.location, {draggable: true});
	                	$('Lat').value=marker.getPosition().lat().toFixed(7);
	                	$('Lng').value=marker.getPosition().lng().toFixed(7);
	                	google.maps.event.addListener(marker, "dragend", function() {
	                	    $('Lat').value=marker.getPosition().lat().toFixed(7);
				            $('Lng').value=marker.getPosition().lng().toFixed(7);
	                	});
	        	    } else {
	                	alert("Не откривам място с адрес: " + address + ', ' + city + ', ' + country);
	        	    }
	        	});
		    });
		});
	    }
	    if ($('review_search_results')) {
          Site.renderGeoResults(reviews);
	    }
    },

    // Resize based off Googles code.
    resizeMapDiv: function() {
	// Return the window height
		function getWindowHeight() {
		    if (window.self&&self.innerHeight) {
				return self.innerHeight;
		    }
		    if (document.documentElement&&document.documentElement.clientHeight) {
				return document.documentElement.clientHeight;
		    }
		    if (document.body && document.body.clientHeight) {
				return windowHeight = document.body.clientHeight;
		    }
		    return 0;
		}

        var offsetTop = 0;
        var mapDiv = document.getElementById("map_canvas");
        for (var elem = mapDiv; elem; elem = elem.offsetParent){
            offsetTop += elem.offsetTop;
        }
		var height = getWindowHeight() - offsetTop - 30;
		if (height >= 0) {
            mapDiv.style.height = height + "px";
	    }
	// If the map has been created at this point then resize and alter accordingly
    },

    slideSearchMap: function() {
        var element = $('rightsidebar');
        if ($('contentheader')) {
            var top_offset = $('contentheader').getStyle('margin-bottom').toInt();
        } else {
            var top_offset = $('navbar').getStyle('margin-bottom').toInt();
        }
        var top = $('ocwrapper').getPosition().y - top_offset;

        var fx = new Fx.Morph(element, {
                                        wait:false,
                                        duration:400,
                                        transition: 'expo:in:out'
        });

        window.addEvent('scroll', function(){
            var scroll_pos = window.getScrollTop();
            var max_pos = ($('ocwrapper').getSize().y + top) - element.getSize().y;

            if (max_pos > top) {
                if (scroll_pos >= top) {
                    element.addClass('sliding');
                } else if (scroll_pos < top) {
                    element.removeClass('sliding');
                }

                if (scroll_pos > (max_pos)) {
                    element.removeClass('sliding');
                    element.setStyle('top', max_pos + top_offset );
                    element.addClass('bottom');
                } else {
                    element.removeClass('bottom');
                    element.setStyle('top', '');
                }
            }
        });
    },

    getDirections: function() {
      var start = document.getElementById("start").value;
      var end = new google.maps.LatLng(parseFloat(static_marker.latitude), parseFloat(static_marker.longitude));
      var request = {
          origin:start,
          destination:end,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          var contentDiv = $('content');
          var ocwrapperDiv = $('ocwrapper');
          var rightsidebarDiv = $('rightsidebar');
          var directionsDiv = $('results_container');
          ocwrapperDiv.setStyles({borderRightWidth: 340, marginRight: 340 });
          rightsidebarDiv.setStyle("display","block");
          directionsDisplay.setDirections(response);
          directionsDiv.setStyle("height", $('content').getSize().y-20);
        }
      });
    },

    setLocation: function(location) {
        // Create new geocoding object
		var address = location;
        geocoder = new google.maps.Geocoder();
		var viewport = new google.maps.LatLngBounds();
		geocoder.geocode( { 'address': address}, function(response, status) {
    	    if (status == google.maps.GeocoderStatus.OK) {
    	        map.setCenter(response[0].geometry.location);
    	        map.fitBounds(response[0].geometry.bounds);
    			if ($('query') && $('query').value) {
    			    Site.getGeoResults(catid);
    			}
    	        Cookie.write('_location', response[0].formatted_address, {duration: 365, path: '/'});
    			if ($('Location')) {$('Location').value=response[0].formatted_address;}
    	    } else {
    	        alert('Не намирам адрес"'+address+'"');
    	    }
		});
    },

    // Fetch results for specified map boundaries
    getGeoResults: function(cat,page) {
    	pageid = page;
    	query = $('query').value;
    	var bm = 0;
    	var minx = Site.getAdjustedMapBounds().minlng; 
    	var miny = Site.getAdjustedMapBounds().minlat;
    	var maxx = Site.getAdjustedMapBounds().maxlng;
    	var maxy = Site.getAdjustedMapBounds().maxlat;

    	// Do some cleanup
    	$('result_loop').empty().addClass('ajax-loading');
    	$('paging_loop').empty();

    	var request = new Request.JSON({
    	    url: '/search.cgi',
    	    method: 'get',
    	    data: {
        	    query: query,
    	    	catid: catid,
        		'Lat-gt': miny,
        		'Lng-gt': minx,
        		'Lat-lt': maxy,
        		'Lng-lt': maxx,
        		t: 'json',
        		nh: page
        	}, onComplete: function(jsonObj) {
        		$('result_loop').removeClass('ajax-loading');
        		Site.toggleMarkerGroup('searchresults');
        		Site.loadGeoResults(jsonObj);
    	    }
    	}).send();
        try {
            _gaq.push(['_setAccount', ga_UACC]);
            _gaq.push(['_trackPageview', '/spots/?query=' + query]);
            } catch(err) {
        }
    },

    // Inject results into document and map
    loadGeoResults: function(results) {
	    var result_div = $('result_loop');
	    var paging_div = $('paging_loop');
	    result_div.empty();
	    paging_div.empty();
    	if (results.linkloop.length < 1 ) {
            $('result_loop').setProperty('html', 'Съжалявам но не намирам <strong>' + query + '</strong> в района на <strong>'
              + $('Location').value + '</strong>, моля изберете друг регион!'
              + '<br /><br />' + 'Ако <strong>' + query + '</strong> е обект защо не го добавиш. Ще отнеме само 1 мин ;)<br /><br />'
              + '<a class="red_button" href="' + siteURL + '/add/1" onClick="pageTracker._trackEvent(\'Listing\', \'Submit\', this.href );">Добави!</a>'
            );
        } else {
            var results_loop = results.linkloop;
            var next_page = results.current_page+1;
            // Render results in to the page
        	results_loop.each(function(result,index) {
        	    // Build proper html but first do rating calculations
        	    var intRating = ((result.Rating/5)*100);
        	    if (result.Votes == 1 ) {var voters = ' мнение'} else { var voters = ' мнения'}
        	    // Now inject listings
        	    var el = new Element('div', {'id':'l'+result.ID,'class': 'linklisting clear'});
        	    var info_right = new Element('div', {'class': 'info_right', 'style': 'width: 80px;' , 'html' : '<div class="rating_bar"><div style="width:' + intRating + '%"></div></div><br /><p> '+result.Votes + voters+' </p>' }).inject(el);
        	    var biz_photo_href = new Element('a', {'class':'biz_photo', 'href':result.detailed_url}).inject(el);
        	    var biz_photo = new Element('img', {'style':'float: left; margin-right: 5px;', 'width': 50, 'height': 50, 'alt': result.Title, 'src':result.biz_photo}).inject(biz_photo_href);
                var title_heading = new Element ('h4', {'class': 'linktitle'}).inject(el);
//        	    var ind = new Element('span', {'html': index+1 + '.&nbsp;'}).inject(title_heading);
        	    var title = new Element('a', {'html': result.Title, 'href':result.detailed_url}).inject(title_heading);
        	    var contact = new Element('p', {'class':'info_contact','html': result.Address+'<br />'}).inject(el);
        	    var cat = new Element ('span', {'html': result.category}).inject(contact);
        	    el.inject(result_div);
    	    });
            // Render results in to the map
            Site.renderGeoResults(results_loop);
            // Inject paging
        	paging_div.setProperty('html', results.paging);
            scroll(0,1);
            scroll(0,0);
        }
    },

    // Render results on the map
    renderGeoResults: function(results) {
        var marker = [];
        var map_bounds = new google.maps.LatLngBounds();
        // Loop trough all results and add correspondig marker to the map
        results.each(function(result,index) {
            // Add marker to map
        	var point = new google.maps.LatLng (result.Lat, result.Lng);
            marker[index] = Site.CreateMarker(point,0,result,index+1,result.ID,result.detailed_url);
        	markerGroups['searchresults'].push(marker[index]);
           	map_bounds.extend(point);
    	});
    	// Hack to stop map go below zoom level 15 beacuse it looks ugly
    	google.maps.event.addListener(map, 'zoom_changed', function() {
        zoomChangeBoundsListener = 
            google.maps.event.addListener(map, 'bounds_changed', function(event) {
                if (map.getZoom() > 15 && map.initialZoom == true) {
                    // Change max/min zoom here
                    map.setZoom(15);
                    map.initialZoom = false;
                }
                google.maps.event.removeListener(zoomChangeBoundsListener);
            });
        });
        map.initialZoom = true;
    	// Fit view port to marker boundaries
        map.fitBounds(map_bounds);
    },

    // Marker group toggler
    toggleMarkerGroup: function(group) {
        for (var i = 0; i < markerGroups[group].length; i++) {
            markerGroups[group][i].setMap(null);
        }
    },

    // Begin CreateMarker();
    CreateMarker: function(point, type, place, index, lid, url) {
	var marker;
    	if(type == 0) {
	    if(index == "") {
		    marker = new google.maps.Marker({ position: point, animation: google.maps.Animation.DROP, map: map });
	    } else {
			marker = new google.maps.Marker({ position: point, animation: google.maps.Animation.DROP, map: map });
			var rat = ((place.Rating/5)*100);
			if (place.Votes == 1 ) {var vot = ' review'} else { var vot = ' reviews'}
			if (place.Address) {place.Address = ', ' + place.Address;}
			if ($('search') || $('review_search_results')) {
			    var target = $('l' + lid);
			    target.addEvent('mouseover', function(){
                   oimg = "http://maps.google.com/mapfiles/ms/micons/yellow-dot.png";
                   marker.setIcon(oimg);
                   marker.setZIndex(1000);
			    });
			    target.addEvent('mouseout', function(){
                   marker.setIcon(null);
                   marker.setZIndex(0);
			    });
			    google.maps.event.addListener(marker, "mouseover", function()  {
			    });
			    google.maps.event.addListener(marker, "mouseout", function()  {
			    });
			}
	    }
	} else {
	    marker = new google.maps.Marker({ position: point, animation: google.maps.Animation.DROP, map: map });
	}	
    	google.maps.event.addListener(marker, "click", function()  {
	    if (url) { window.open(url) } else { map.panTo(marker.getPosition()); }
	});
	return marker;
    },
    // End of CreateMarker();

    getAdjustedMapBounds: function () {
        var mapContainer = $('map_canvas');
        var adjBounds = {};
        var topDead = 55;
        var leftDead = 65;
        var rightDead = 25;
        var bounds = map.getBounds();
        var lonPerPix = (bounds.getNorthEast().lng() - bounds.getSouthWest().lng())/mapContainer.clientWidth;
        var latPerPix = (bounds.getNorthEast().lat() - bounds.getSouthWest().lat())/mapContainer.clientHeight;

        adjBounds['minlng'] = bounds.getSouthWest().lng() + leftDead*lonPerPix;
        adjBounds['maxlng'] = bounds.getNorthEast().lng() - rightDead*lonPerPix;
        adjBounds['minlat'] = bounds.getSouthWest().lat() + rightDead*latPerPix;
        adjBounds['maxlat'] = bounds.getNorthEast().lat() - topDead*latPerPix;
        return adjBounds;
    }
};

// Javascrips aproach for paging results on map 
function setResultsPage(page) {
    Site.getGeoResults(catid,page);
}

/* page init */
window.addEvent('domready', function(){
  Site.start();
});

// Attach .tooltips
/*
window.addEvent("domready", function() {
   $$("[tooltip]").filter(function(el) {
       el.tiptext = el.get('tooltip');
       el.tooltip_options = {
           sticky: parseInt(el.get('tooltip_sticky')),
           width:  parseInt(el.get('tooltip_width'))
       };
       el.tooltip ( el.tiptext, el.tooltip_options );
   });
});
*/
