/*
 FCBKcomplete 2.6.1
 - Jquery version required: 1.2.x, 1.3.x
 
 Changelog:
 
 - 2.00	new version of fcbkcomplete
 
 - 2.01 fixed bugs & added features
 		fixed filter bug for preadded items
 		focus on the input after selecting tag
 		the element removed pressing backspace when the element is selected
 		input tag in the control has a border in IE7
 		added iterate over each match and apply the plugin separately
 		set focus on the input after selecting tag
 
 - 2.02 fixed fist element selected bug
 		fixed defaultfilter error bug
 
 - 2.5 	removed selected="selected" attribute due ie bug
 		element search algorithm changed
 		better performance fix added
 		fixed many small bugs
 		onselect event added
 		onremove event added
 		
 - 2.6 	ie6/7 support fix added
 		added new public method addItem due request
 		added new options "firstselected" that you can set true/false to select first element on dropdown list
 		autoexpand input element added
 		removeItem bug fixed
 		and many more bug fixed

 - 2.6.1
 		fixed public method to use it $("elem").trigger("addItem",[{"title": "test", "value": "test"}]);
 */

/* Coded by: emposha <admin@emposha.com> */
/* Copyright: Emposha.com <http://www.emposha.com/> - Distributed under MIT - Keep this message! */
/*
 * json_url         - url to fetch json object
 * cache       		- use cache
 * height           - maximum number of element shown before scroll will apear
 * newel            - show typed text like a element
 * firstselected	- automaticly select first element from dropdown
 * filter_case      - case sensitive filter
 * filter_selected  - filter selected items from list
 * complete_text    - text for complete page
 * maxshownitems	- maximum numbers that will be shown at dropdown list (less better performance)
 * onselect			- fire event on item select
 * onremove			- fire event on item remove
 */
jQuery(function($){$.fn.fcbkcomplete=function(opt){return this.each(function(){function init(){createFCBK();preSet();addInput(0)}function createFCBK(){element.hide();element.attr("multiple","multiple");if(element.attr("name").indexOf("[]")==-1){element.attr("name",element.attr("name")+"[]")}holder=$(document.createElement("ul"));holder.attr("class","holder");element.after(holder);complete=$(document.createElement("div"));complete.addClass("facebook-auto");complete.append('<div class="default">'+options.complete_text+"</div>");if(browser_msie){complete.append('<iframe class="ie6fix" scrolling="no" frameborder="0"></iframe>');browser_msie_frame=complete.children('.ie6fix')}feed=$(document.createElement("ul"));feed.attr("id",elemid+"_feed");complete.prepend(feed);holder.after(complete);feed.css("width",complete.width())}function preSet(){element.children("option").each(function(i,option){option=$(option);if(option.hasClass("selected")){addItem(option.text(),option.val(),true);option.attr("selected","selected")}else{option.removeAttr("selected")}cache.push({caption:option.text(),value:option.val()});search_string+=""+(cache.length-1)+":"+option.text()+";"})}$(this).bind("addItem",function(event,data){addItem(data.title,data.value)});function addItem(title,value,preadded){var li=document.createElement("li");var txt=document.createTextNode(title);var aclose=document.createElement("a");$(li).attr({"class":"bit-box","rel":value});$(li).prepend(txt);$(aclose).attr({"class":"closebutton","href":"#"});li.appendChild(aclose);var exists = false;$(holder).find("li").each(function(){if($(this).attr("rel")==value){exists = true;}});if(exists)return;holder.append(li);$(aclose).click(function(){$(this).parent("li").fadeOut("fast",function(){removeItem($(this))});return false});if(!preadded){$("#"+elemid+"_annoninput").remove();var _item;addInput(1);if(element.children("option[value="+value+"]").length){_item=element.children("option[value="+value+"]");_item.get(0).setAttribute("selected","selected");if(!_item.hasClass("selected")){_item.addClass("selected")}}else{var _item=$(document.createElement("option"));_item.attr("value",value).get(0).setAttribute("selected","selected");_item.attr("value",value).addClass("selected");_item.text(title);element.append(_item)}if(options.onselect.length){funCall(options.onselect,_item)}}holder.children("li.bit-box.deleted").removeClass("deleted");feed.hide();browser_msie?browser_msie_frame.hide():''}function removeItem(item){if(options.onremove.length){var _item=element.children("option[value="+item.attr("rel")+"]");funCall(options.onremove,_item)}element.children("option[value="+item.attr("rel")+"]").removeAttr("selected");element.children("option[value="+item.attr("rel")+"]").removeClass("selected");item.remove();deleting=0}function addInput(focusme){var li=$(document.createElement("li"));var input=$(document.createElement("input"));li.attr({"class":"bit-input","id":elemid+"_annoninput"});input.attr({"type":"text","class":"maininput","size":"1"});holder.append(li.append(input));input.focus(function(){complete.fadeIn("fast")});input.blur(function(){complete.fadeOut("fast")});holder.click(function(){input.focus();if(feed.length&&input.val().length){feed.show()}else{feed.hide();browser_msie?browser_msie_frame.hide():'';complete.children(".default").show()}});input.keypress(function(event){if(event.keyCode==13){return false}input.attr("size",input.val().length+1)});input.keydown(function(event){if(event.keyCode==191){event.preventDefault();return false}});input.keyup(function(event){var etext=xssPrevent(input.val());if(event.keyCode==8&&etext.length==0){feed.hide();browser_msie?browser_msie_frame.hide():'';if(holder.children("li.bit-box.deleted").length==0){holder.children("li.bit-box:last").addClass("deleted");return false}else{if(deleting){return}deleting=1;holder.children("li.bit-box.deleted").fadeOut("fast",function(){removeItem($(this));return false})}}if(event.keyCode!=40&&event.keyCode!=38&&etext.length!=0){counter=0;if(options.json_url){if(options.cache&&json_cache){addMembers(etext);bindEvents()}else{$.getJSON(options.json_url+"?tag="+etext,null,function(data){addMembers(etext,data);json_cache=true;bindEvents()})}}else{addMembers(etext);bindEvents()}complete.children(".default").hide();feed.show()}});if(focusme){setTimeout(function(){input.focus();complete.children(".default").show()},1)}}function addMembers(etext,data){feed.html('');if(!options.cache){cache=new Array();search_string=""}addTextItem(etext);if(data!=null&&data.length){$.each(data,function(i,val){cache.push({caption:val.caption,value:val.value});search_string+=""+(cache.length-1)+":"+val.caption+";"})}var maximum=options.maxshownitems<cache.length?options.maxshownitems:cache.length;var filter="i";if(options.filter_case){filter=""}var myregexp,match;try{myregexp=eval('/(?:^|;)\\s*(\\d+)\\s*:[^;]*?'+etext+'[^;]*/g'+filter);match=myregexp.exec(search_string)}catch(ex){};var content='';while(match!=null&&maximum>0){var id=match[1];var object=cache[id];if(options.filter_selected&&element.children("option[value="+object.value+"]").hasClass("selected")){}else{content+='<li rel="'+object.value+'">'+itemIllumination(object.caption,etext)+'</li>';counter++;maximum--}match=myregexp.exec(search_string)}feed.append(content);if(options.firstselected){focuson=feed.children("li:visible:first");focuson.addClass("auto-focus")}if(counter>options.height){feed.css({"height":(options.height*24)+"px","overflow":"auto"});if(browser_msie){browser_msie_frame.css({"height":(options.height*24)+"px","width":feed.width()+"px"}).show()}}else{feed.css("height","auto");if(browser_msie){browser_msie_frame.css({"height":feed.height()+"px","width":feed.width()+"px"}).show()}}}function itemIllumination(text,etext){if(options.filter_case){try{eval("var text = text.replace(/(.*)("+etext+")(.*)/gi,'$1<em>$2</em>$3');")}catch(ex){}}else{try{eval("var text = text.replace(/(.*)("+etext.toLowerCase()+")(.*)/gi,'$1<em>$2</em>$3');")}catch(ex){}}return text}function bindFeedEvent(){feed.children("li").mouseover(function(){feed.children("li").removeClass("auto-focus");$(this).addClass("auto-focus");focuson=$(this)});feed.children("li").mouseout(function(){$(this).removeClass("auto-focus");focuson=null})}function removeFeedEvent(){feed.children("li").unbind("mouseover");feed.children("li").unbind("mouseout");feed.mousemove(function(){bindFeedEvent();feed.unbind("mousemove")})}function bindEvents(){var maininput=$("#"+elemid+"_annoninput").children(".maininput");bindFeedEvent();feed.children("li").unbind("mousedown");feed.children("li").mousedown(function(){var option=$(this);addItem(option.text(),option.attr("rel"));feed.hide();browser_msie?browser_msie_frame.hide():'';complete.hide()});maininput.unbind("keydown");maininput.keydown(function(event){if(event.keyCode==191){event.preventDefault();return false}if(event.keyCode!=8){holder.children("li.bit-box.deleted").removeClass("deleted")}if(event.keyCode==13&&checkFocusOn()){var option=focuson;addItem(option.text(),option.attr("rel"));complete.hide();event.preventDefault();focuson=null;return false}if(event.keyCode==13&&!checkFocusOn()){if(options.newel){var value=xssPrevent($(this).val());addItem(value,value);complete.hide();event.preventDefault();focuson=null}return false}if(event.keyCode==40){removeFeedEvent();if(focuson==null||focuson.length==0){focuson=feed.children("li:visible:first");feed.get(0).scrollTop=0}else{focuson.removeClass("auto-focus");focuson=focuson.nextAll("li:visible:first");var prev=parseInt(focuson.prevAll("li:visible").length,10);var next=parseInt(focuson.nextAll("li:visible").length,10);if((prev>Math.round(options.height/2)||next<=Math.round(options.height/2))&&typeof(focuson.get(0))!="undefined"){feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(prev-Math.round(options.height/2))}}feed.children("li").removeClass("auto-focus");focuson.addClass("auto-focus")}if(event.keyCode==38){removeFeedEvent();if(focuson==null||focuson.length==0){focuson=feed.children("li:visible:last");feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(parseInt(feed.children("li:visible").length,10)-Math.round(options.height/2))}else{focuson.removeClass("auto-focus");focuson=focuson.prevAll("li:visible:first");var prev=parseInt(focuson.prevAll("li:visible").length,10);var next=parseInt(focuson.nextAll("li:visible").length,10);if((next>Math.round(options.height/2)||prev<=Math.round(options.height/2))&&typeof(focuson.get(0))!="undefined"){feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(prev-Math.round(options.height/2))}}feed.children("li").removeClass("auto-focus");focuson.addClass("auto-focus")}})}function addTextItem(value){if(options.newel){feed.children("li[fckb=1]").remove();if(value.length==0){return}var li=$(document.createElement("li"));li.attr({"rel":value,"fckb":"1"}).html(value);feed.prepend(li);counter++}else{return}}function funCall(func,item){var _object = "\"_container\": \"" + $(item).parent().get(0).id + "\",";for(i=0;i<item.get(0).attributes.length;i++){if(item.get(0).attributes[i].nodeValue!=null){_object+="\"_"+item.get(0).attributes[i].nodeName+"\": \""+item.get(0).attributes[i].nodeValue+"\","}}_object="{"+_object+" notinuse: 0}";try{eval(func+"("+_object+")")}catch(ex){}}function checkFocusOn(){if(focuson==null){return false}if(focuson.length==0){return false}return true}function xssPrevent(string){string=string.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g,"\"\"");string=string.replace(/script(.*)/g,"");string=string.replace(/eval\((.*)\)/g,"");string=string.replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','');return string}var options=$.extend({json_url:null,cache:false,height:"10",newel:false,firstselected:false,filter_case:false,filter_hide:false,complete_text:"Start to type...",maxshownitems:30,onselect:"",onremove:""},opt);var holder=null;var feed=null;var complete=null;var counter=0;var cache=new Array();var json_cache=false;var search_string="";var focuson=null;var deleting=0;var browser_msie="\v"=="v";var browser_msie_frame;var element=$(this);var elemid=element.attr("id");init();return this})}});
if(typeof(bsn)=="undefined")_b=bsn={};if(typeof(_b.Autosuggest)=="undefined")_b.Autosuggest={};else alert("Autosuggest is already set!");_b.AutoSuggest=function(b,c){if(!document.getElementById)return 0;this.fld=_b.DOM.gE(b);if(!this.fld)return 0;this.sInp="";this.nInpC=0;this.aSug=[];this.iHigh=0;this.oP=c?c:{};var k,def={minchars:1,meth:"get",varname:"input",className:"autosuggest",timeout:2500,delay:500,offsety:-5,shownoresults:true,noresults:"No results!",maxheight:250,cache:true,maxentries:25};for(k in def){if(typeof(this.oP[k])!=typeof(def[k]))this.oP[k]=def[k]}var p=this;this.fld.onkeypress=function(a){return p.onKeyPress(a)};this.fld.onkeyup=function(a){return p.onKeyUp(a)};this.fld.setAttribute("autocomplete","off")};_b.AutoSuggest.prototype.onKeyPress=function(a){var b=(window.event)?window.event.keyCode:a.keyCode;var c=13;var d=9;var e=27;var f=1;switch(b){case c:this.setHighlightedValue();f=0;break;case e:this.clearSuggestions();break}return f};_b.AutoSuggest.prototype.onKeyUp=function(a){var b=(window.event)?window.event.keyCode:a.keyCode;var c=38;var d=40;var e=1;switch(b){case c:this.changeHighlight(b);e=0;break;case d:this.changeHighlight(b);e=0;break;default:this.getSuggestions(this.fld.value)}return e};_b.AutoSuggest.prototype.getSuggestions=function(a){if(a==this.sInp)return 0;_b.DOM.remE(this.idAs);this.sInp=a;if(a.length<this.oP.minchars){this.aSug=[];this.nInpC=a.length;return 0}var b=this.nInpC;this.nInpC=a.length?a.length:0;var l=this.aSug.length;if(this.nInpC>b&&l&&l<this.oP.maxentries&&this.oP.cache){var c=[];for(var i=0;i<l;i++){if(this.aSug[i].value.substr(0,a.length).toLowerCase()==a.toLowerCase())c.push(this.aSug[i])}this.aSug=c;this.createList(this.aSug);return false}else{var d=this;var e=this.sInp;clearTimeout(this.ajID);this.ajID=setTimeout(function(){d.doAjaxRequest(e)},this.oP.delay)}return false};_b.AutoSuggest.prototype.doAjaxRequest=function(b){if(b!=this.fld.value)return false;var c=this;if(typeof(this.oP.script)=="function")var d=this.oP.script(encodeURIComponent(this.sInp));else var d=this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);if(!d)return false;var e=this.oP.meth;var b=this.sInp;var f=function(a){c.setSuggestions(a,b)};var g=function(a){alert("AJAX error: "+a)};var h=new _b.Ajax();h.makeRequest(d,e,f,g)};_b.AutoSuggest.prototype.setSuggestions=function(a,b){if(b!=this.fld.value)return false;this.aSug=[];if(this.oP.json){var c=eval('('+a.responseText+')');for(var i=0;i<c.results.length;i++){this.aSug.push({'id':c.results[i].id,'value':c.results[i].value,'info':c.results[i].info})}}else{var d=a.responseXML;var e=d.getElementsByTagName('results')[0].childNodes;for(var i=0;i<e.length;i++){if(e[i].hasChildNodes())this.aSug.push({'id':e[i].getAttribute('id'),'value':e[i].childNodes[0].nodeValue,'info':e[i].getAttribute('info')})}}this.idAs="as_"+this.fld.id;this.createList(this.aSug)};_b.AutoSuggest.prototype.createList=function(b){var c=this;_b.DOM.remE(this.idAs);this.killTimeout();if(b.length==0&&!this.oP.shownoresults)return false;var d=_b.DOM.cE("div",{id:this.idAs,className:this.oP.className});var e=_b.DOM.cE("div",{className:"as_corner"});var f=_b.DOM.cE("div",{className:"as_bar"});var g=_b.DOM.cE("div",{className:"as_header"});g.appendChild(e);g.appendChild(f);d.appendChild(g);var h=_b.DOM.cE("ul",{id:"as_ul"});for(var i=0;i<b.length;i++){var j=b[i].value;var k=j.toLowerCase().indexOf(this.sInp.toLowerCase());var l=j.substring(0,k)+"<em>"+j.substring(k,k+this.sInp.length)+"</em>"+j.substring(k+this.sInp.length);var m=_b.DOM.cE("span",{},l,true);if(b[i].info!=""){var n=_b.DOM.cE("br",{});m.appendChild(n);var o=_b.DOM.cE("small",{},b[i].info);m.appendChild(o)}var a=_b.DOM.cE("a",{href:"#"});var p=_b.DOM.cE("span",{className:"tl"}," ");var q=_b.DOM.cE("span",{className:"tr"}," ");a.appendChild(p);a.appendChild(q);a.appendChild(m);a.name=i+1;a.onclick=function(){c.setHighlightedValue();return false};a.onmouseover=function(){c.setHighlight(this.name)};var r=_b.DOM.cE("li",{},a);h.appendChild(r)}if(b.length==0&&this.oP.shownoresults){var r=_b.DOM.cE("li",{className:"as_warning"},this.oP.noresults);h.appendChild(r)}d.appendChild(h);var s=_b.DOM.cE("div",{className:"as_corner"});var t=_b.DOM.cE("div",{className:"as_bar"});var u=_b.DOM.cE("div",{className:"as_footer"});u.appendChild(s);u.appendChild(t);d.appendChild(u);var v=_b.DOM.getPos(this.fld);d.style.left=v.x+"px";/*d.style.top=(v.y+this.fld.offsetHeight+this.oP.offsety)+"px";*/d.style.top=(v.y+this.fld.offsetHeight+this.oP.offsety+2)+"px";/*d.style.width=this.fld.offsetWidth+"px";*/d.style.width="380px";d.onmouseover=function(){c.killTimeout()};d.onmouseout=function(){c.resetTimeout()};document.getElementsByTagName("body")[0].appendChild(d);this.iHigh=0;var c=this;this.toID=setTimeout(function(){c.clearSuggestions()},this.oP.timeout)};_b.AutoSuggest.prototype.changeHighlight=function(a){var b=_b.DOM.gE("as_ul");if(!b)return false;var n;if(a==40)n=this.iHigh+1;else if(a==38)n=this.iHigh-1;if(n>b.childNodes.length)n=b.childNodes.length;if(n<1)n=1;this.setHighlight(n)};_b.AutoSuggest.prototype.setHighlight=function(n){var a=_b.DOM.gE("as_ul");if(!a)return false;if(this.iHigh>0)this.clearHighlight();this.iHigh=Number(n);a.childNodes[this.iHigh-1].className="as_highlight";this.killTimeout()};_b.AutoSuggest.prototype.clearHighlight=function(){var a=_b.DOM.gE("as_ul");if(!a)return false;if(this.iHigh>0){a.childNodes[this.iHigh-1].className="";this.iHigh=0}};_b.AutoSuggest.prototype.setHighlightedValue=function(){if(this.iHigh){this.sInp=this.fld.value=this.aSug[this.iHigh-1].value;setSugParams(this.aSug[this.iHigh-1]);this.fld.focus();if(this.fld.selectionStart)this.fld.setSelectionRange(this.sInp.length,this.sInp.length);this.clearSuggestions();if(typeof(this.oP.callback)=="function")this.oP.callback(this.aSug[this.iHigh-1])}};_b.AutoSuggest.prototype.killTimeout=function(){clearTimeout(this.toID)};_b.AutoSuggest.prototype.resetTimeout=function(){clearTimeout(this.toID);var a=this;this.toID=setTimeout(function(){a.clearSuggestions()},1000)};_b.AutoSuggest.prototype.clearSuggestions=function(){this.killTimeout();var a=_b.DOM.gE(this.idAs);var b=this;if(a){var c=new _b.Fader(a,1,0,250,function(){_b.DOM.remE(b.idAs)})}};if(typeof(_b.Ajax)=="undefined")_b.Ajax={};_b.Ajax=function(){this.req={};this.isIE=false};_b.Ajax.prototype.makeRequest=function(a,b,c,d){if(b!="POST")b="GET";this.onComplete=c;this.onError=d;var e=this;if(window.XMLHttpRequest){this.req=new XMLHttpRequest();this.req.onreadystatechange=function(){e.processReqChange()};this.req.open("GET",a,true);this.req.send(null)}else if(window.ActiveXObject){this.req=new ActiveXObject("Microsoft.XMLHTTP");if(this.req){this.req.onreadystatechange=function(){e.processReqChange()};this.req.open(b,a,true);this.req.send()}}};_b.Ajax.prototype.processReqChange=function(){if(this.req.readyState==4){if(this.req.status==200){this.onComplete(this.req)}else{this.onError(this.req.status)}}};if(typeof(_b.DOM)=="undefined")_b.DOM={};_b.DOM.cE=function(b,c,d,e){var f=document.createElement(b);if(!f)return 0;for(var a in c)f[a]=c[a];var t=typeof(d);if(t=="string"&&!e)f.appendChild(document.createTextNode(d));else if(t=="string"&&e)f.innerHTML=d;else if(t=="object")f.appendChild(d);return f};_b.DOM.gE=function(e){var t=typeof(e);if(t=="undefined")return 0;else if(t=="string"){var a=document.getElementById(e);if(!a)return 0;else if(typeof(a.appendChild)!="undefined")return a;else return 0}else if(typeof(e.appendChild)!="undefined")return e;else return 0};_b.DOM.remE=function(a){var e=this.gE(a);if(!e)return 0;else if(e.parentNode.removeChild(e))return true;else return 0};_b.DOM.getPos=function(e){var e=this.gE(e);var a=e;var b=0;if(a.offsetParent){while(a.offsetParent){b+=a.offsetLeft;a=a.offsetParent}}else if(a.x)b+=a.x;var a=e;var c=0;if(a.offsetParent){while(a.offsetParent){c+=a.offsetTop;a=a.offsetParent}}else if(a.y)c+=a.y;return{x:b,y:c}};if(typeof(_b.Fader)=="undefined")_b.Fader={};_b.Fader=function(a,b,c,d,e){if(!a)return 0;this.e=a;this.from=b;this.to=c;this.cb=e;this.nDur=d;this.nInt=50;this.nTime=0;var p=this;this.nID=setInterval(function(){p._fade()},this.nInt)};_b.Fader.prototype._fade=function(){this.nTime+=this.nInt;var a=Math.round(this._tween(this.nTime,this.from,this.to,this.nDur)*100);var b=a/100;if(this.e.filters){try{this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity=a}catch(e){this.e.style.filter='progid:DXImageTransform.Microsoft.Alpha(opacity='+a+')'}}else{this.e.style.opacity=b}if(this.nTime==this.nDur){clearInterval(this.nID);if(this.cb!=undefined)this.cb()}};_b.Fader.prototype._tween=function(t,b,c,d){return b+((c-b)*(t/d))};
/* A Bar is a simple overlay that outlines a lat/lng bounds on the
 * map. It has a border of the given weight and color and can optionally
 * have a semi-transparent background color.
 * @param latlng {GLatLng} Point to place bar at.
 * @param opts {Object Literal} Passes configuration options - 
 *   weight, color, height, width, text, and offset.
 */
function MarkerLight(latlng, opts) {
  this.latlng = latlng;

  if (!opts) opts = {};

  this.height_ = opts.height || 34;
  this.width_ = opts.width || 20;
  this.image_ = opts.image;
  this.imageOver_ = opts.imageOver;
  this.clicked_ = 0;
  this.infowindowopen_ = 0;
}

/* MarkerLight extends GOverlay class from the Google Maps API
 */
MarkerLight.prototype = new GOverlay();

/* Creates the DIV representing this MarkerLight.
 * @param map {GMap2} Map that bar overlay is added to.
 */
MarkerLight.prototype.initialize = function(map) {
  var me = this;

  // Create the DIV representing our MarkerLight
  var div = document.createElement("div");
  //div.style.border = "1px solid white";
  div.style.border = "0px";
  div.style.position = "absolute";
  div.style.paddingLeft = "0px";
  div.style.cursor = 'pointer';

  var img = document.createElement("img");
  img.src = me.image_;
  img.style.width = me.width_ + "px";
  img.style.height = me.height_ + "px";
  div.appendChild(img);  

  GEvent.addDomListener(div, "click", function(event) {
    me.clicked_ = 1;
    GEvent.trigger(me, "click");
  });

  GEvent.addDomListener(map, "infowindowopen", function(event) {
    me.infowindowopen_ = 1;
    GEvent.trigger(me, "infowindowopen");
  });

  map.getPane(G_MAP_MARKER_PANE).appendChild(div);

  this.map_ = map;
  this.div_ = div;
};

/* Remove the main DIV from the map pane
 */
MarkerLight.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
};

/* Copy our data to a new MarkerLight
 * @return {MarkerLight} Copy of bar
 */
MarkerLight.prototype.copy = function() {
  var opts = {};
  opts.color = this.color_;
  opts.height = this.height_;
  opts.width = this.width_;
  opts.image = this.image_;
  opts.imageOver = this.image_;
  return new MarkerLight(this.latlng, opts);
};

/* Redraw the MarkerLight based on the current projection and zoom level
 * @param force {boolean} Helps decide whether to redraw overlay
 */
MarkerLight.prototype.redraw = function(force) {

  // We only need to redraw if the coordinate system has changed
  if (!force) return;

  // Calculate the DIV coordinates of two opposite corners 
  // of our bounds to get the size and position of our MarkerLight
  var divPixel = this.map_.fromLatLngToDivPixel(this.latlng);

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = this.width_ + "px";
  //this.div_.style.left = (divPixel.x) + "px"
  this.div_.style.left = (divPixel.x-10) + "px"
  this.div_.style.height = (this.height_) + "px";
  this.div_.style.top = (divPixel.y+20) - this.height_ + "px";
};

MarkerLight.prototype.getZIndex = function(m) {
  return GOverlay.getZIndex(marker.getPoint().lat())-m.clicked*10000;
}

MarkerLight.prototype.getPoint = function() {
  return this.latlng;
};

MarkerLight.prototype.setStyle = function(style) {
  for (s in style) {
    this.div_.style[s] = style[s];
  }
};

MarkerLight.prototype.setImage = function(image) {
  this.div_.getElementsByTagName("img")[0].src = image;
};


/**
 * AJAX Upload ( http://valums.com/ajax-upload/ ) 
 * Copyright (c) Andris Valums
 * Licensed under the MIT license ( http://valums.com/mit-license/ )
 * Thanks to Gary Haran, David Mark, Corey Burns and others for contributions 
 */
(function () {
    /* global window */
    /* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true */
    
    /**
     * Wrapper for FireBug's console.log
     */
    function log(){
        if (typeof(console) != 'undefined' && typeof(console.log) == 'function'){            
            Array.prototype.unshift.call(arguments, '[Ajax Upload]');
            console.log( Array.prototype.join.call(arguments, ' '));
        }
    } 

    /**
     * Attaches event to a dom element.
     * @param {Element} el
     * @param type event name
     * @param fn callback This refers to the passed element
     */
    function addEvent(el, type, fn){
        if (el.addEventListener) {
            el.addEventListener(type, fn, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + type, function(){
                fn.call(el);
	        });
	    } else {
            throw new Error('not supported or DOM not loaded');
        }
    }   
    
    /**
     * Attaches resize event to a window, limiting
     * number of event fired. Fires only when encounteres
     * delay of 100 after series of events.
     * 
     * Some browsers fire event multiple times when resizing
     * http://www.quirksmode.org/dom/events/resize.html
     * 
     * @param fn callback This refers to the passed element
     */
    function addResizeEvent(fn){
        var timeout;
               
	    addEvent(window, 'resize', function(){
            if (timeout){
                clearTimeout(timeout);
            }
            timeout = setTimeout(fn, 100);                        
        });
    }    
    
    // Needs more testing, will be rewriten for next version        
    // getOffset function copied from jQuery lib (http://jquery.com/)
    if (document.documentElement.getBoundingClientRect){
        // Get Offset using getBoundingClientRect
        // http://ejohn.org/blog/getboundingclientrect-is-awesome/
        var getOffset = function(el){
            var box = el.getBoundingClientRect();
            var doc = el.ownerDocument;
            var body = doc.body;
            var docElem = doc.documentElement; // for ie 
            var clientTop = docElem.clientTop || body.clientTop || 0;
            var clientLeft = docElem.clientLeft || body.clientLeft || 0;
             
            // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
            // while others are logical. Make all logical, like in IE8.	
            var zoom = 1;            
            if (body.getBoundingClientRect) {
                var bound = body.getBoundingClientRect();
                zoom = (bound.right - bound.left) / body.clientWidth;
            }
            
            if (zoom > 1) {
                clientTop = 0;
                clientLeft = 0;
            }
            
            var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;
            
            return {
                top: top,
                left: left
            };
        };        
    } else {
        // Get offset adding all offsets 
        var getOffset = function(el){
            var top = 0, left = 0;
            do {
                top += el.offsetTop || 0;
                left += el.offsetLeft || 0;
                el = el.offsetParent;
            } while (el);
            
            return {
                left: left,
                top: top
            };
        };
    }
    
    /**
     * Returns left, top, right and bottom properties describing the border-box,
     * in pixels, with the top-left relative to the body
     * @param {Element} el
     * @return {Object} Contains left, top, right,bottom
     */
    function getBox(el){
        var left, right, top, bottom;
        var offset = getOffset(el);
        left = offset.left;
        top = offset.top;
        
        right = left + el.offsetWidth;
        bottom = top + el.offsetHeight;
        
        return {
            left: left,
            right: right,
            top: top,
            bottom: bottom
        };
    }
    
    /**
     * Helper that takes object literal
     * and add all properties to element.style
     * @param {Element} el
     * @param {Object} styles
     */
    function addStyles(el, styles){
        for (var name in styles) {
            if (styles.hasOwnProperty(name)) {
                el.style[name] = styles[name];
            }
        }
    }
        
    /**
     * Function places an absolutely positioned
     * element on top of the specified element
     * copying position and dimentions.
     * @param {Element} from
     * @param {Element} to
     */    
    function copyLayout(from, to){
	    var box = getBox(from);
        
        addStyles(to, {
	        position: 'absolute',                    
	        left : box.left + 'px',
	        top : box.top + 'px',
	        width : from.offsetWidth + 'px',
	        height : from.offsetHeight + 'px'
	    });        
    }

    /**
    * Creates and returns element from html chunk
    * Uses innerHTML to create an element
    */
    var toElement = (function(){
        var div = document.createElement('div');
        return function(html){
            div.innerHTML = html;
            var el = div.firstChild;
            return div.removeChild(el);
        };
    })();
            
    /**
     * Function generates unique id
     * @return unique id 
     */
    var getUID = (function(){
        var id = 0;
        return function(){
            return 'ValumsAjaxUpload' + id++;
        };
    })();        
 
    /**
     * Get file name from path
     * @param {String} file path to file
     * @return filename
     */  
    function fileFromPath(file){
        return file.replace(/.*(\/|\\)/, "");
    }
    
    /**
     * Get file extension lowercase
     * @param {String} file name
     * @return file extenstion
     */    
    function getExt(file){
        return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
    }

    function hasClass(el, name){        
        var re = new RegExp('\\b' + name + '\\b');        
        return re.test(el.className);
    }    
    function addClass(el, name){
        if ( ! hasClass(el, name)){   
            el.className += ' ' + name;
        }
    }    
    function removeClass(el, name){
        var re = new RegExp('\\b' + name + '\\b');                
        el.className = el.className.replace(re, '');        
    }
    
    function removeNode(el){
        el.parentNode.removeChild(el);
    }

    /**
     * Easy styling and uploading
     * @constructor
     * @param button An element you want convert to 
     * upload button. Tested dimentions up to 500x500px
     * @param {Object} options See defaults below.
     */
    window.AjaxUpload = function(button, options){
        this._settings = {
            // Location of the server-side upload script
            action: 'upload.php',
            // File upload name
            name: 'userfile',
            // Additional data to send
            data: {},
            // Submit file as soon as it's selected
            autoSubmit: true,
            // The type of data that you're expecting back from the server.
            // html and xml are detected automatically.
            // Only useful when you are using json data as a response.
            // Set to "json" in that case. 
            responseType: false,
            // Class applied to button when mouse is hovered
            hoverClass: 'hover',
            // Class applied to button when AU is disabled
            disabledClass: 'disabled',            
            // When user selects a file, useful with autoSubmit disabled
            // You can return false to cancel upload			
            onChange: function(file, extension){
            },
            // Callback to fire before file is uploaded
            // You can return false to cancel upload
            onSubmit: function(file, extension){
            },
            // Fired when file upload is completed
            // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
            onComplete: function(file, response){
            }
        };
                        
        // Merge the users options with our defaults
        for (var i in options) {
            if (options.hasOwnProperty(i)){
                this._settings[i] = options[i];
            }
        }
                
        // button isn't necessary a dom element
        if (button.jquery){
            // jQuery object was passed
            button = button[0];
        } else if (typeof button == "string") {
            if (/^#.*/.test(button)){
                // If jQuery user passes #elementId don't break it					
                button = button.slice(1);                
            }
            
            button = document.getElementById(button);
        }
        
        if ( ! button || button.nodeType !== 1){
            throw new Error("Please make sure that you're passing a valid element"); 
        }
                
        if ( button.nodeName.toUpperCase() == 'A'){
            // disable link                       
            addEvent(button, 'click', function(e){
                if (e && e.preventDefault){
                    e.preventDefault();
                } else if (window.event){
                    window.event.returnValue = false;
                }
            });
        }
                    
        // DOM element
        this._button = button;        
        // DOM element                 
        this._input = null;
        // If disabled clicking on button won't do anything
        this._disabled = false;
        
        // if the button was disabled before refresh if will remain
        // disabled in FireFox, let's fix it
        this.enable();        
        
        this._rerouteClicks();
    };
    
    // assigning methods to our class
    AjaxUpload.prototype = {
        setData: function(data){
            this._settings.data = data;
        },
        disable: function(){            
            addClass(this._button, this._settings.disabledClass);
            this._disabled = true;
            
            var nodeName = this._button.nodeName.toUpperCase();            
            if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
                this._button.setAttribute('disabled', 'disabled');
            }            
            
            // hide input
            if (this._input){
                // We use visibility instead of display to fix problem with Safari 4
                // The problem is that the value of input doesn't change if it 
                // has display none when user selects a file           
                this._input.parentNode.style.visibility = 'hidden';
            }
        },
        enable: function(){
            removeClass(this._button, this._settings.disabledClass);
            this._button.removeAttribute('disabled');
            this._disabled = false;
            
        },
        /**
         * Creates invisible file input 
         * that will hover above the button
         * <div><input type='file' /></div>
         */
        _createInput: function(){ 
            var self = this;
                        
            var input = document.createElement("input");
            input.setAttribute('type', 'file');
            input.setAttribute('name', this._settings.name);
            
            addStyles(input, {
                'position' : 'absolute',
                // in Opera only 'browse' button
                // is clickable and it is located at
                // the right side of the input
                'right' : 0,
                'margin' : 0,
                'padding' : 0,
                'fontSize' : '480px',                
                'cursor' : 'pointer'
            });            

            var div = document.createElement("div");                        
            addStyles(div, {
                'display' : 'block',
                'position' : 'absolute',
                'overflow' : 'hidden',
                'margin' : 0,
                'padding' : 0,                
                'opacity' : 0,
                // Make sure browse button is in the right side
                // in Internet Explorer
                'direction' : 'ltr',
                //Max zIndex supported by Opera 9.0-9.2
                'zIndex': 2147483583
            });
            
            // Make sure that element opacity exists.
            // Otherwise use IE filter            
            if ( div.style.opacity !== "0") {
                if (typeof(div.filters) == 'undefined'){
                    throw new Error('Opacity not supported by the browser');
                }
                div.style.filter = "alpha(opacity=0)";
            }            
            
            addEvent(input, 'change', function(){
                 
                if ( ! input || input.value === ''){                
                    return;                
                }
                            
                // Get filename from input, required                
                // as some browsers have path instead of it          
                var file = fileFromPath(input.value);
                                
                if (false === self._settings.onChange.call(self, file, getExt(file))){
                    self._clearInput();                
                    return;
                }
                
                // Submit form when value is changed
                if (self._settings.autoSubmit) {
                    self.submit();
                }
            });            

            addEvent(input, 'mouseover', function(){
                addClass(self._button, self._settings.hoverClass);
            });
            
            addEvent(input, 'mouseout', function(){
                removeClass(self._button, self._settings.hoverClass);
                
                // We use visibility instead of display to fix problem with Safari 4
                // The problem is that the value of input doesn't change if it 
                // has display none when user selects a file           
                input.parentNode.style.visibility = 'hidden';

            });   
                        
	        div.appendChild(input);
            document.body.appendChild(div);
              
            this._input = input;
        },
        _clearInput : function(){
            if (!this._input){
                return;
            }            
                             
            // this._input.value = ''; Doesn't work in IE6                               
            removeNode(this._input.parentNode);
            this._input = null;                                                                   
            this._createInput();
            
            removeClass(this._button, this._settings.hoverClass);
        },
        /**
         * Function makes sure that when user clicks upload button,
         * the this._input is clicked instead
         */
        _rerouteClicks: function(){
            var self = this;
            
            // IE will later display 'access denied' error
            // if you use using self._input.click()
            // other browsers just ignore click()

            addEvent(self._button, 'mouseover', function(){
                if (self._disabled){
                    return;
                }
                                
                if ( ! self._input){
	                self._createInput();
                }
                
                var div = self._input.parentNode;                            
                copyLayout(self._button, div);
                div.style.visibility = 'visible';
                                
            });
            
            
            // commented because we now hide input on mouseleave
            /**
             * When the window is resized the elements 
             * can be misaligned if button position depends
             * on window size
             */
            //addResizeEvent(function(){
            //    if (self._input){
            //        copyLayout(self._button, self._input.parentNode);
            //    }
            //});            
                                         
        },
        /**
         * Creates iframe with unique name
         * @return {Element} iframe
         */
        _createIframe: function(){
            // We can't use getTime, because it sometimes return
            // same value in safari :(
            var id = getUID();            
             
            // We can't use following code as the name attribute
            // won't be properly registered in IE6, and new window
            // on form submit will open
            // var iframe = document.createElement('iframe');
            // iframe.setAttribute('name', id);                        
 
            var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
            // src="javascript:false; was added
            // because it possibly removes ie6 prompt 
            // "This page contains both secure and nonsecure items"
            // Anyway, it doesn't do any harm.            
            iframe.setAttribute('id', id);
            
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            
            return iframe;
        },
        /**
         * Creates form, that will be submitted to iframe
         * @param {Element} iframe Where to submit
         * @return {Element} form
         */
        _createForm: function(iframe){
            var settings = this._settings;
                        
            // We can't use the following code in IE6
            // var form = document.createElement('form');
            // form.setAttribute('method', 'post');
            // form.setAttribute('enctype', 'multipart/form-data');
            // Because in this case file won't be attached to request                    
            var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
                        
            form.setAttribute('action', settings.action);
            form.setAttribute('target', iframe.name);                                   
            form.style.display = 'none';
            document.body.appendChild(form);
            
            // Create hidden input element for each data key
            for (var prop in settings.data) {
                if (settings.data.hasOwnProperty(prop)){
                    var el = document.createElement("input");
                    el.setAttribute('type', 'hidden');
                    el.setAttribute('name', prop);
                    el.setAttribute('value', settings.data[prop]);
                    form.appendChild(el);
                }
            }
            return form;
        },
        /**
         * Gets response from iframe and fires onComplete event when ready
         * @param iframe
         * @param file Filename to use in onComplete callback 
         */
        _getResponse : function(iframe, file){            
            // getting response
            var toDeleteFlag = false, self = this, settings = this._settings;   
               
            addEvent(iframe, 'load', function(){                
                
                if (// For Safari 
                    iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
                    // For FF, IE
                    iframe.src == "javascript:'<html></html>';"){                                                                        
                        // First time around, do not delete.
                        // We reload to blank page, so that reloading main page
                        // does not re-submit the post.
                        
                        if (toDeleteFlag) {
                            // Fix busy state in FF3
                            setTimeout(function(){
                                removeNode(iframe);
                            }, 0);
                        }
                                                
                        return;
                }
                
                var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
                
                // fixing Opera 9.26,10.00
                if (doc.readyState && doc.readyState != 'complete') {
                   // Opera fires load event multiple times
                   // Even when the DOM is not ready yet
                   // this fix should not affect other browsers
                   return;
                }
                
                // fixing Opera 9.64
                if (doc.body && doc.body.innerHTML == "false") {
                    // In Opera 9.64 event was fired second time
                    // when body.innerHTML changed from false 
                    // to server response approx. after 1 sec
                    return;
                }
                
                var response;
                
                if (doc.XMLDocument) {
                    // response is a xml document Internet Explorer property
                    response = doc.XMLDocument;
                } else if (doc.body){
                    // response is html document or plain text
                    response = doc.body.innerHTML;
                    
                    if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
                        // If the document was sent as 'application/javascript' or
                        // 'text/javascript', then the browser wraps the text in a <pre>
                        // tag and performs html encoding on the contents.  In this case,
                        // we need to pull the original text content from the text node's
                        // nodeValue property to retrieve the unmangled content.
                        // Note that IE6 only understands text/html
                        if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
                            response = doc.body.firstChild.firstChild.nodeValue;
                        }
                        
                        if (response) {
                            response = eval("(" + response + ")");
                        } else {
                            response = {};
                        }
                    }
                } else {
                    // response is a xml document
                    response = doc;
                }
                
                settings.onComplete.call(self, file, response);
                
                // Reload blank page, so that reloading main page
                // does not re-submit the post. Also, remember to
                // delete the frame
                toDeleteFlag = true;
                
                // Fix IE mixed content issue
                iframe.src = "javascript:'<html></html>';";
            });            
        },        
        /**
         * Upload file contained in this._input
         */
        submit: function(){                        
            var self = this, settings = this._settings;
            
            if ( ! this._input || this._input.value === ''){                
                return;                
            }
                                    
            var file = fileFromPath(this._input.value);
            
            // user returned false to cancel upload
            if (false === settings.onSubmit.call(this, file, getExt(file))){
                this._clearInput();                
                return;
            }
            
            // sending request    
            var iframe = this._createIframe();
            var form = this._createForm(iframe);
            
            // assuming following structure
            // div -> input type='file'
            removeNode(this._input.parentNode);            
            removeClass(self._button, self._settings.hoverClass);
                        
            form.appendChild(this._input);
                        
            form.submit();

            // request set, clean up                
            removeNode(form); form = null;                          
            removeNode(this._input); this._input = null;
            
            // Get response from iframe and fire onComplete event when ready
            this._getResponse(iframe, file);            

            // get ready for next request            
            this._createInput();
        }
    };
})(); 

/**
* Cornerz 0.6 - Bullet Proof Corners
* Jonah Fox (jonah@parkerfox.co.uk) 2008
* 
* Usage: $('.myclass').curve(options)
* options is a hash with the following parameters. Bracketed is the default
*   radius (10)
*   borderWidth (read from BorderTopWidth or 0)
*   background ("white"). Note that this is not calculated from the HTML as it is expensive
*   borderColor (read from BorderTopColor)
*   corners ("tl br tr bl"). Specify which borders
*   fixIE ("padding") - attmepts to fix IE by incrementing the property by 1 if the outer width/height is odd.

CHANGELIST from  v0.4

0.5 - Now attempts to fix the odd dimension problem in IE 
0.6 - Added semicolons for packing and fixed a problem with odd border width's in IE

*/
    
;(function($){

  if($.browser.msie && document.namespaces["v"] == null) {
    document.namespaces.add("v", "urn:schemas-microsoft-com:vml", "#default#VML");
  }

  $.fn.cornerz = function(options){
    
    function canvasCorner(t,l, r,bw,bc,bg){
	    var sa,ea,cw,sx,sy,x,y, p = 1.57, css="position:absolute;";
	    if(t) 
		    {sa=-p; sy=r; y=0; css+="top:-"+bw+"px;";  }
	    else 
		    {sa=p; sy=0; y=r; css+="bottom:-"+bw+"px;"; }
	    if(l) 
		    {ea=p*2; sx=r; x=0;	css+="left:-"+bw+"px;";}
	    else 
		    {ea=0; sx=0; x=r; css+="right:-"+bw+"px;";	}
		
	    var canvas=$("<canvas width="+r+"px height="+ r +"px style='" + css+"' ></canvas>");
	    var ctx=canvas[0].getContext('2d');
	    ctx.beginPath();
	    ctx.lineWidth=bw*2;	
	    ctx.arc(sx,sy,r,sa,ea,!(t^l));
	    ctx.strokeStyle=bc;
	    ctx.stroke();
	    ctx.lineWidth = 0;
	    ctx.lineTo(x,y);
	    ctx.fillStyle=bg;
	    ctx.fill();
	    return canvas;
    };

    function canvasCorners(corners, r, bw,bc,bg) {
	    var hh = $("<div style='display: inherit' />"); // trying out style='float:left' 
	    $.each(corners.split(" "), function() {
	      hh.append(canvasCorner(this[0]=="t",this[1]=="l", r,bw,bc,bg));
	    });
	    return hh;
    };

    function vmlCurve(r,b,c,m,ml,mt, right_fix) {
        var l = m-ml-right_fix;
        var t = m-mt;
        return "<v:arc filled='False' strokeweight='"+b+"px' strokecolor='"+c+"' startangle='0' endangle='361' style=' top:" + t +"px;left: "+ l + "px;width:" + r+ "px; height:" + r+ "px' />";
    }
    

    function vmlCorners(corners, r, bw, bc, bg, w) {
      var h ="<div style='text-align:left; '>";
      $.each($.trim(corners).split(" "), function() {
        var css,ml=1,mt=1,right_fix=0;
        if(this.charAt(0)=="t") {
          css="top:-"+bw+"px;";
        }
        else {
          css= "bottom:-"+bw+"px;";
          mt=r+1;
        }
        if(this.charAt(1)=="l")
          css+="left:-"+bw+"px;";
        else {
          css +="right:-"+(bw)+"px; "; // odd width gives wrong margin?
           ml=r;
           right_fix = 1;
        }

        h+="<div style='"+css+"; position: absolute; overflow:hidden; width:"+ r +"px; height: " + r + "px;'>";
        h+= "<v:group  style='width:1000px;height:1000px;position:absolute;' coordsize='1000,1000' >";
        h+= vmlCurve(r*3,r+bw,bg, -r/2,ml,mt,right_fix); 
        if(bw>0)
          h+= vmlCurve(r*2-bw,bw,bc, Math.floor(bw/2+0.5),ml,mt,right_fix);
        h+="</v:group>";
        h+= "</div>"; 
      });
      h += "</div>";
      
      return h;
    };

    var settings = {
      corners : "tl tr bl br",
      radius : 10,
      background: "white",
      borderWidth: 0,
      fixIE: true };              
    $.extend(settings, options || {});
    
    var incrementProperty = function(elem, prop, x) {
      var y = parseInt(elem.css(prop), 10) || 0 ;
      elem.css(prop, x+y);
    };
    
    
    return this.each(function() {
      
      var $$ = $(this);
      var r = settings.radius*1.0;
      var bw = (settings.borderWidth || parseInt($$.css("borderTopWidth"), 10) || 0)*1.0;
      var bg = settings.background;
      var bc = settings.borderColor;
      bc = bc || ( bw > 0 ? $$.css("borderTopColor") : bg);
            
      var cs = settings.corners;

      if($.browser.msie) {//need to use innerHTML rather than jQuery
        h = vmlCorners(cs,r,bw,bc,bg, $(this).width() );     
        this.insertAdjacentHTML('beforeEnd', h);
        
      }
      else  //canvasCorners returns a DOM element
        $$.append(canvasCorners(cs,r,bw,bc,bg));
      
      
      if(this.style.position != "absolute")
        this.style.position = "relative";
     
       this.style.zoom = 1; // give it a layout in IE
      
       if($.browser.msie && settings.fixIE) {
          var ow = $$.outerWidth();
          var oh = $$.outerHeight();
          
          if(ow%2 == 1) {
            incrementProperty($$, "padding-right", 1);
            incrementProperty($$, "margin-right", 1);
          }

          if(oh%2 == 1) { 
            incrementProperty($$, "padding-bottom", 1);
            incrementProperty($$, "margin-bottom", 1);
          }
        }
          
      }
      
    );
 
  };
})(jQuery);

  var fullpath, default_region_title, pre_operation, pre_id, user_location_data, gdir, directions_overlay, headerData, map_center;
  var defalut_snewsletter_value = "Your E-Mail Address Here", defalut_location_value = "Address or Zip Code",
      default_center = new GLatLng(44.231329, -76.480925);
  var page_content_array = new Array(), markers_array = new Array();
  var set_address, initial_data, MapBounds, geocoder, map_zoom_level, current_marker_obj, map_options_regions = false, show_direction = false, 
      totalLocations = 0, p_current = 1, p_size = 5, details_mode = false, is_authorized = false, do_search_state = false, 
      operation = "get_region";
  var uui = randomUUID();
  var cc_settings = {tl: { radius: 6 },tr: { radius: 6 },bl: { radius: 6 },br: { radius: 6 },antiAlias: true}

  function setSugParams(sdata){
    if(sdata.info=="tag"){
      $("#search_type").val(sdata.info);
      $("#search_id").val(sdata.id);
    } else {
      $("#search_type").val("listing");
      $("#search_id").val(sdata.id);
    }
    doSearch();
  }

  function doSearch(){
    if(do_search_state){
      return;
    }
    $("#user_panel").hide();
    do_search_state = true;
    if($("#search_type").val()=="tag"){
      //console.log("/"+default_region_title+"/"+$("#search_id").val()+"/"+mfile);
      if(mfile=="map.html"){
        document.location = "/"+default_region_title+"/"+$("#search_id").val()+"/"+mfile;
      } else {
        document.location = "/"+default_region_title+"/"+$("#search_id").val()+"/";
      }
    } else if($("#search_type").val()=="listing"){
      document.location = $("#search_id").val()+".html";
    } else {
      var search_text = $("#search_text").val();
      if(search_text.length==0 || search_text.length>250){
        alert("You must fill a search field!");
        $("#search_text").focus();
        return;
      }
      var url = "data.php?operation=search&search_text="+search_text;
      switchCD("loading");
      $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        success: searchOutput
      });
    }
  }

  function showDirectionDetails(point){
    map.showMapBlowup(point);
  }

  function searchOutput(xd){
    map.clearOverlays();
    backToDirectory();
    $("#location").removeAttr("disabled");
    $("#distance_box").removeAttr("disabled");
    locations_array = new Array();
    totalLocations = $("location",xd).length;
    var search_for = "&#160;";
    if($("#search_text").val()!=""){
      search_for = "Search for '"+$("#search_text").val()+"'";
    }
    $("#results_list_header").html("<div class='sectionHeader'><h1>Search</h1><h5>"+search_for+"</h5></div>");
    var MapBounds = new GLatLngBounds();
    markers_array = new Array();
    locations_array = new Array()
    var marker_count = 0;
    p_current = 1;
    $("location",xd).each(function(){
      var location = new locationClassXML($(this));
      locations_array.push(location);
      if(location.lat && location.lng){
        var point = new GLatLng(location.lat,location.lng);
        var marker = new createLocationMarker(point, location);
        markers_array.push(marker);
        map.addOverlay(marker,0,17);
        MapBounds.extend(point);
      }
      marker_count++
    });
    if(totalLocations==0){
      //$("#results_list_data").html("There is no data<br>");
      $("#results_list_page_nav_top").html("");
      $("#results_list_page_nav").html("");
    } else {
      map.setZoom(map.getBoundsZoomLevel(MapBounds));
      var clat = (MapBounds.getNorthEast().lat() + MapBounds.getSouthWest().lat()) /2;
      var clng = (MapBounds.getNorthEast().lng() + MapBounds.getSouthWest().lng()) /2;
      map.setCenter(new GLatLng(clat,clng));
      makePage(p_current);
    }
    getNavLinks(true);
    do_search_state = false;
    if($("#search_type").val()=="listing"){
      getLocation($("#search_id").val());
      $("#search_type").val("");
    }
    switchCD("main_column");
  }

  var pngfixed = false;

  function common_init(){
    //checkLogged();
    $("div.content_left_column").each(function(){
      page_content_array.push($(this).attr("id"));
    });
    var options_xml = {
      script: function (input) { return "data.php?operation=search_sug&search_text="+input; },
      timeout:5000,
      varname:"input"
    };
    var as_xml = new bsn.AutoSuggest('search_text', options_xml);
    $("#search_text").keypress(function (e) {  
      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
        doSearch();
      }  
    });
    $("#nl_search").keypress(function (e) {  
      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
        nl_start=1;
        nl_page=1;
        findNewListing();
      }  
    });
    $("#snewsletter").val(defalut_snewsletter_value);
    $("#snewsletter").focus(function() {
      if( this.value == defalut_snewsletter_value ) {
        this.value = "";
      }
    }).blur(function() {
      if( !this.value.length ) {
        this.value = defalut_snewsletter_value;
      }
    });
    $("div#login_form").dialog(
      {autoOpen:false,bgiframe:true,width:480,height:300,modal:true,resizable:false,title:"Sign in / Sign up"}
    );
    /*
    var badBrowser = (/MSIE ((5\.5)|6|7)/.test(navigator.userAgent) && navigator.platform == "Win32");
    if (badBrowser && !pngfixed) {
      DD_belatedPNG.fix('.pngimage,.top_line_link,.content_top_link,#region_box_l,#distance_box_l,.selectbox,.selectbox_grey,#user_panel');
      pngfixed = true;
    } 
    */
  }

  function loadXMLString(txt){
    try //Internet Explorer
      {
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async="false";
      xmlDoc.loadXML(txt);
      return xmlDoc;
      }
    catch(e)
      {
      try //Firefox, Mozilla, Opera, etc.
        {
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(txt,"text/xml");
        return xmlDoc;
        }
      catch(e) {alert(e.message)}
      }
    return null;
  }

  function doSubscribe(){
    var email = $("#snewsletter").val();
    if(!isValidEmailAddress(email)){
      alert("Please, enter a valid email address!");
      return;
    }
    $.ajax({
      type: "GET",
      url: "data.php?operation=subscribe&email="+email,
      dataType: "xml",
      success: doSubscribeOutput
    });
  }

  function doSubscribeOutput(xd){
    switch($("response",xd).attr("code")){
      case "already_exists":
        alert("Email aready exists in out database!");
      break;
      case "added":
        alert("Email successfully registered!");
        $("#snewsletter").val(defalut_snewsletter_value);
      break;
    }
  }

  function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
  }

  function initFB() {
    FB_RequireFeatures(["XFBML"], function(){
      FB.init("98eaff8c0b1bc3561e3938186003d7ea", "/fb/xd_receiver.htm");
    });
  }

  function fbConnect() {
    FB.init("", "/fb/xd_receiver.htm",{"reloadIfSessionStateChanged":true});
  }

  function checkLogged(){
    var url = "/data.php?operation=check_login";
    $.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: checkLoggedOutput
    });
  }

  function openLoginForm(){
    $("#login_form_pr").hide();
    $("#login_form_pr_result").hide();
    $("#login_form_main").show();
    $("div#login_form").dialog("open");
  }

  function openPasswordReminder(){
    $("#login_form_main").hide();
    $("#login_form_pr_result").hide();
    $("#login_form_pr").show();
  }

  function doPasswordReminder(){
    if($("#pr_email").val()==""){
      alert("Email address is required!");
      $("#pr_email").focus();
      return;
    }
    $("#pr_button").attr("disabled","disabled").val("Processing...");
    var url = "data.php?operation=remind_password";
    var data = "&email="+$("#pr_email").val();
    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: "xml",
      success: doPasswordReminderOutput
    });
  }

  function doPasswordReminderOutput(xd){
    $("#user_panel").hide();
    $("#pr_button").removeAttr("disabled").val("Remind me");
    var content = "User with such email is not registered!";
    switch($("response",xd).attr("code")){
      case "password_sent":
        var content = "A new password was sent to your email address.";
      break;
    }
    $("#login_form_pr_result").html(content).show();
  } 

  function checkLoggedOutput(xd){
    var content = "<a href='javascript:void(0)' onclick='openLoginForm()'>Sign in or Join</a>";
    is_authorized = false;
    if($("response",xd).attr("login")=="true"){
      var logout_link = "logoutFB();";
      if($("response",xd).attr("fb_user")=="false"){
        logout_link = "logout();";
      }
      var account_link = "<a href='/account.html'>Account</a>";
      var unread_messages = parseInt($("response",xd).attr("unread_messages"));
      if(unread_messages>0){
        account_link = "<b><a href='/account.html'>Account</a> ("+unread_messages+")</b>";
      }
      content = account_link+" &#160;&#160; <a href='javascript:void(0)' onclick='"+logout_link+"'>Logout</a>";
      is_authorized = true;
    }
    $("#user_panel div.c div").html(content);
    $("#user_panel").show();
  }

  function logoutFB(){
    FB.Connect.logoutAndRedirect('http://dogfriendlykingston.com/kingston/dogfriendly/?operation=logout');
  }

  function logout(){
    window.location = 'http://dogfriendlykingston.com/kingston/dogfriendly/?operation=logout';
  }

  function doFBLogin(){
    checkLogged();
    $("div#login_form").dialog("close");
  }

  function doLogin(){
    if($("#l_email").val()==""){
      alert("Email address is required!");
      $("#l_email").focus();
      return;
    }
    if($("#l_password").val()==""){
      alert("Password is required!");
      $("#l_password").focus();
      return;
    }
    $("#login_button").attr("disabled","disabled").val("Processing...");
    var url = "data.php?operation=do_login";
    var data = "&email="+$("#l_email").val()+"&password="+$("#l_password").val();
    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: "xml",
      success: doLoginOutput
    });
  }

  function doLoginOutput(xd){
    $("#login_button").removeAttr("disabled").val("Sign in");
    switch($("response",xd).attr("code")){
      case "ok":
        doFBLogin();
      break;
      default:
        alert("Incorrect Email/Password Combination!");
      break;
    }
  } 

  function doRegister(){
    if($("#nu_email").val()==""){
      alert("Email address is required!");
      $("#nu_email").focus();
      return;
    }
    if($("#nu_password").val()==""){
      alert("Password is required!");
      $("#nu_password").focus();
      return;
    }
    var maillist = 0;
    if($("#nu_maillist").val()=="on"){
      maillist = 1;
    }
    $("#signup_button").attr("disabled","disabled").val("Processing...");
    var url = "data.php?operation=signup";
    var data = "&email="+$("#nu_email").val()+"&password="+$("#nu_password").val()+"&name="+$("#nu_name").val()+"&maillist="+maillist;
    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: "xml",
      success: doRegisterOutput
    });
  }

  function doRegisterOutput(xd){
    $("#signup_button").removeAttr("disabled").val("Sign up");
    switch($("response",xd).attr("code")){
      case "ok":
        doFBLogin();
      break;
      default:
        alert("User with such email is already exists!");
      break;
    }
  } 

  function clear_form_elements(form_container){
    var where = ':input';
    if(form_container){
      where = form_container+' input, textarea';
    }
    $(where).each(function() {
      switch(this.type) {
        case 'password':
        case 'select-multiple':
        case 'select-one':
        case 'text':
        case 'hidden':
        case 'textarea':
          $(this).val('');
        break;
        case 'checkbox':
        /*
        case 'radio':
          this.checked = false;
        */
      }
    });
  }

  function randomUUID() {
    var s = [], itoh = '0123456789ABCDEF';
    // Make array of random hex digits. The UUID only has 32 digits in it, but we
    // allocate an extra items to make room for the '-'s we'll be inserting.
    for (var i = 0; i <36; i++) s[i] = Math.floor(Math.random()*0x10);
    // Conform to RFC-4122, section 4.4
    s[14] = 4;  // Set 4 high bits of time_high field to version
    s[19] = (s[19] & 0x3) | 0x8;  // Specify 2 high bits of clock sequence
    // Convert to hex chars
    for (var i = 0; i <36; i++) s[i] = itoh[s[i]];
    // Insert '-'s
    s[8] = s[13] = s[18] = s[23] = '-';
    return s.join('');
  }

  function getMarkerObj(id){
    for(var i=0;i<markers_array.length;i++){
      if(markers_array[i].id==id){
        return markers_array[i];
        break;
      }
    } 
    return null;
  }

  function setLocation(){
    var location = $("#location").val();
    if(location==defalut_location_value || location.length==""){
      alert("Enter "+defalut_location_value+"!");
      return;
    } else {
      operation = "set_location";
      $("#location").attr("disabled","disabled");
      $("#distance_box").attr("disabled","disabled");

      // Need to replace on site's preferences[
      if(location.indexOf("Kingston")==-1){
        location += ", Kingston";
      }
      if(location.indexOf("Canada")==-1){
        location += ", Canada";
      }
      // ]

      switchCD("loading");
      pageTracker._trackEvent("Set Location", "Send Request", location);
      $.ajax({
        type: "GET",
        url: "data.php?operation=do_geocode&location="+location,
        dataType: "xml",
        success: findLocation
      });
    }
  }

  function findLocation(xd){
    var satus = parseInt($(xd).find("Status").find("code").text());
    if(satus==200){
      var current_location = $(xd).find("Placemark[id=p1]");
      var coordinates = $(current_location).find("coordinates").text().split(",");
      var address = $(current_location).find("address").text();
      pageTracker._trackEvent("Set Location", "Get Geocoded Data", address);
      var url = fullpath+mfile;
      if(mfile=="maas.html"){
        var url = "/"+defalut_region_tag+"/missing_animals";
        for(var i=0;i<maas_url_settings_array.length;i++){
          url+="/"+maas_url_settings_array[i];
        }
        url+="/";
      }
      document.location = url+"?operation="+operation+"&metric="+defalut_metric_attr+"&lat="+parseFloat(coordinates[1])+
                          "&lng="+parseFloat(coordinates[0])+"&radius="+parseFloat($("#distance_box").val())+"&address="+address;
    } else {
      switchCD("main_column");
      pageTracker._trackEvent("Set Location", "Not Geocoded", address);
      alert(address + " not found");
      $("#location").removeAttr("disabled");
      $("#distance_box").removeAttr("disabled");
    }
  }

  function createYourLocationMarker() {
    var latlng = new GLatLng($(user_location_data).attr("lat"),$(user_location_data).attr("lng"));
    var marker = new GMarker(latlng);
    var myHtml = "Your location:<br>"+$(user_location_data).attr("address");
    marker.infoHTML = myHtml;
    GEvent.addListener(marker,"click", function() {
      map.openInfoWindowHtml(latlng, myHtml);
    });
    return marker;
  }

  function drawCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity) {
    var d2r = Math.PI/180;
    var r2d = 180/Math.PI;
    //var Clat = radius * 0.014483;  // Convert statute miles into degrees latitude
    var Clat = radius / 111.12; // Convert km into degrees latitude
    var Clng = Clat/Math.cos(lat*d2r); 
    var Cpoints = []; 
    for (var i=0; i < 33; i++) { 
      var theta = Math.PI * (i/16); 
      Cy = lat + (Clat * Math.sin(theta)); 
      Cx = lng + (Clng * Math.cos(theta)); 
      var P = new GPoint(Cx,Cy); 
      Cpoints.push(P); 
    }
    var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity);
    return polygon;
  }

  function switchCD(switch_to){
    for(var i=0;i<page_content_array.length;i++){
      $("#"+page_content_array[i]).hide();
    }
    $("#"+switch_to).show();
  }

  function showDirection(){
    if(!user_location_data){
      alert("Please enter a start location and click \"On\"!");
      return;
    }
    if(!current_marker_obj){
      alert("You must have a destination location selected!");
      return;
    }
    show_direction = !show_direction;
    if(show_direction){
      $("#show_direction_link").html("Hide directions");
      $("#directions").show();
      setDirections();
    } else {
      $("#show_direction_link").html("Show directions");
      $("#directions").hide();
      if(directions_overlay){
        map.removeOverlay(directions_overlay);
      }
    }
  }

  function setDirections(){
    if(user_location_data && show_direction){
      var location = getLocationObj(current_marker_obj.id);
      var direction = "from: " + user_location_data.lat+","+user_location_data.lng + " to: " + location.lat+","+location.lng;
      gdir.load(direction,{"locale":"en_US",getPolyline:true,getSteps:true});
      var MapBounds = new GLatLngBounds();
      MapBounds.extend(new GLatLng(user_location_data.lat,user_location_data.lng));
      MapBounds.extend(new GLatLng(location.lat,location.lng));
      map.setZoom(map.getBoundsZoomLevel(MapBounds)-1);
      var clat = (MapBounds.getNorthEast().lat() + MapBounds.getSouthWest().lat()) /2;
      var clng = (MapBounds.getNorthEast().lng() + MapBounds.getSouthWest().lng()) /2;
      map.setCenter(new GLatLng(clat,clng));
    }
  }

  function handleErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
      alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
      alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
      alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
      alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
      alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    else alert("An unknown error occurred.");
  }

  function customPanel(map,mapname,dirn,div) {
    var html = "";
    function waypoint(point, type, address) {
      var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
      //html += "<div style='border:1px solid #707070;margin:10px 0px;background-color:e0e0e0;color:#000000;'>"+address+"</div>";
    }
    function routeDistance(dist) {
      html += "<div style='padding-bottom:0.3em;'><span class='tipArial'><b>"+dist+"</b></span></div>";
    }      
    function detail(point, num, description, dist) {
      html += "<div class='directionItem' onclick='showDirectionDetails(new GLatLng("+point.toUrlValue(6)+"))'>"+description+" ("+dist+")</div>";
    }
    function copyright(text) {
      //html += '<div style="font-size: 0.86em;">' + text + "</div>";
    }
    for (var i=0; i<dirn.getNumRoutes(); i++) {
      if (i==0) {
        var type="play";
      } else {
        var type="pause";
      }
      var route = dirn.getRoute(i);
      var geocode = route.getStartGeocode();
      var point = route.getStep(0).getLatLng();
      waypoint(point, type, geocode.address);
      routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
      for (var j=0; j<route.getNumSteps(); j++) {
        var step = route.getStep(j);
        detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
      }
    }
    var geocode = route.getEndGeocode();
    var point = route.getEndLatLng();
    waypoint(point, "stop", geocode.address);
    copyright(dirn.getCopyrightsHtml());
    div.innerHTML = html;
  }

  function changeRadius(){
    if(user_location_data){
      setLocation(true);
    }
  }

  function changeRegion(){
    if($('#region_box').val()==""){
      getSuggestRegion();
    } else {
      document.location = countryDomainPrefix+"/"+$('#region_box').val()+"/";
    }
  }

  function getLoadingHTML(align,tm,text){
    if(!align){
      var align = "center";
    }
    if(!tm){
      var tm = "30px";
    }
    if(!text){
      var text = "Loading. Please wait...";
    }
    return "<div style='margin-top:"+tm+";'><table align='"+align+"'><tr><td><img src='/img/ajax-loader.gif' width='24' height='24' style='margin-right:5px'/></td><td><div style='margin-bottom:6px;'><h3 class='loading'>"+text+"</h2></div></td></tr></table></div>";
  }


  function openFullMap(){
    //window.open(fullpath+"map.html");
    window.open(document.location+"map.html");
    //document.location = fullpath+"map.html";
  }
/**
 * jquery.simpletip 1.3.1. A simple tooltip plugin
 * 
 * Copyright (c) 2009 Craig Thompson
 * http://craigsworks.com
 *
 * Licensed under GPLv3
 * http://www.opensource.org/licenses/gpl-3.0.html
 *
 * Launch  : February 2009
 * Version : 1.3.1
 * Released: February 5, 2009 - 11:04am
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'([3-9a-zB-Z]|1\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(6($){6 Z(f,3){4 7=n;f=b(f);4 5=b(document.createElement(\'div\')).B(3.10).B((3.p)?3.11:\'\').B((3.C)?3.12:\'\').13(3.q).appendTo(f);a(!3.14)5.t();o 5.r();a(!3.C){f.hover(6(c){7.t(c)},6(){7.r()});a(!3.p){f.mousemove(6(c){a(5.D(\'N\')!==\'u\')7.E(c)})}}o{f.click(6(c){a(c.15===f.16(0)){a(5.D(\'N\')!==\'u\')7.r();o 7.t()}});b(v).mousedown(6(c){a(5.D(\'N\')!==\'u\'){4 17=(3.O)?b(c.15).parents(\'.5\').andSelf().filter(6(){d n===5.16(0)}).length:0;a(17===0)7.r()}})};b.18(7,{getVersion:6(){d[1,2,0]},getParent:6(){d f},getTooltip:6(){d 5},getPos:6(){d 5.i()},19:6(8,9){4 e=f.i();a(s 8==\'F\')8=G(8)+e.k;a(s 9==\'F\')9=G(9)+e.l;5.D({k:8,l:9});d 7},t:6(c){3.1a.m(7);7.E((3.p)?P:c);Q(3.1b){g\'H\':5.fadeIn(3.I);h;g\'1c\':5.slideDown(3.I,7.E);h;g\'1d\':3.1e.m(5,3.I);h;w:g\'u\':5.t();h};5.B(3.R);3.1f.m(7);d 7},r:6(){3.1g.m(7);Q(3.1h){g\'H\':5.fadeOut(3.J);h;g\'1c\':5.slideUp(3.J);h;g\'1d\':3.1i.m(5,3.J);h;w:g\'u\':5.r();h};5.removeClass(3.R);3.1j.m(7);d 7},update:6(q){5.13(q);3.q=q;d 7},1k:6(1l,K){3.1m.m(7);5.1k(1l,K,6(){3.1n.m(7)});d 7},L:6(8,9){4 1o=8+5.S();4 1p=9+5.T();4 1q=b(v).width()+b(v).scrollLeft();4 1r=b(v).height()+b(v).scrollTop();d[(1o>=1q),(1p>=1r)]},E:6(c){4 x=5.S();4 y=5.T();a(!c&&3.p){a(3.j.constructor==Array){8=G(3.j[0]);9=G(3.j[1])}o a(b(3.j).attr(\'nodeType\')===1){4 i=b(3.j).i();8=i.k;9=i.l}o{4 e=f.i();4 z=f.S();4 M=f.T();Q(3.j){g\'l\':4 8=e.k-(x/2)+(z/2);4 9=e.l-y;h;g\'bottom\':4 8=e.k-(x/2)+(z/2);4 9=e.l+M;h;g\'k\':4 8=e.k-x;4 9=e.l-(y/2)+(M/2);h;g\'right\':4 8=e.k+z;4 9=e.l-(y/2)+(M/2);h;w:g\'w\':4 8=(z/2)+e.k+20;4 9=e.l;h}}}o{4 8=c.pageX;4 9=c.pageY};a(s 3.j!=\'object\'){8=8+3.i[0];9=9+3.i[1];a(3.L){4 U=7.L(8,9);a(U[0])8=8-(x/2)-(2*3.i[0]);a(U[1])9=9-(y/2)-(2*3.i[1])}}o{a(s 3.j[0]=="F")8=1s(8);a(s 3.j[1]=="F")9=1s(9)};7.19(8,9);d 7}})};b.fn.V=6(3){4 W=b(n).eq(s 3==\'number\'?3:0).K("V");a(W)d W;4 X={q:\'A simple 5\',C:1t,O:1t,14:Y,j:\'w\',i:[0,0],L:Y,p:Y,1b:\'H\',I:1u,1e:P,1h:\'H\',J:1u,1i:P,10:\'5\',R:\'active\',11:\'p\',12:\'C\',focusClass:\'O\',1a:6(){},1f:6(){},1g:6(){},1j:6(){},1m:6(){},1n:6(){}};b.18(X,3);n.each(6(){4 el=new Z(b(n),X);b(n).K("V",el)});d n}})();',[],93,'|||conf|var|tooltip|function|self|posX|posY|if|jQuery|event|return|elemPos|elem|case|break|offset|position|left|top|call|this|else|fixed|content|hide|typeof|show|none|window|default|tooltipWidth|tooltipHeight|elemWidth||addClass|persistent|css|updatePos|string|parseInt|fade|showTime|hideTime|data|boundryCheck|elemHeight|display|focus|null|switch|activeClass|outerWidth|outerHeight|overflow|simpletip|api|defaultConf|true|Simpletip|baseClass|fixedClass|persistentClass|html|hidden|target|get|check|extend|setPos|onBeforeShow|showEffect|slide|custom|showCustom|onShow|onBeforeHide|hideEffect|hideCustom|onHide|load|uri|beforeContentLoad|onContentLoad|newX|newY|windowWidth|windowHeight|String|false|150'.split('|'),0,{}));
﻿/*
* jQuery pager plugin
* Version 1.0 (12/22/2008)
* @requires jQuery v1.2.6 or later
*
* Example at: http://jonpauldavies.github.com/JQuery/Pager/PagerDemo.html
*
* Copyright (c) 2008-2009 Jon Paul Davies
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* 
* Read the related blog post and contact the author at http://www.j-dee.com/2008/12/22/jquery-pager-plugin/
*
* This version is far from perfect and doesn't manage it's own state, therefore contributions are more than welcome!
*
* Usage: .pager({ pagenumber: 1, pagecount: 15, buttonClickCallback: PagerClickTest });
*
* Where pagenumber is the visible page number
*       pagecount is the total number of pages to display
*       buttonClickCallback is the method to fire when a pager button is clicked.
*
* buttonClickCallback signiture is PagerClickTest = function(pageclickednumber) 
* Where pageclickednumber is the number of the page clicked in the control.
*
* The included Pager.CSS file is a dependancy but can obviously tweaked to your wishes
* Tested in IE6 IE7 Firefox & Safari. Any browser strangeness, please report.
*/
(function($) {

    $.fn.pager = function(options) {

        var opts = $.extend({}, $.fn.pager.defaults, options);

        return this.each(function() {

        // empty out the destination element and then render out the pager with the supplied options
            $(this).empty().append(renderpager(parseInt(options.pagenumber), parseInt(options.pagecount), options.buttonClickCallback));
            
            // specify correct cursor activity
            $('.pages li').mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; });
        });
    };

    // render and return the pager with the supplied options
    function renderpager(pagenumber, pagecount, buttonClickCallback) {

        // setup $pager to hold render
        var $pager = $('<ul class="pages"></ul>');

        // add in the previous and next buttons
        //$pager.append(renderButton('first', pagenumber, pagecount, buttonClickCallback)).append(renderButton('prev', pagenumber, pagecount, buttonClickCallback));
        $pager.append(renderButton('prev', pagenumber, pagecount, buttonClickCallback));

        // pager currently only handles 10 viewable pages ( could be easily parameterized, maybe in next version ) so handle edge cases
        var startPoint = 1;
        //var endPoint = 9;
        var endPoint = 5;

        if (pagenumber > 2) {
            startPoint = pagenumber - 2;
            endPoint = pagenumber + 2;
        }

        if (endPoint > pagecount) {
            //startPoint = pagecount - 8;
            startPoint = pagecount - 4;
            endPoint = pagecount;
        }

        if (startPoint < 1) {
            startPoint = 1;
        }

        // loop thru visible pages and render buttons
        for (var page = startPoint; page <= endPoint; page++) {

            var currentButton = $('<li class="page-number">' + (page) + '</li>');

            page == pagenumber ? currentButton.addClass('pgCurrent') : currentButton.click(function() { buttonClickCallback(this.firstChild.data); });
            currentButton.appendTo($pager);
        }

        // render in the next and last buttons before returning the whole rendered control back.
        $pager.append(renderButton('next', pagenumber, pagecount, buttonClickCallback));
        //$pager.append(renderButton('next', pagenumber, pagecount, buttonClickCallback)).append(renderButton('last', pagenumber, pagecount, buttonClickCallback));

        return $pager;
    }

    // renders and returns a 'specialized' button, ie 'next', 'previous' etc. rather than a page number button
    function renderButton(buttonLabel, pagenumber, pagecount, buttonClickCallback) {

        if(buttonLabel=="prev"){
          var $Button = $('<li class="pgNext"><img src="/img/nav_prev.gif" width="5" height="9" style="margin-right:4px">prev</li>');
        } else if (buttonLabel=="next"){
          var $Button = $('<li class="pgNext">next<img src="/img/nav_next.gif" width="5" height="9" style="margin-left:4px"></li>');
        } else {
          var $Button = $('<li class="pgNext">' + buttonLabel + '</li>');
        }

        var destPage = 1;

        // work out destination page for required button type
        switch (buttonLabel) {
            case "first":
                destPage = 1;
                break;
            case "prev":
                destPage = pagenumber - 1;
                break;
            case "next":
                destPage = pagenumber + 1;
                break;
            case "last":
                destPage = pagecount;
                break;
        }

        // disable and 'grey' out buttons if not needed.
        if (buttonLabel == "first" || buttonLabel == "prev") {
            pagenumber <= 1 ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); });
        }
        else {
            pagenumber >= pagecount ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); });
        }

        return $Button;
    }

    // pager defaults. hardly worth bothering with in this case but used as placeholder for expansion in the next version
    $.fn.pager.defaults = {
        pagenumber: 1,
        pagecount: 1
    };

})(jQuery);






/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.5
 * 
 * Changelog :
 *  Version 0.5 
 *  - separate css style for current selected element and hover element which solve the highlight issue 
 *  Version 0.4
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});


/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) { 
	 }
	}
}
/* */

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.selectedClass || "selected"
	opt.debug = opt.debug || false;
	opt.onchange = opt.onchange || "";
	opt.width = opt.width || "";
	
	var elm_id = selectobj.id;
	var active = -1;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = $(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	//jquery input object 
	var $input = setupInput(opt);
	if(opt.width!=""){
	  $input.attr("style","width:"+opt.width+"px");
	}
	// hide select and append newly created elements
	$select.hide().before($input).before($container);
	
	init();
	
	$input
	.click(function(){
    if (!inFocus) {
		  $container.toggle();
		}
	})
	.focus(function(){
	   if ($container.not(':visible')) {
	       inFocus = true;
	       $container.show();
	   }
	})
	.keydown(function(event) {	   
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				break;
			//case 9:  // tab 
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				$('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
		}
	})
	.blur(function() {
		if ($container.is(':visible') && hasfocus > 0 ) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
			hideMe();	
		}
	});

	function hideMe() { 
		hasfocus = 0;
		$container.hide(); 
		//alert($input.val());
	}
	
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		if(opt.width!=""){
		  var width = $input.css('width');
		  $container.width(width);
		}
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		
		return $container;
	}
	
	function setupInput(options) {
		var input = document.createElement("input");
		var $input = $(input);
		$input.attr("id", elm_id+"_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass);
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
		return $input;	
	}
	
	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass(opt.hoverClass);

		$(lis[active]).addClass(opt.hoverClass);
	}
	
	function setCurrent() {	
		var li = $("li."+opt.currentClass, $container).get(0);
		var ar = (''+li.id).split('__');
		var el = ar[ar.length-1];
		$select.val(el);
		$input.val($(li).html());
		eval(opt.onchange);
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '__' + $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
			  var fl = $('li.'+opt.hoverClass, $container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				$('li.'+opt.currentClass).removeClass(opt.currentClass); 
				$(this).addClass(opt.currentClass);
				setCurrent();
				hideMe();
			});
		});
		return ul;
	}
	
};

  var google_map_key = "";
  var map_alaska, map_hawaii, draw_interval, waypoints=[], tooltip, el_map, nl_map, mapSearchControl, all_tags_data;
  var edit_options = new Array({id:"el_opt_dog_friendly",tag:"dogfriendly"},{id:"el_opt_treats",tag:"treats"},{id:"el_opt_waterbowl",tag:"waterbowl"},
                               {id:"el_opt_patio",tag:"patio"}, {id:"el_opt_resident_dog",tag:"resident dog"}, {id:"el_opt_resident_cat",tag:"resident cat"},
                               {id:"el_opt_hasdogs",tag:"hasdogs"}, {id:"el_opt_hascats",tag:"hascats"},{id:"el_opt_breakables",tag:"breakables"});
  var main_host = "http://"+document.location.host;
  var locations_array = new Array();
  var section_id, section_title, tag_id, sectionsData, tagsData, tagsTotal;
  var sectionTitle = "";
  var tagsPage = 3;
  var tagsSelectedPage = 0;
  var markers_array = [], map_regions = [], locations_array = [];
  var marker_counts, current_marker_obj;
  var defalut_region_id, defalut_region_tag, config_data, defalut_metric_attr, tags_ids, areas_array, set_address, region, user_location_data;
  var distance_steps = new Array("1","2","3","5","7","10");
  var p_size = 5;
  var p_current = 1;
  var tags_rule = "all";
  var nav_links = new Array();
  var new_region_marker, new_region_circle;
  var edit_listing_id, new_listing, mfile;
  var geocoder = null, details_mode = false;
  var common_fmv_opacity = 0.8;
  var mc_region = new GSize(80, 17);
  var maxGeoRequests = 100; // 500?
  var currentGeoRequest = 0;

  $(function() {
    $("#directions").hide();
    $("#results_details").hide();
    $("#el_confirm_div").hide();

    $("div#edit_listing").dialog(
      {autoOpen:false,bgiframe:true,width:850,height:480,modal:true,resizable:false,title:"Update / Modify Listing",
        open: function(event, ui) {
          if(!el_map){
            el_map = new GMap2(document.getElementById("el_map_canvas"));
            el_map.addControl(new GSmallMapControl());
            el_map.addControl(new GMapTypeControl());
          }
          el_map.clearOverlays();
        },
        buttons: {
          'Submit': function() {
            updateListing();
          },
          'Close Window': function() {
            $("div#edit_listing").dialog("close");
          }
        }
      }
    );

    $("div#new_listing").dialog(
      {autoOpen:false,bgiframe:true,width:490,height:120,modal:true,resizable:false,title:"Add New Listing",
        buttons: {
          'Search': function() {
            nl_start=1;
            nl_page=1;
            findNewListing();
          },
          'Close Window': function() {
            $("div#new_listing").dialog("close");
          }
        }
      }
    );

    $("div#new_listing_results_list").dialog(
      {autoOpen:false,bgiframe:true,width:800,height:540,modal:true,resizable:false,title:"Add New Listing",
        buttons: {
          'Close Window': function() {
            $("div#new_listing_results_list").dialog("close");
          }
        }
      }
    );    

    if($('#upload_button').length > 0){
      //new AjaxUpload('upload_button_id', {action: 'upload.php'});
      var button = $('#upload_button'), interval;
      new AjaxUpload(button,{
        action: '/upload.php',
        onSubmit : function(file, ext){
          // change button text, when user selects file			
          button.text('Uploading');
          // If you want to allow uploading only 1 file at time,
          // you can disable upload button
          //this.disable();
          // Uploding -> Uploading. -> Uploading...
          interval = window.setInterval(function(){
            var text = button.text();
            if (text.length < 13){
              button.text(text + '.');					
            } else {
              button.text('Uploading');				
            }
          }, 200);
        },
        onComplete: function(file, response){
          button.text('Upload');
          window.clearInterval(interval);
          // enable upload button
          this.enable();
          var thumbnail_content = "<div style='width:100px;overflow:auto;float:left;margin-right:5px;'><img src='/img/thumbnails/"+file+"' width='100'/></div> <input type='button' value='remove' onclick='removeThumbnail()'>";
          $("#el_thumbnail").val(file);
          $("#thumbnail").html(thumbnail_content);
        }
      });
    }
    if(set_address && set_address!=""){
      $("#location").val(set_address);
    } else {
      $("#location").val(defalut_location_value);
    }
    $("#distance_box").find("option").remove();
    $("#new_region_distance_box").find("option").remove();
    for(var i=0;i<distance_steps.length;i++){
      if(distance_steps[i]<=1){
        var title = distance_steps[i]+defalut_metric_attr;
      } else {
        var title = distance_steps[i]+defalut_metric_attr+"s";
      }
      $("#distance_box").append("<option value='"+distance_steps[i]+"'>"+title+"</option>");
      $("#new_region_distance_box").append("<option value='"+distance_steps[i]+"'>"+title+"</option>");
    }
    $("#location").focus(function() {
      if( this.value == defalut_location_value ) {
        this.value = "";
      }
    }).blur(function() {
      if( !this.value.length ) {
        this.value = defalut_location_value;
      }
    });
    $("#region_box").val(defalut_region_tag);
    $('#region_box').selectbox({onchange:"changeRegion()"});
    if(user_location_data && user_location_data.radius!=""){
      $("#distance_box").val(user_location_data.radius);
    }
    $('#distance_box').selectbox({inputClass:"selectbox_grey",containerClass:"selectbox-wrapper_grey",onchange:"changeRadius()"});
    $(".selectbox-wrapper_grey").css("margin-top","-"+(35+$("#distance_box").find("option").length*19)+"px");
    common_init();
    initializeMap();
    switch(pre_operation){
      case "add_new_listing":
        addNewListing();
      break;
      case "confirm":
        if(pre_id){
          editListing(pre_id);
        }
      break;
    }
    getLToG();
  });

  function removeNewRegionMarker(){
    map.removeOverlay(new_region_marker);
    map.removeOverlay(new_region_circle);
  }

  function setNewRegionMarker(){
    //var point = new GLatLng(39.639538,-34.101563);
    var point = map.getBounds().getCenter();
    new_region_marker = new GMarker(point, {draggable:true});
    GEvent.addListener(new_region_marker, 'dragend', function() {
      map.removeOverlay(new_region_circle);
      var point = new_region_marker.getPoint();
      new_region_circle = drawCircle(point.lat(), point.lng(), $("#new_region_distance_box").val(), "#000080", 0.5, 0.75, "#0000FF",0.25);
      map.addOverlay(new_region_circle);
    });
    map.addOverlay(new_region_marker);
    new_region_circle = drawCircle(point.lat(), point.lng(), $("#new_region_distance_box").val(), "#000080", 0.5, 0.75, "#0000FF",0.25);
    map.addOverlay(new_region_circle);
  }

  function changeNewRegionRadius(){
    map.removeOverlay(new_region_circle);
    var point = new_region_marker.getPoint();
    new_region_circle = drawCircle(point.lat(), point.lng(), $("#new_region_distance_box").val(), "#000080", 0.5, 0.75, "#0000FF",0.25);
    map.addOverlay(new_region_circle);
  }

  function set_top_nav_link(action,title){
    return "<div class='setop'><div class='l'></div><a href='javascript:void(0)' onclick='"+action+"'>"+title+"</a><div class='r'></div></div>";
  }

  function getNavLinks(issearch){
    var content = "";
    if(issearch){
      //content += "<a href='javascript:void(0)' onclick='doSearch()'>Search for '"+$("#search_text").val()+"'</a>";
      content += set_top_nav_link('doSearch()',"Search for "+$("#search_text").val());
    } else {
      if(user_location_data){
        //content += "<a href='javascript:void(0)' onclick='tags_ids=\"\";tags_rule=\"all\";getMapData()'>Within "+$("#distance_box").find(":selected").text()+"</a>";
        content += set_top_nav_link('tags_ids=\"\";tags_rule=\"all\";getMapData()',"Within "+$("#distance_box").find(":selected").text());
      } else {
        var region = $("#region_box").val();
        /*
        if(region && region!=""){
          //content += "<a href='javascript:void(0)' onclick='tags_ids=\"\";tags_rule=\"all\";getMapData()'>"+$("#region_box").find(":selected").text()+"</a>";
          content += set_top_nav_link('tags_ids=\"\";tags_rule=\"all\";getMapData()',$("#region_box").find(":selected").text());
        }
        */
      }
      if(section_id && section_id!=""){
        content += set_top_nav_link("document.location=\""+fullpath+"\";",section_title);
      }
      var tags_ids_array = new Array();
      if(tags_ids && tags_ids.length>0){
        tags_ids_array = tags_ids.split(",");
      }
      //alert(tags_ids_array.length)
      if(tags_ids_array.length>0){
        var tcontent = "";
        for(var i=0;i<tags_ids_array.length;i++){
          if(tags_ids_array[i]!=section_id){
            for(var j=0;j<tagsData.length;j++){
              if(tagsData[j].id==tags_ids_array[i]){
                //tcontent += "<a href='javascript:void(0)' onclick='tags_ids=\""+$(this).attr("id")+"\";tags_rule=\"all\";getMapData()'>"+$(this).attr("title")+"</a>";
                tcontent += set_top_nav_link("document.location=\""+fullpath+"all/"+tagsData[j].tag+"/\";",tagsData[j].title);
              }
            }
          }
        }
        content += tcontent;
      }
    }
    $("#map_top_nav_way").html(content);
  }

  function getMapData(){
    if(user_location_data){
      var url = "data.php?operation="+operation+"&metric="+defalut_metric_attr+
                "&lat="+user_location_data.lat+"&lng="+user_location_data.lng+"&radius="+user_location_data.radius;
    } else {
      var region = $("#region_box").val()
      var url = "data.php?operation="+operation+"&region="+region;
    }
    var tags_ids_array = new Array();
    if(tags_ids && tags_ids.length>0){
      tags_ids_array = tags_ids.split(",");
    }
    url += "&tags_ids[]="+section_id;
    url += "&section_id="+section_id+"&tags_rule="+tags_rule;
    if(tags_ids_array.length>0){
      for(var i=0;i<tags_ids_array.length;i++){
        url += "&tags_ids[]="+tags_ids_array[i];
      }
    }
    switchCD("loading");
    $.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: outputRegion
    });
  }

  function locationClass(id,title,phone,address,thumbnail,zoom_level,lat,lng,sponsored,website,partner,tag_ids,sections){
    this.id = id;
    this.title = title;
    this.phone = phone;
    this.address = address;
    this.thumbnail = thumbnail;
    this.zoom_level = parseInt(zoom_level);
    this.lat = parseFloat(lat);
    this.lng = parseFloat(lng);
    this.sponsored = sponsored;
    this.website = website;
    this.partner = partner;
    this.tag_ids = tag_ids;
    this.tag_ids_str = "";
    if(tag_ids.length>0){
      this.tag_ids = tag_ids.split(",");
      this.tag_ids_str = tag_ids;
    }
    this.sections = sections;
  }

  function locationClassXML(src_xml){
    this.id = $(src_xml).attr("id");
    this.title = $(src_xml).attr("title");
    this.phone = $(src_xml).attr("phone");
    this.address = $(src_xml).attr("address");
    this.thumbnail = $(src_xml).attr("thumbnail");
    this.zoom_level = parseInt($(src_xml).attr("zoom_level"));
    this.lat = parseFloat($(src_xml).attr("lat"));
    this.lng = parseFloat($(src_xml).attr("lng"));
    this.sponsored = $(src_xml).attr("sponsored");
    this.website = $(src_xml).attr("website");
    this.partner = $(src_xml).attr("partner");
    this.tag_ids = "";
    this.tag_ids_str = "";
    if($(src_xml).attr("tag_ids")){
      this.tag_ids = $(src_xml).attr("tag_ids").split(",");
      this.tag_ids_str = $(src_xml).attr("tag_ids");
    }
    var sections = new Array();
    $("section",src_xml).each(function(){
      var id = $(this).attr("id");
      var title = $(this).attr("title");
      sections.push({id: id, title: title});
    });
    this.sections = sections;
  }

  function focusLocation(mid){
    var current_marker = getMarkerObj(mid);
    map.setCenter(current_marker.getPoint());
    current_marker.openInfoWindowHtml(current_marker.infoHTML);
  }

  function createLocationMarker(latlng, location) {
    var cIcon = new GIcon(G_DEFAULT_ICON);
    cIcon.image = "/img/red.png";
    markerOptions = { icon:cIcon };
    var marker = new GMarker(latlng,markerOptions);
    marker.id = location.id;
    var icons = "";
    $("tag_legend",config_data).each(function(){
      for(var j=0;j<location.tag_ids.length;j++){
        if($(this).attr("id")==location.tag_ids[j]){
          var icon_eid = "icon_"+location.id+"_"+$(this).attr("id");
          icons += "<img class='pngimage' id='"+icon_eid+"' src='"+$(this).attr("icon_url")+"'>";
        }
      }
    });
    GEvent.addListener(marker,'mouseover',function(){
      showTooltip('<div class="tooltip">'+location.title+'<br>'+icons+'</div>',new GLatLng(location.lat, location.lng),10);
    });
    GEvent.addListener(marker,'mouseout',function(){
      tooltip.style.visibility="hidden";
    });

    GEvent.addListener(marker,"click", function() {
      //map.openInfoWindowHtml(latlng, myHtml);
      current_marker_obj = marker;
      getLocation(location.id);
      setDirections();
    });
    return marker;
  }

  function showTooltip(tooltip_text,tooltip_point,radius) {
    tooltip.innerHTML = tooltip_text;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(tooltip_point,map.getZoom());
    var width=(radius+1);
    var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x + width,- offset.y + point.y)); 
    pos.apply(tooltip);
    tooltip.style.visibility="visible";
  }

  function outputRegion(locations){
    map.clearOverlays();
    //backToDirectory();
    $("#location").removeAttr("disabled");
    $("#distance_box").removeAttr("disabled");
    totalLocations = locations_array.length;
    var MapBounds = new GLatLngBounds();

    map_regions = new Array();
    if(user_location_data){
      var lat = $(user_location_data).attr("lat");
      var lng = $(user_location_data).attr("lng");
      var radius = $(user_location_data).attr("radius");
      var polygon = drawCircle(lat, lng, radius, "#000080", 0.5, 0.75, "#0000FF",.2);
      var point = new GLatLng(lat, lng);
      MapBounds.extend(point);
      map.setCenter(point);
      var marker = new createYourLocationMarker();
      map.addOverlay(marker);
      marker.openInfoWindowHtml(marker.infoHTML);
    } else if($(region).length>0){
      var lat = parseFloat($(region).attr("lat"));
      var lng = parseFloat($(region).attr("lng"));
      var radius = parseFloat($(region).attr("radius"));
      var polygon = drawCircle(lat, lng, radius, "#000080", 0.5, 0.75, "#0000FF",0);
      map.setCenter(new GLatLng(lat, lng));
    }
    if(polygon){
      map_regions.push(polygon);
      if(map_options_regions){
        polygon.show();
      } else {
        polygon.hide();
      }
      map.addOverlay(polygon);
    }
    $(areas_array).each(function(){
      var point = new GLatLng(parseFloat($(this).attr("lat")),parseFloat($(this).attr("lng")));
      MapBounds.extend(point);
      var polygon = drawCircle(parseFloat($(this).attr("lat")), parseFloat($(this).attr("lng")), parseFloat($(this).attr("radius")), "#800000", 0.5, 0.75, "#FF0000",.2);
      map_regions.push(polygon);
      if(map_options_regions){
        polygon.show();
      } else {
        polygon.hide();
      }    
      map.addOverlay(polygon);
    });
    markers_array = new Array();
    var marker_count = 0;
    p_current = 1;
    
    for(var i=0;i<locations_array.length;i++){
      var location = locations_array[i];
      if(location.lat && location.lng){
        var point = new GLatLng(location.lat,location.lng);
        var marker = new createLocationMarker(point, location);
        markers_array.push(marker);
        map.addOverlay(marker,0,17);
        MapBounds.extend(point);
      }
      marker_count++;
    }
    if(totalLocations==0){
      //$("#results_list_data").html("There is no data<br>");
      $("#results_list_page_nav_top").html("");
      $("#results_list_page_nav").html("");
    } else {
      map.setZoom(map.getBoundsZoomLevel(MapBounds));
      var clat = (MapBounds.getNorthEast().lat() + MapBounds.getSouthWest().lat()) /2;
      var clng = (MapBounds.getNorthEast().lng() + MapBounds.getSouthWest().lng()) /2;
      map.setCenter(new GLatLng(clat,clng));
      makePage(p_current);
    }
    getNavLinks();
    $("#main").css("visibility","visible");
    do_search_state = false;
    $("#search_type").val("");
    switchCD("main_column");
    if(edit_listing_id && edit_listing_id!=null){
      var edit_listing = getLocationObj(edit_listing_id);
      if(edit_listing==null){
        $("#search_type").val("listing");
        $("#search_id").val(edit_listing_id);
        doSearch();
      } else {
        getLocation(edit_listing_id);
      }
      edit_listing_id = null;
    }
  }

  function makeTagsPage(pc){
    var content = "";
    tagsSelectedPage = pc;
    var prevLink = "";
    var nextLink = "";
    if(tagsSelectedPage>0){
      prevLink = "<a href='javascript:void(0)' onclick='makeTagsPage("+(tagsSelectedPage-1)+")'>&#171; prev</a>";
    }
    if(((tagsSelectedPage+1)*tagsPage)<tagsTotal){
      nextLink = "<a href='javascript:void(0)' onclick='makeTagsPage("+(tagsSelectedPage+1)+")'>next &#187;</a>";
    }
    var tags_counter = 0;
    var hr = "border-bottom:1px solid #cef4f8;";
    $(tagsData).each(function(){
      if(tags_counter>=(tagsSelectedPage*tagsPage) && tags_counter<((tagsSelectedPage+1)*tagsPage)){
        if(tags_counter==tagsTotal-1){
          hr = "";
        }
        content += "<div style='padding-bottom:6px;padding-top:6px;"+hr+"'><a href='javascript:void(0)' class='general' onclick='tags_ids=\""+$(this).attr("id")+"\";tags_rule=\"all\";getMapData()'>"+$(this).attr("title")+"&#160;("+$(this).attr("count")+")</a><br></div>";
      }
      tags_counter++;
    });
    if(content!=""){
      if(prevLink!=""){
        content += prevLink;
      }
      if(nextLink!=""){
        if(prevLink!=""){
          content += " - ";
        }
        content += nextLink;
      }
    }
    $("#tags_list").html(content);
  }

  function makePage(pc){
    p_current = pc;
    var result = "";
    var max_limit = (pc)*p_size;
    if(totalLocations<max_limit){
      max_limit = totalLocations;
    }

    for(var i=0;i<markers_array.length;i++){
      markers_array[i].setImage("/img/grey.png");
    }

    for(var i=((pc-1)*p_size);i<max_limit;i++){
      var location = locations_array[i];
      getMarkerObj(location.id).setImage("/img/red.png");
      var phone = "";
      if(location.phone!=""){
        phone = "<h4>"+location.phone+"</h4>";
      }
      if(location.sponsored){
        var location_title = "<b>"+location.title+"</b>";
      } else {
        var location_title = location.title;
      }
      var icons = "";
      $("tag_legend",config_data).each(function(){
        for(var j=0;j<location.tag_ids.length;j++){
          if($(this).attr("id")==location.tag_ids[j]){
            icons += "<img src='/images/icons/"+$(this).attr("id")+".png' alt='"+$(this).attr("title")+"' title='"+$(this).attr("title")+"'>";
          }
        }
      });
      if(icons!=""){
        icons = "<span class='icons'>"+icons+"</span>";
      }
      result += "<a href='javascript:void(0)' onclick='getLocation("+location.id+")'>"+
                "  <span class='c'>"+
                "    <strong>"+location_title+"</strong>"+icons+
                "    <em>"+location.address+"</em>"+
                "    <span class='link'>View Profile</span>"+
                "  </span>"+
                "</a>";
    }
    if(totalLocations>p_size){
      $("#results_list_page_nav_top").pager({ pagenumber: p_current, pagecount: Math.ceil(totalLocations/p_size), buttonClickCallback: makePage });
      $("#results_list_page_nav").pager({ pagenumber: p_current, pagecount: Math.ceil(totalLocations/p_size), buttonClickCallback: makePage });
    } else {
      $("#results_list_page_nav_top").html("");
      $("#results_list_page_nav").html("");
    }

    $("#results_list_data").html(result);
  }


  function getLocationDescription(location){
    var icons = "";
    var is_breakables = "";
    $("tag_legend",config_data).each(function(){
      for(var j=0;j<location.tag_ids.length;j++){
        if($(this).attr("id")==location.tag_ids[j]){
          var icon_eid = "icon_"+location.id+"_"+$(this).attr("id");
          icons += "<img id='"+icon_eid+"' src='"+$(this).attr("icon_url")+"' class='pngimage'>";
        }
        if(parseInt(location.tag_ids[j])==29){
          is_breakables = "<p><span style='color:#ad0000'>Caution for breakables</span></p>";
        }
      }
    });
    var services = "";
    $("service",config_data).each(function(){
      var title = $(this).attr("title");
      var new_string = "";
      $("tag",this).each(function(){
        var conf_tags = $(this).attr("id").split(",");
        var conf_tags_titles = new Array();
        if($(this).attr("titles")){
          conf_tags_titles = $(this).attr("titles").split(",");
        }
        if(conf_tags.length<=1){
          for(var j=0;j<location.tag_ids.length;j++){
            if(conf_tags[0]==location.tag_ids[j]){
              if(new_string==""){
                new_string += title+" ";
              } else {
                new_string += ", ";
              }
              new_string += "<a href='"+fullpath+"all/"+$(this).attr("tag")+"/'>"+$(this).attr("title")+"</a>";
            }
          }
        } else {
          for(var k=0;k<conf_tags.length;k++){
            var is_common = false;
            for(var j=0;j<location.tag_ids.length;j++){
              if(conf_tags[k]==location.tag_ids[j]){
                tags_ids_str = "";
                var tags_title_str = "";
                for(var l=0;l<conf_tags.length;l++){
                  if(tags_ids_str!=""){
                    tags_ids_str+=", ";
                    tags_title_str+=", ";
                  }
                  tags_ids_str += conf_tags[l];
                  tags_title_str += conf_tags_titles[l];
                }
                if(!is_common){
                  if(new_string==""){
                    new_string += title+" ";
                  } else {
                    new_string += ", ";
                  }
                  var final_title = "";
                  if(tags_title_str!=""){
                    final_title = $(this).attr("title")+" ("+tags_title_str+")";
                  } else {
                    final_title = $(this).attr("title");
                  }
                  new_string += "<a href='javascript:void(0)' onclick='tags_ids=\""+tags_ids_str+"\";tags_rule=\"all\";getMapData()'>"+final_title+"</a>";
                  is_common = true;
                }
              }
            }
            if(is_common){
              break;
            }
          }
        }
      });
      if(new_string!=""){
        services += new_string+"<br>";
      }
    });
    if(services!=""){
      services = "<p>"+services+"</p>";
    }
    if(icons!=""){
      icons = "<p><div>"+icons+"<br></div></p>";
    }
    var thumbnail = "";
    if(location.thumbnail!=""){
      thumbnail = "<p><div><img src='/img/thumbnails/"+location.thumbnail+"' width='100' style='margin-top:3px;margin-bottom:5px;'><br></div></p>";
    }
    var website = "";
    if(location.partner==1){
      website = location.website;
      if(website.indexOf("http://")==-1){
        website = "http://"+website;
      }
      website = "<p><a href='"+website+"' target='_blank'>"+location.website+"</a></p>";
    }
    var edit_link = "<div id='update_listing'><a href='javascript:void(0)' onclick='getListingDetails("+location.id+")'>Details</a>&#160;&#160; <a href='javascript:void(0)' onclick='editListing("+location.id+")'>Update / Modify This Listing</a></div>";
    var result = "<div class='locationDescription'>"+
//                  "  <h2>"+location.title+"</h2>"+
                  icons+
                  thumbnail+
                  "  <p>Address: "+location.address+"</p>"+
                  is_breakables+
                  "  <div style='float:left'><p class='phone'>"+location.phone+"</p></div><div style='float:left'><img src='/img/phone_lg.gif' width='20' height='20' border='0' style='margin-left:4px;'></div><div style='clear:both;'></div>"+website+
                  
//                  "  <p><a href='javascript:void(0)' style='color:#0000ff'>Add to Favourites or Phonebook</a></p><br>"+
                  services+edit_link+
                  "</div>";
    return result;
  }

  function getListingDetails(id){
    var location = getLocationObj(id);
    document.location = countryDomainPrefix+fullpath+getDetailsPath(location);
    //window.open(fullpath+id+".html");
  }

  function getDetailsPath(location){
    var path = location.title.toLowerCase().replace(/ /g,"_")+"_"+location.address.toLowerCase().replace(/ /g,"_")+"_"+location.id+".html";
    path = path.replace(/#/g,"");
    path = path.replace(/&/g,"");
    path = path.replace(/\?/g,"");
    path = path.replace(/'/g,"");
    path = path.replace(/,/g,"");
    return path;
  }

  function getLocation(lid){
    if(!map_zoom_level || map.getZoom()<map_zoom_level){
      map_zoom_level = map.getZoom()-1;
    }
    var location = getLocationObj(lid);
    var content = getLocationDescription(location);
    if(!details_mode){
      headerData = $("#results_list_header").html();
    }
    var sections = "";
    for(var i=0;i<location.sections.length;i++){
      if(sections!=""){
        sections += ", ";
      }
      sections += "<a href='/"+default_region_title+"/"+location.sections[i].tag+"/' style='color:#707070'>"+location.sections[i].title+"</a>";
    }
    map_center = map.getCenter();
    current_marker_obj = getMarkerObj(lid);
    var msections = "";
    if(sections!=""){
      msections = "<p style='margin-bottom:5px;'>"+sections+"</p>";
    }
    current_marker_obj.openInfoWindowHtml("<p class='markerHeader'><b>"+location.title+"<br></b></p>"+msections+content);
    if(location.zoom_level>0){
      map.setCenter(current_marker_obj.getPoint(),location.zoom_level);
    } else {
      map.setCenter(current_marker_obj.getPoint(),17);
    }
    if(sections!=""){
      sections = "<p>"+sections+"</p>";
    }
    details_mode = true;
    $("#results_list_header").html("<h2>"+location.title+"</h2>"+sections+"<p style='margin-top:6px;'><a href='javascript:void(0)' onclick='backToDirectory()' class='general'>&#171; back to directory</a></p>");
    $("#results_list_data").hide();
    $("#results_list_page_nav_top").hide();
    $("#results_list_page_nav").hide();
    $("#results_details").html(content);
    $("#results_details").show();
  }

  function getSuggestRegion(){
    headerData = $("#results_list_header").html();
    var content = "<table cellpadding='2' cellspacing='3' border='0'>"+
                  "<tr>"+
                  "  <td>Region title: </td>"+
                  "  <td><input id='new_region_title' type='text' style='width:140px;'/></td>"+
                  "</tr>"+
                  "<tr>"+
                  "  <td>Region radius: </td>"+
                  "  <td>"+
                  "    <select id='new_region_distance_box' onchange='changeNewRegionRadius()' style='width:144px;'>";
        for(var i=0;i<distance_steps.length;i++){
          if(distance_steps[i]<=1){
            var title = distance_steps[i]+defalut_metric_attr;
          } else {
            var title = distance_steps[i]+defalut_metric_attr+"s";
          }
          content+= "<option value='"+distance_steps[i]+"'>"+title+"</option>";
        }
        content+= "    </select>"+
                  "  </td>"+
                  "</tr>"+
                  "<tr>"+
                  "  <td>&#160;</td>"+
                  "  <td><input type='button' value='Submit' onclick='doSuggestRegion()'>&#160;<input type='button' value='Cancel' onclick='removeNewRegionMarker();backToDirectory()'></td>"+
                  "</tr>"+
                  "</table>";
    $("#results_list_header").html("<div class='sectionHeader'><h1>Suggest Region</h1><h5 style='margin-top:6px;'>Drag and drop the marker to setup region center.</h5></div>");
    $("#results_list_data").hide();
    $("#results_list_page_nav_top").hide();
    $("#results_list_page_nav").hide();
    $("#results_details").html(content);
    $("#results_details").show();
    setNewRegionMarker();
  }

  function doSuggestRegion(){
    if($("#new_region_title").val()==""){
      alert("Region title is required!");
      return;
    }
    var point = new_region_marker.getPoint();
    switchCD("loading");
    pageTracker._trackEvent("Suggest New Region", "Send Request", $("#new_region_title").val());
    $.ajax({
      type: "GET",
      url: "data.php?operation=set_new_region&lat="+point.lat()+"&lng="+point.lng()+"&radius="+$("#new_region_distance_box").val()+"&title="+escape($("#new_region_title").val()),
      dataType: "xml",
      success: outputNewRegion
    });
  }

  function outputNewRegion(xd){
    window.location.reload();
  }

  function backToDirectory(){
    $("#results_list_header").html(headerData);
    $("#results_details").hide();
    $("#results_list_data").show();
    $("#results_list_page_nav_top").show();
    $("#results_list_page_nav").show();
    switchCD("main_column");
    map.setCenter(map_center,map_zoom_level);
    if(current_marker_obj){
      current_marker_obj.closeInfoWindow();
    }
    details_mode = false;
  }

  function MoreControl(){};
  MoreControl.prototype = new GControl();
  MoreControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    var savepos = document.createElement("div");
    var title_show = "Show regions";
    var title_hide = "Hide regions";
    savepos.id= "map_option_regions";
    savepos.title= "Show/Hide regions layers on the map";
    savepos.className= "MDbuttons";
    savepos.style.width= "80px";
    container.appendChild(savepos);
    if(map_options_regions){
      savepos.appendChild(document.createTextNode(title_hide));
    } else {
      savepos.appendChild(document.createTextNode(title_show));
    }    
    GEvent.addDomListener(savepos, "click", function() {
      if(map_options_regions){
        $("#map_option_regions").html(title_show);
      } else {
        $("#map_option_regions").html(title_hide);
      }
      map_options_regions = !map_options_regions;
      for(var i = 0;i<map_regions.length;i++){
        if(map_options_regions){
          map_regions[i].show();
        } else {
          map_regions[i].hide();
        }
      }
    });
    map.getContainer().appendChild(container);
    return container;
  }
  MoreControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, mc_region);
  }

  function getLocationObj(id){
    for(var i=0;i<locations_array.length;i++){
      if(locations_array[i].id==id){
        return locations_array[i];
        break;
      }
    } 
    return null;
  }

  function setNewListingPositionMarker(point){
    var marker = new GMarker(point, {draggable:true});
    GEvent.addListener(marker, 'dragend', function() {
      $("#el_lat").val(marker.getPoint().lat());
      $("#el_lng").val(marker.getPoint().lng());
    });
    el_map.addOverlay(marker);
  }

  function editListing(lid){
    var url = "data.php?operation=get_listing&lid="+lid;
    $("div#edit_listing").dialog("open");
    $("div#edit_listing div.dw_content").hide();
    $("div#edit_listing div.dw_message").html(getLoadingHTML()).show();
    //switchCD("loading");
    $.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: editListingOutput
    });
  }

  function editListingOutput(xd){
    if(pre_operation=="confirm"){
      $("#edit_listing_header").html("Confirm Your Business");
      $("#el_confirm_div").show();
      if($("location",xd).attr("confirm")==1){
        $("#el_confirmation").val("confirmed");
        $("#el_confirmation").attr("readonly","readonly");
      } else {
        $("#el_confirmation").val("");
        $("#el_confirmation").removeAttr("readonly");
      }
    } else {
      $("#edit_listing_header").html("Update / Modify Listing");
    }
    all_tags_data = $("tags",xd);
    $("#el_id").val($("location",xd).attr("id"));
    $("#el_title").val($("location",xd).attr("title"));
    $("#el_address").val($("location",xd).attr("address"));
    $("#el_website").val($("location",xd).attr("website"));
    $("#el_phone").val($("location",xd).attr("phone"));
    $("#lregions").html($("location",xd).attr("regions"));
    $("#el_lat").val($("location",xd).attr("lat"));
    $("#el_lng").val($("location",xd).attr("lng"));
    var thumbnail_content = "";
    if($("location",xd).attr("thumbnail")!=""){
      thumbnail_content = "<div style='width:100px;overflow:auto;float:left;margin-right:5px;'><img src='/"+$("location",xd).attr("thumbnail")+"' width='100'/></div> <input type='button' value='remove' onclick='removeThumbnail()'>";
    }
    $("#thumbnail").html(thumbnail_content);
    var zoom_level = 17
    if(parseInt($("location",xd).attr("zoom_level"))>0){
      zoom_level = parseInt($("location",xd).attr("zoom_level"));
    }
    el_map.clearOverlays();
    var point = new GLatLng(parseFloat($("location",xd).attr("lat")), parseFloat($("location",xd).attr("lng")));
    el_map.setCenter(point, zoom_level);
    setNewListingPositionMarker(point);
    for(var i=0;i<edit_options.length;i++){
      $("#"+edit_options[i].id).attr('checked',false);
    }
    var tags_content = "";
    $("tag",$("location",xd)).each(function(){
      for(var i=0;i<edit_options.length;i++){
        var c = edit_options[i];
        if(c.tag==$(this).attr("tag")){
          $("#"+c.id).attr('checked',true);
          break;
        }
      }
    });
    initListingTags("el_tags_div","el_tags",$("location",xd));
    getPopularTags();
    //switchCD("edit_listing");
    initListingTagsBox();
  }

  function initListingTagsBox(){
    $("#el_tags").fcbkcomplete({
      json_url: '/tags.php',
      cache: false,
      filter_case: false,
      filter_hide: true,
      filter_selected: true,
      onselect: "checkParentsTag",
      height:5,
      newel: true
    });
  }

  function initListingTags(container_div,container_tags,xd){
    $("#"+container_div).html("").append("<select id='"+container_tags+"' name='el_tags'></select>");
    if(xd){
      //$("tag",$("location",xd)).each(function(){
      $(xd).find("tag").each(function(){
        var edit_options_flag = false;
        for(var i=0;i<edit_options.length;i++){
          var c = edit_options[i];
          if(c.tag==$(this).attr("tag")){
            $("#"+c.id).attr('checked',true);
            edit_options_flag = true;
            break;
          }
        }
        if(edit_options_flag==false){
          $("#"+container_tags).append("<option value='"+$(this).attr("tag")+"' class='selected'>"+$(this).attr("title")+"</option>");
        }
      });
    }
    $("div#edit_listing div.dw_message").hide();
    $("div#edit_listing div.dw_content").show();
  }

  function updateListing(){
    if(pre_operation=="confirm"){
      if($("#el_confirmation").val().length==0){
        alert("Enter confirmation code!");
        $("#el_confirmation").focus();
        return;
      }
    }
    if($("#el_lat").val()=="" || $("#el_lng").val()==""){
      getCoordinates($("#el_address").val());
    } else {
      var url = "data.php?operation=update_listing&lid="+$("#el_id").val();
      var tags_str = "";
      $("#el_tags").find("option.selected").each(function(){
        if(tags_str!=""){
          tags_str+=",";
        }
        tags_str+=$(this).val();
      });
      var tags_str_array = tags_str.split(",");
      for(var i=0;i<edit_options.length;i++){
        var c = edit_options[i];
        var exists = false;
        for(var j=0;j<tags_str_array.length;j++){
          if(c.tag == tags_str_array[j]){
            exists = true;
          }
        }
        if($("#"+c.id).attr('checked') && exists==false) {
          if(tags_str!="") tags_str += ",";
          tags_str += c.tag;
        }
      }
      //switchCD("loading");
      $("div#edit_listing div.dw_content").hide();
      $("div#edit_listing div.dw_message").show();
      pageTracker._trackEvent("Update Listing", "Send Request", "ID: "+$("#el_id").val());
      $.ajax({
        type: "POST",
        url: url,
        data: "title="+escape($("#el_title").val())+"&address="+escape($("#el_address").val())+"&phone="+escape($("#el_phone").val())+
              "&lat="+$("#el_lat").val()+"&lng="+$("#el_lng").val()+"&tags="+tags_str+"&thumbnail="+$("#el_thumbnail").val()+
              "&website="+escape($("#el_website").val())+"&ccode="+$("#el_confirmation").val(),
        dataType: "xml",
        success: updateListingOutput
      });
    }
  }

  function updateListingOutput(xd){
    if($("response",xd).length>0){
      switch($("response",xd).attr("code")){
        case "confirmed":
          alert("Your business was successfully confirmed! Thank You!");
        break;
        case "not_confirmed":
          alert("Wrong confiramtion number! Your business was NOT confirmed!");
          editListing(pre_id);
          return;
        break;
      }
    }
    if($("location",xd).length>0){
      var updated_location = new locationClassXML($("location",xd));
      for(var i=0;i<locations_array.length;i++){
        if(locations_array[i].id==$("location",xd).attr("id")){
          locations_array[i] = updated_location;
          pageTracker._trackEvent("Update Listing", "Listing Updated", "ID: "+updated_location.id);
        }
      }
      //document.location = fullpath+parseInt($("response",xd).attr("id"))+".html";
    }
    $("div#edit_listing").dialog("close");
    outputRegion();
    //backToDirectory();
  }

  function getCoordinates(address) {
    if (geocoder) {
      geocoder.getLatLng(address,
        function(point) {
          if (!point) {
            alert(address + " not found");
          } else {
            alert("Please confirm location!");
            var zoom_level = 17;
            el_map.clearOverlays();
            el_map.setCenter(point, zoom_level);
            setNewListingPositionMarker(point);
            $("#el_lat").val(point.lat());
            $("#el_lng").val(point.lng())
          }
        }
      );
    }
  }

  function removeThumbnail(){
    var thumbnail_content = "";
    $("#el_thumbnail").val("");
    $("#thumbnail").html("");
  }

  function addNewListing(){
    $("#nl_search").val("");
    //$("#new_listing_results_list").html("");
    $("div#new_listing div.dw_message").hide();
    $("div#new_listing div.dw_content").show();
    $("div#new_listing").dialog("open");
    //switchCD("new_listing");
  }

  function findNewListing(){
    $("div#new_listing div.dw_content").hide();
    $("div#new_listing div.dw_message").html(getLoadingHTML(null,"0px")).show();
    var search_str = $("#nl_search").val();
    var url = "data.php?operation=new_location&search="+search_str+"&start="+nl_start+"&page="+nl_page;
    pageTracker._trackEvent("Add New Listing", "Send Request", search_str);
    $.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: newListingOutput
    });
  }

  function newListingOutput(xd){
    all_tags_data = $("tags",xd);
    new_listing = xd;
    //switchCD("new_listing");
    nl_page = parseInt($("location_settings",xd).attr("page"));
    nl_start =  parseInt($("new_location_settings",xd).attr("start"));
    nl_total_pages =  parseInt($("new_location_settings",xd).attr("total_pages"));
    var lcontent = "";
    if($("location",xd).length > 0){
      lcontent += "<p class='hline'>Is it one of these locations already listed on this site?</p>";
      lcontent += "<ul>";
      $("location",xd).each(function(){
        var location = new locationClassXML($(this));
        lcontent += "<li><h2>"+location.title+" <a href='javascript:void(0)' onclick='editListing("+location.id+")' style='color:#ad0000'>update</a></h2><p>"+location.address+"</p></li>";
      });
      lcontent += "</ul>";
      if(parseInt($("location_settings",xd).attr("total_pages"))>1){
        lcontent += "<div id='new_listing_results_existed_nav' class='results_list_page_nav_class'></div>";
      }
    }

    var rcontent = "";
    var count = 0;
    if($("new_location",xd).length > 0){
      rcontent += "<p class='hline'>If not listed, is it one of these then?</p>";
      rcontent += "<div style='width:400px;height:400px;overflow:auto'><ul>";
      $("new_location",xd).each(function(){
        var location = new locationClassXML($(this));
        rcontent += "<li><h2>"+location.title+" <a href='javascript:void(0)' onclick='selectNewListing("+count+")' style='color:#ad0000'>add</a></h2><p>"+location.address+"</p></li>";
      });
      rcontent += "</ul></div>";
      count++;
    }
    $("#new_listing_results_list").html("<table width='780' cellspacing='4'><tr><td width='60%' valign='top'>"+lcontent+"<div style='clear:both'></div><div style='padding-top:15px;'><p class='hline'>Not here? <a href='javascript:void(0)' onclick='addBlankListing()' style='color:#ad0000'>Click here</a> to add it manually!</p></div></td><td width='40%' valign='top'>"+rcontent+"</td></tr></table>");
    if($("#new_listing_results_existed_nav").length>0){
      $("#new_listing_results_existed_nav").pager({ pagenumber: nl_page, 
                                                    pagecount: parseInt($("location_settings",xd).attr("total_pages")),
                                                    buttonClickCallback: findNewListingPage });
    }
    $("div#new_listing").dialog("close");
    $("div#new_listing_results_list").dialog("open");
  }

  function findNewListingPage(page){
    nl_page = page;
    findNewListing();
  }

  function findNewListingStart(start){
    nl_start = start;
    findNewListing();
  }

  function selectNewListing(pos){
    $("div#edit_listing").dialog("open");
    $("div#edit_listing div.dw_content").hide();
    $("div#edit_listing div.dw_message").html(getLoadingHTML()).show();
    $location = $("new_location",new_listing).eq(pos);
    getPopularTags();
    $("#el_id").val("");
    $("#el_title").val($location.attr("title"));
    $("#el_address").val($location.attr("address"));
    $("#el_website").val($location.attr("website"));
    $("#el_phone").val($location.attr("phone"));
    $("#el_lat").val($location.attr("lat"));
    $("#el_lng").val($location.attr("lng"));
    var zoom_level = 17;
    el_map.clearOverlays();
    var point = new GLatLng(parseFloat($location.attr("lat")), parseFloat($location.attr("lng")));
    el_map.setCenter(point, zoom_level);
    setNewListingPositionMarker(point);
    for(var i=0;i<edit_options.length;i++){
      $("#"+edit_options[i].id).attr('checked',false);
    }
    initListingTags("el_tags_div","el_tags",$location);
    //switchCD("edit_listing");
    initListingTagsBox();
  }

  function addTag(name,title,tag){
    $("#"+name).trigger("addItem",[{"title":title,"value":tag}]);
    checkParentsTag(name,tag);
  }

  function checkParentsTag(name,value){
    if(!value){
      var value = name._value;
      var name = name._container;
    }
    var source_tag = null;
    $(all_tags_data).find("t").each(function(){
      if($(this).attr("tag")==value){
        source_tag = $(this);
      }
    });
    if(source_tag!=null){
      var parent_ids = source_tag.attr("parent_id").split(",");
      for(var i=0;i<parent_ids.length;i++){
        var id = jQuery.trim(parent_ids[i]);
        $(all_tags_data).find("t").each(function(){
          if($(this).attr("id")==id){
            $("#"+name).trigger("addItem",[{"title":$(this).attr("title"),"value":$(this).attr("tag")}]);
          }
        });
      }
    }
  }

  function getPopularTags(){
    $("#offer_services").html("");
    var url = "data.php?operation=get_popular_tags";
    $.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: getPopularTagsOutput
    });
  }

  function getPopularTagsOutput(xd){
    var content = "";
    $("popular_tag",xd).each(function(){
      if(content!=""){
        content+=", ";
      }
      content += "<a href='javascript:void(0)' onclick='addTag(\"el_tags\",\""+$(this).attr("title")+"\",\""+$(this).attr("tag")+"\")'>"+$(this).attr("title")+"</a>";
    });
    $("#offer_services").html(content);
  }

  function addBlankListing(){
    $("div#edit_listing").dialog("open");
    $("div#edit_listing div.dw_content").hide();
    $("div#edit_listing div.dw_message").html(getLoadingHTML()).show();
    getPopularTags();
    $("#el_id").val("");
    $("#el_title").val("");
    $("#el_address").val("");
    $("#el_phone").val("");
    $("#el_lat").val("");
    $("#el_lng").val("");
    var zoom_level = 17;
    el_map.clearOverlays();
    el_map.setCenter(new GLatLng(44.231329, -76.480925), 11);
    for(var i=0;i<edit_options.length;i++){
      $("#"+edit_options[i].id).attr('checked',false);
    }
    initListingTags("el_tags_div","el_tags");
    initListingTagsBox();
  }

  function openMain(){
    document.location = fullpath+"index.html";
  }

  function getLToG(){
    var url = "/data.php?operation=getltog";
    $.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: getLToGOutput
    });
  }

  function getLToGOutput(xd){
    if($("l",xd).length>0){
      getGeoData($("l",xd).attr("id"),$("l",xd).attr("lat")+","+$("l",xd).attr("lng"));
    }
  }

  function getGeoData(id,latlng) {
    if (geocoder) {
      geocoder.getLocations(latlng,
        function(response) {
          var data = "&id="+id+"&status="+response.Status.code;
          if (!response || response.Status.code != 200) {
            console.log("Status Code:" + response.Status.code);
            if(response.Status.code == 620){
              return;
            }
          } else {
            var place = response.Placemark[0];
            var ad = place.AddressDetails.Country;
            var not_full = false;
            try { data += "&lat="+place.Point.coordinates[1]; } catch(e) { not_full = true; }
            try { data += "&lng="+place.Point.coordinates[0]; } catch(e) { not_full = true; }
            try { data += "&street_name="+ad.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName; } catch(e) { not_full = true; }
            try { data += "&city="+ad.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; } catch(e) { not_full = true; }
            try { data += "&state="+ad.AdministrativeArea.AdministrativeAreaName; } catch(e) { not_full = true; }
            try { data += "&zip="+ad.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber; } catch(e) { not_full = true; }
            try { data += "&country="+ad.CountryName; } catch(e) { not_full = true; }
            if(not_full){ data += "&not_full=true"; }
          }
          //console.log(data);
          $.ajax({
            type: "POST",
            url: "/data.php?operation=ulwgv",
            dataType: "xml",
            data: data,
            success: getGeoDataOutput
          });
        }
      );
    }
  }

  function getGeoDataOutput(xd){
    currentGeoRequest++;
    if(currentGeoRequest<maxGeoRequests){
      setTimeout("getLToG()",1000);
    }
  }

