//Written by Nathan Faubion: http://n-son.com
//Use thisor edit how you want, just give me
//some credit!
function jsScrollbar (o, s, a, ev) {
	var self = this;
	this.reset = function () {
		//Arguments that were passed
		this._parent = o;
		this._src    = s;
		this.auto    = a ? a : false;
		this.eventHandler = ev ? ev : function () {};
		//Component Objects
		this._up   = this._findComponent("scrollbar-up", this._parent);
		this._down = this._findComponent("scrollbar-down", this._parent);
		this._yTrack  = this._findComponent("scrollbar-track", this._parent);
		this._yHandle = this._findComponent("scrollbar-handle", this._yTrack);

		//Height and position properties
		this._trackTop = findOffsetTop(this._yTrack);
		this._trackHeight  = this._yTrack.offsetHeight;
		this._handleHeight = this._yHandle.offsetHeight;
		this._x = 0;
		this._y = 0;
		//Misc. variables
		this._scrollDist  = 5;
		this._scrollTimer = null;
		this._selectFunc  = null;
		this._grabPoint   = null;
		this._tempTarget  = null;
		this._tempDistX   = 0;
		this._tempDistY   = 0;
		this._disabled    = false;

		this._ratio = (this._src.totalHeight - this._src.viewableHeight)/(this._trackHeight - this._handleHeight);

		this._yHandle.ondragstart  = function () {return false;};
		this._yHandle.onmousedown = function () {return false;};
		this._addEvent(this._src.content, "mousewheel", this._scrollbarWheel);
		this._removeEvent(this._parent, "mousedown", this._scrollbarClick);
		this._addEvent(this._parent, "mousedown", this._scrollbarClick);

		this._src.reset();

		with (this._yHandle.style) {
			top  = "0px";
			left = "0px";
		}
		this._moveContent();
		if (this._src.totalHeight < this._src.viewableHeight) {
			this._disabled = true;
			this._yHandle.style.visibility = "hidden";
			this._up.style.visibility = "hidden";
			this._down.style.visibility = "hidden";
			this._yTrack.style.visibility = "hidden";
			if (this.auto) this._parent.style.visibility = "hidden";
		} else {
			this._disabled = false;
			this._yHandle.style.visibility = "inherit";
			this._up.style.visibility = "inherit";
			this._down.style.visibility = "inherit";
			this._yTrack.style.visibility = "inherit";
			this._parent.style.visibility  = "inherit";
		}

	};
	this._addEvent = function (o, t, f) {
		if (o.addEventListener) o.addEventListener(t, f, false);
		else if (o.attachEvent) o.attachEvent('on'+ t, f);
		else o['on'+ t] = f;
	};
	this._removeEvent = function (o, t, f) {
		if (o.removeEventListener) o.removeEventListener(t, f, false);
		else if (o.detachEvent) o.detachEvent('on'+ t, f);
		else o['on'+ t] = null;
	};
	this._findComponent = function (c, o) {
		var kids = o.childNodes;
		for (var i = 0; i < kids.length; i++) {
			if (kids[i].className && kids[i].className == c) {
				return kids[i];
			}
		}
	};
	//Thank you, Quirksmode
	function findOffsetTop (o) {
		var t = 0;
		if (o.offsetParent) {
			while (o.offsetParent) {
				t += o.offsetTop;
				o  = o.offsetParent;
			}
		}
		return t;
	};
	this._scrollbarClick = function (e) {
		if (self._disabled) return false;

		e = e ? e : event;
		if (!e.target) e.target = e.srcElement;

		if (e.target.className.indexOf("scrollbar-up") > -1) self._scrollUp(e);
		else if (e.target.className.indexOf("scrollbar-down") > -1) self._scrollDown(e);
		else if (e.target.className.indexOf("scrollbar-track") > -1) self._scrollTrack(e);
		else if (e.target.className.indexOf("scrollbar-handle") > -1) self._scrollHandle(e);

		self._tempTarget = e.target;
		self._selectFunc = document.onselectstart;
		document.onselectstart = function () {return false;};

		self.eventHandler(e.target, "mousedown");
		self._addEvent(document, "mouseup", self._stopScroll, false);

		return false;
	};
	this._scrollbarDrag = function (e) {
		e = e ? e : event;
		var t = parseInt(self._yHandle.style.top);
		var v = e.clientY + document.body.scrollTop - self._trackTop;
		with (self._yHandle.style) {
			if (v >= self._trackHeight - self._handleHeight + self._grabPoint)
				top = self._trackHeight - self._handleHeight +"px";
			else if (v <= self._grabPoint) top = "0px";
			else top = v - self._grabPoint +"px";
			self._y = parseInt(top);
		}

		self._moveContent();
	};
	this._scrollbarWheel = function (e) {
		e = e ? e : event;
		var dir = 0;
		if (e.wheelDelta >= 120) dir = -1;
		if (e.wheelDelta <= -120) dir = 1;

		self.scrollBy(0, dir * 20);
		e.returnValue = false;
	};
	this._startScroll = function (x, y) {
		this._tempDistX = x;
		this._tempDistY = y;
		this._scrollTimer = window.setInterval(function () {
			self.scrollBy(self._tempDistX, self._tempDistY);
		}, 40);
	};
	this._stopScroll = function () {
		self._removeEvent(document, "mousemove", self._scrollbarDrag, false);
		self._removeEvent(document, "mouseup", self._stopScroll, false);

		if (self._selectFunc) document.onselectstart = self._selectFunc;
		else document.onselectstart = function () { return true; };

		if (self._scrollTimer) window.clearInterval(self._scrollTimer);
		self.eventHandler (self._tempTarget, "mouseup");
	};
	this._scrollUp = function (e) {this._startScroll(0, -this._scrollDist);};
	this._scrollDown = function (e) {this._startScroll(0, this._scrollDist);};
	this._scrollTrack = function (e) {
		var curY = e.clientY + document.body.scrollTop;
		this._scroll(0, curY - this._trackTop - this._handleHeight/2);
	};
	this._scrollHandle = function (e) {
		var curY = e.clientY + document.body.scrollTop;
		this._grabPoint = curY - findOffsetTop(this._yHandle);
		this._addEvent(document, "mousemove", this._scrollbarDrag, false);
	};
	this._scroll = function (x, y) {
		if (y > this._trackHeight - this._handleHeight)
			y = this._trackHeight - this._handleHeight;
		if (y < 0) y = 0;

		this._yHandle.style.top = y +"px";
		this._y = y;

		this._moveContent();
	};
	this._moveContent = function () {
		this._src.scrollTo(0, Math.round(this._y * this._ratio));
	};

	this.scrollBy = function (x, y) {
		this._scroll(0, (-this._src._y + y)/this._ratio);
	};
	this.scrollTo = function (x, y) {
		this._scroll(0, y/this._ratio);
	};
	this.swapContent = function (o, w, h) {
		this._removeEvent(this._src.content, "mousewheel", this._scrollbarWheel, false);
		this._src.swapContent(o, w, h);
		this.reset();
	};

	this.reset();
};

function jsScroller (o, w, h) {
	var self = this;
	var list = o.getElementsByTagName("div");
	for (var i = 0; i < list.length; i++) {
		if (list[i].className.indexOf("scroller-container") > -1) {
			o = list[i];
		}
	}

	//Private methods
	this._setPos = function (x, y) {
		if (x < this.viewableWidth - this.totalWidth)
			x = this.viewableWidth - this.totalWidth;
		if (x > 0) x = 0;
		if (y < this.viewableHeight - this.totalHeight)
			y = this.viewableHeight - this.totalHeight;
		if (y > 0) y = 0;
		this._x = x;
		this._y = y;
		with (o.style) {
			left = this._x +"px";
			if(isNaN(this._y)) this._y=0;
			top  = this._y +"px";

		}
	};

	//Public Methods
	this.reset = function () {
		this.content = o;
		this.totalHeight = o.offsetHeight;
		this.totalWidth	 = o.offsetWidth;
		this._x = 0;
		this._y = 0;
		with (o.style) {
			left = "0px";
			top  = "0px";
		}
	};
	this.scrollBy = function (x, y) {
		this._setPos(this._x + x, this._y + y);
	};
	this.scrollTo = function (x, y) {
		this._setPos(-x, -y);
	};
	this.stopScroll = function () {
		if (this.scrollTimer) window.clearInterval(this.scrollTimer);
	};
	this.startScroll = function (x, y) {
		this.stopScroll();
		this.scrollTimer = window.setInterval(
			function(){ self.scrollBy(x, y); }, 40
		);
	};
	this.swapContent = function (c, w, h) {
		o = c;
		var list = o.getElementsByTagName("div");
		for (var i = 0; i < list.length; i++) {
			if (list[i].className.indexOf("scroller-container") > -1) {
				o = list[i];
			}
		}
		if (w) this.viewableWidth  = w;
		if (h) this.viewableHeight = h;
		this.reset();
	};

	//variables
	this.content = o;
	this.viewableWidth  = w;
	this.viewableHeight = h;
	this.totalWidth	 = o.offsetWidth;
	this.totalHeight = o.offsetHeight;
	this.scrollTimer = null;
	this.reset();
};


jQuery.noConflict();

jQuery(document).ready(function(){
    changeSelects();
    });

function optionClickHover()
{

  jQuery('div.optionsDivInvisible > span').mousedown(
      function()
      {

      jQuery(this.parentNode.parentNode.getElementsByTagName('input').item(1)).attr("value",jQuery(this).attr("name")); 
      jQuery(this.parentNode.parentNode.getElementsByTagName('input').item(0)).attr("value",jQuery(this).text()); 
      jQuery(this.parentNode).css("display","none"); 
      });


  jQuery('div.optionsDivInvisible > span').mouseover(
      function()
      {
      this.className="over";
      });

  jQuery('div.optionsDivInvisible > span').mouseout(
      function()
      {
      this.className="";
      });



  jQuery('div.scroller-container > span').click(
      function()
      {
      var optionsDivInVisible = jQuery(this).parents("div.optionsDivInvisible");
      var hiddenInput = optionsDivInVisible.parent().find('input.hidden').eq(0); 
      var valueOption = jQuery(this).attr("name"); 
      var textOption = jQuery(this).text(); 
      var inputInSelect = optionsDivInVisible.parent().find("input").eq(0); 

      inputInSelect.val(textOption); 
      if(hiddenInput) hiddenInput.val(valueOption); 
      optionsDivInVisible.css("display","none"); 
      }
      );



  jQuery('div.scroller-container > span').mouseover(
      function()
      {
      this.className="over";
      });

  jQuery('div.scroller-container > span').mouseout(
      function()
      {
      this.className="";
      });
}


function changeSelects()
{ 
  jQuery("#search select").each(
      function(num)
      {

      var selectOrCombobox = 8; 	
      var kolOptions=jQuery(this).children().length; 

      var className=this.className;
      var selName=this.name;		 
      var selID=this.id;			 



      if(kolOptions>selectOrCombobox)
      {

      jQuery(this).css("display","none"); 



      jQuery(this).before("<div class='selectArea "+className+"' style='z-index:"+(100-num)+"'>"+
        "<div class='left'></div>"+ 
        "<div class='center_a'></div>"+ 
        "<div class='optionsDivInvisible' id='optInvis_"+num+"'>"+ 
        "<div class='scrollbar-container' id='scroll_container_"+num+"'>"+ 
        "<div class='scrollbar-up'></div>"+ 
        "<div class='scrollbar-down' id='scrollbar-down'></div>"+ 
        "<div class='scrollbar-track' id='scrollbar-track'><b class='scrollbar-handle' id='scrollbar-handle'></b></div>"+ 
        "<div class='container2' id='container'>"+ 
        "<div class='scroller-1' id='scroller_"+num+"'>"+
        "<div class='scroller-container' id='"+selID+"_fake'></div>"+
        "</div>"+
        "</div>"+
        "</div>"+
        "</div>"+
        "<input id='v"+selID+"' />"+ 
        "<input type='hidden' name='"+selName+"' id='"+selID+"' />"+ 
        "</div>");



      var containerFofSel=jQuery("#scroller_"+num+" > div");
      var selArr=jQuery(this).children(); 
      var sel_i; 
      for(var i=0;i<kolOptions;i++) 
      {							  

        sel_i = selArr.eq(i);
        containerFofSel.append("<span name='"+sel_i.val()+"'>"+sel_i.text()+"</span>");
      }


      var selected = jQuery(jQuery(this).children(":selected").get(0));
      jQuery("#"+selID).val(selected.val());
      jQuery("#v"+selID).val(selected.text());


      var id_1='scroll_container_'+num;
      var id_2='scroller_'+num;
      scroller = new jsScroller(document.getElementById(id_2), 0, 143);
      scrollbar = new jsScrollbar(document.getElementById(id_1), scroller, false, false);


      jQuery("#optInvis_"+num).css("display","none").css("visibility","visible");

      jQuery(this).remove();
      }


      else 
      {

        jQuery(this).before("<div class='selectArea "+className+"' style='z-index:"+(100-num)+"'>"+
            "<div class='left'></div>"+
            "<div class='center_a'></div>"+
            "<div class='optionsDivInvisible' id='"+selID+"_fake'></div>"+
            "<input type='text' readonly='readonly' name='v"+selName+"' id='v"+selID+"' />"+
            "<input type='hidden' name='"+selName+"' id='"+selID+"' />"+
            "</div>");



        var sel_i; 
        var selArr=jQuery(this).children(); 
        for(var i=0;i<kolOptions;i++)
        {
          sel_i = selArr.eq(i);


          jQuery("#"+selID+"_fake").append("<span name='"+sel_i.val()+"'>"+sel_i.text()+"</span>");
        }


        var selected = jQuery(jQuery(this).children(":selected").get(0));
        jQuery("#"+selID).val(selected.val());
        jQuery("#v"+selID).val(selected.text());
        jQuery("#"+selID+"_fake").css("display","none").css("visibility","visible");


        jQuery(this).remove();
      }

      });


  jQuery('div.center_a').mousedown(
      function()
      {
      var optionsDivInvisible = this.parentNode.getElementsByTagName('div').item(2); 
      if(jQuery(optionsDivInvisible).css("display")=="none") jQuery(optionsDivInvisible).slideDown(200); 
      else jQuery(optionsDivInvisible).slideUp(200); 


      var inp=this.parentNode.getElementsByTagName('input').item(0);
      if(!jQuery(inp).attr("readonly")) 
      {
      jQuery(inp).focus(); jQuery(inp).select(); 

      var id_1=this.parentNode.getElementsByTagName('div').item(3).id;
      var id_2=this.parentNode.getElementsByTagName('div').item(8).id;
      scroller  = new jsScroller(document.getElementById(id_2), 0, 143);
      scrollbar = new jsScrollbar(document.getElementById(id_1), scroller, false, false);
      }
      });


  jQuery('div.selectArea > input').mousedown(
      function()
      {
      if(jQuery(this.parentNode.getElementsByTagName('div').item(2)).css("display")=="none")
      jQuery(this.parentNode.getElementsByTagName('div').item(2)).slideDown(200);
      });


  optionClickHover();



  jQuery('div.selectArea').mouseout(
      function(e)
      {
      var x = 0, y = 0; 
      if (!e) e = window.event;
      if (e.pageX || e.pageY){
      x = e.pageX;
      y = e.pageY;
      } else if (e.clientX || e.clientY){
      x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
      y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
      }
      var obj = this;
      var posx=findPosX(obj);
      var posy=findPosY(obj);
      var length_obj = obj.offsetWidth-2;
      var left=this.getElementsByTagName('div')[0].offsetWidth;
      var h = this.getElementsByTagName('div')[1].offsetHeight;
      var minus;
      if(jQuery.browser.msie) {minus=0;min2=1;left-=1;}
      else {minus=2;min2=1;left-=3;}
      var h1 = this.getElementsByTagName('div')[2].offsetHeight-minus;

      if((x<=posx+left || x>posx+length_obj+min2 || y<posy+2 || y>posy+h+h1) && jQuery(this).children('div.optionsDivInvisible').css("display")=="block")
      {
        jQuery(this).children('div.optionsDivInvisible').slideUp(200);
      }
      });


  jQuery('div.selectArea > input').keyup(
      function()
      {
      var id_1=this.parentNode.getElementsByTagName('div').item(3).id;

      var id_2=this.parentNode.getElementsByTagName('div').item(8).id;

      var col=jQuery("#"+id_2+" > div > span").length; 
      var span=jQuery("#"+id_2+" > div > span"); 
      var val_input=jQuery(this).val().toUpperCase(); 
      for(i=0;i<col;i++)
      {
      var val_list=span.eq(i).text().toUpperCase();

      var pos=val_list.indexOf(val_input);
      if(pos!=0) span.eq(i).css("display","none"); 
      else span.eq(i).css("display","block");
      }

      scroller  = new jsScroller(document.getElementById(id_2), 0, 143);
      scrollbar = new jsScrollbar(document.getElementById(id_1), scroller, false, false);

      });
  function findPosY(obj) {
    var posTop = 0;
    while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
    return posTop;
  }
  function findPosX(obj) {
    var posLeft = 0;
    while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
    return posLeft;
  }

}



/*

CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only thing you need to change in this file is the following
variables: checkboxHeight, radioHeight and selectWidth.

Replace the first two numbers with the height of the checkbox and
radio button. The actual height of both the checkbox and radio
images should be 4 times the height of these two variables. The
selectWidth value should be the width of your select list image.

You may need to adjust your images a bit if there is a slight
vertical movement during the different stages of the button
activation.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "25";
var radioHeight = "13";
var selectWidth = "190";

/* No need to change anything after this */

document.write('<style type="text/css">input.styled { display: none !important; }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				span[a].onmousedown = Custom.pushed;
				span[a].onmouseup = Custom.check;
				document.onmouseup = Custom.clear;
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.choose;
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}
window.onload = Custom.init;


/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * jQueryLastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) jQuery
 * jQueryRev: 4265 jQuery
 *
 * Version: 3.0
 * 
 * Requires: jQuery 1.2.2+
 */

(function(jQuery) {

jQuery.event.special.mousewheel = {
	setup: function() {
		var handler = jQuery.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( jQuery.browser.mozilla )
			jQuery(this).bind('mousemove.mousewheel', function(event) {
				jQuery.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
	
		if ( this.addEventListener )
			this.addEventListener( (jQuery.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		var handler = jQuery.event.special.mousewheel.handler;
		
		jQuery(this).unbind('mousemove.mousewheel');
		
		if ( this.removeEventListener )
			this.removeEventListener( (jQuery.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};
		
		jQuery.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = jQuery.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		jQuery.extend( event, jQuery.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
//		if ( jQuery.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return jQuery.event.handle.apply(this, args);
	}
};

jQuery.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);

/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 86 2009-08-30 21:45:11Z kelvin.luck@gmail.com $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								tabIndex		-	The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *								enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *								animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *								topCapHeight	-	The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *								bottomCapHeight	-	The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			var paneEle = this;
			var currentScrollPosition = 0;
			var paneWidth;
			var paneHeight;
			var trackHeight;
			var trackOffset = settings.topCapHeight;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				paneWidth = $c.innerWidth();
				paneHeight = $c.outerHeight();
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScollCap', $c).remove();
				$this.css({'top':0});
			} else {
				$this.data('originalStyleTag', $this.attr('style'));
				// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
				$this.css('overflow', 'hidden');
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				paneWidth = $this.innerWidth();
				paneHeight = $this.innerHeight();
				var $container = $('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					$container.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				$this.wrap($container);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			trackHeight = paneHeight;
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					),
					$('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowUp', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'top':settings.topCapHeight + 'px'
									}
								)
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowDown', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'bottom':settings.bottomCapHeight + 'px'
									}
								)
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
				}
				
				if (settings.arrowSize) {
					trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
					trackOffset += settings.arrowSize;
				} else if ($upArrow) {
					var topArrowHeight = $upArrow.height();
					settings.arrowSize = topArrowHeight;
					trackHeight = paneHeight - topArrowHeight - $downArrow.height();
					trackOffset += topArrowHeight;
				}
				trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
				$track.css({'height': trackHeight+'px', top:trackOffset+'px'})
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					$container.scrollTop(0);
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						$container.scrollTop(0);
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (location.hash && location.hash.length > 1) {
					setTimeout(function() {scrollTo(location.hash);}, $.browser.safari ? 100 : 0);
				}
				
				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				$(document).bind(
					'click',
					function(e)
					{
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#' && h.length > 1) {
								setTimeout(function() {scrollTo(h, !settings.animateToInternalLinks);}, $.browser.safari ? 100 : 0);
							}
						}
					}
				); 
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				$this[0].scrollTo = $this[0].scrollBy = function() {};
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$this.attr('style', $this.data('originalStyleTag'));
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false,
	topCapHeight: 0,
	bottomCapHeight: 0
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);

var mask = {
  config: {
    container:false,
    text:"please wait just a few seconds...we're finding great dog places for you",
    img:'/images/content/busy-spinner.gif',
    opacity:0.7,
    color:'grey'
  },
  
  id: 'shadow_123',
  rendered: false,
  
  render:function(){
    this.shadowDiv = document.createElement("div");
    this.config.container.insertBefore(this.shadowDiv,this.config.container.firstChild);
    this.shadowDiv.id = this.id;
    this.shadowDiv.style.display = 'none'
    this.shadowDiv.style.position = 'absolute'
    this.shadowDiv.style.zIndex = '1000'
    this.shadowDiv.style.left= '-9px'
    
    this.shadowDiv.style.backgroundColor = this.config.color; 
    this.shadowDiv.align = 'left';
    
    jQuery(this.shadowDiv).css('opacity',0);
    jQuery(this.shadowDiv).height(jQuery(this.config.container).height())
    jQuery(this.shadowDiv).width(jQuery(this.config.container).width())

    this.shadowDiv.innerHTML = "<div align='center' style='color: white; font-size: 1.7em;'><img src='"+this.config.img+"' align='center' style='margin-top:-6px;' /> "+"<br />" + this.config.text+" </div>"
    this.rendered = true;
  },
  show:function(){
    if(!this.rendered || jQuery('#'+this.id).length == 0){
      this.render();
    }
    this.shadowDiv.style.display = 'block'
    var image_container = jQuery(this.shadowDiv).children('div');
    jQuery(this.shadowDiv).height(jQuery(this.config.container).height());
    jQuery(this.shadowDiv).width(jQuery(this.config.container).width());
    image_container.css("margin-top",(jQuery(this.config.container).height()/3-image_container.height()/2)+'px');
    jQuery(this.shadowDiv).fadeTo('fast',this.config.opacity);
  },
  
  hide:function(){
    jQuery(this.shadowDiv).fadeOut('fast');
  }
};

jQuery(document).ready(function() {
  mask.config.container = jQuery('.site')[0];
});

function hidePopup() { 
  jQuery("#blanket").css("display","none");
  jQuery("#popUpDiv").css("display","none");
  jQuery("#popupBackground").css("display","none");
  jQuery("#popupBox").hide(200);
  jQuery('.Homepage').children().show().css("display","block");
  jQuery('.MapHomepage').children().show().css("display","block");
  the_marker = undefined;
};

jQuery.fn.linkToScript = function() {
  jQuery(this).click(function() {
    if (jQuery(this).hasClass('menuItem')) {
      if (jQuery(this).hasClass('current')) {
        if (jQuery(this).hasClass('mainCategory')) {
	  if (jQuery(this).next().css('display') == 'none') {
	    jQuery(this).next().css('display', 'block');
	    return false;
	  } else {
	    jQuery(this).next().css('display', 'none');
	    if (jQuery('.navigation > ul > li > ul > li > a.current').size() == 0) {
	      return false;
	    }
	    jQuery('.navigation > ul > li > ul > li > a.current').removeClass('current');
	  }
        } else {
	  return false;
        }
      } else {
        if (jQuery(this).hasClass('mainCategory')) {
          jQuery('.navigation > ul > li > a.current').next().css('display', 'none');
          jQuery('.navigation > ul > li > ul > li > a.current').removeClass('current');
          jQuery('.navigation > ul > li > a.current').removeClass('current');
          jQuery(this).addClass('current');
          jQuery(this).next().css('display', 'block');
        } else {
          jQuery('.navigation > ul > li > ul > li > a.current').removeClass('current');
          jQuery(this).addClass('current');
        }
      }
    }
    var href = jQuery(this).attr("href");
    mask.show();
    jQuery.getScript(href, function() {
      mask.hide();}
    );
    return false;
  });
};

jQuery.fn.getWithAjax = function() {
  this.live('click', function() { 
      jQuery.get(this.href, null, updatePopupFromResponse, "html");
      return false;
      });
  return this;
};

jQuery.fn.submitWithAjax = function() {
  this.submit(function(event) {
      if( event.isPropagationStopped()) {
        return false;
      }
      $this = jQuery(this);
      $this.attr("disabled", "disabled");
      jQuery.post(this.action, $this.serialize(), updatePopupFromResponse, "html");
      return false;
      });
  return this;
};

jQuery.fn.geocodeAddress = function() {
  var edit = false
  if (arguments.length == 1) { 
    edit = arguments[0];
  }
  var geocoder = new GClientGeocoder(); 
  return this.each(function() {
    var $this = jQuery(this);
    if ($this.val && $this.val() !== '') {
      geocoder.getLocations($this.val(), function(response) {
        if (response.Placemark) {
          if (edit) {
            the_marker = createDraggableMarkerAt(new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]));
          } else {
            the_marker = dropPin(map, response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0], undefined);
          }
          map.addOverlay(the_marker);
          centerMapOnMarker(map, the_marker);
        }
      });
    }
  });
};

jQuery.fn.initializeMap = function () {
  if (GBrowserIsCompatible()) {
    map = new GMap2(this.get(0));
    if (arguments.length == 2) { 
      map.setCenter(new GLatLng(arguments[0], arguments[1]), 11);
    } else {
      var glc = google.loader.ClientLocation;
      if(glc) {
        map.setCenter(new GLatLng(glc.latitude, glc.longitude), 11);
      } else  {
        map.setCenter(new GLatLng(40.6548, -95.3263), 3);
      }
    }
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
  }
  return this;
};

jQuery.fn.locationEdit = function () {
  var click_listener = GEvent.addListener(map,"click", function(overlay, latlng) {
      if (typeof(the_marker) ==='undefined') {
        if (latlng) {
        var geoCoder = new GClientGeocoder();
        geoCoder.getLocations(latlng, function(response) {
          if (!response || response.Status.code != 200) {
          alert("unable to drop pin there:" + response.Status.code);
          } else {
          the_marker = createDraggableMarkerAt(latlng);
          map.addOverlay(the_marker);
          centerMapOnMarker(map, the_marker);
          place = response.Placemark[0];
          jQuery('.address').val(place.address);
          GEvent.removeListener(click_listener);
          }
          });
        }
       }
      });

  return this;
};


/*add location feature start*/
jQuery.fn.categorySelect = function () {
 jQuery(".addLocationClassificationItem").click (
      function(){
        if(jQuery(this).next().attr("name")=="picked"){
          jQuery(this).parent().addClass("addLocationClassificationItemPicked");           
        } else {
          jQuery(".addLocationClassificationItem").next().hide(200);
          jQuery(".addLocationClassificationItem").parent().removeClass("addLocationClassificationItemPicked");
          jQuery(".addLocationClassificationItem input").attr("checked","");
          
          jQuery(".addLocationClassificationItem").next().attr("name","notpicked");
          jQuery(this).next().attr("name","picked");
          jQuery(this).next().show(200);
          jQuery(this).parent().addClass("addLocationClassificationItemPicked"); 
        }
	if (jQuery(this).parent().attr("has_schedule")=="true") {
		jQuery("#event_shedule").css("display", "block");
	} else {
		jQuery("#event_shedule").css("display", "none");
	}
        jQuery(this).find("input").attr("checked","checked");
        jQuery(".addLocationClassificationItem").next().find("span").removeClass("radioChecked");
        return true;
      });
    
}
/*add location feature start*/

var toggleChecked = function(event) {
  jQuery(".mapLegendList > li").addClass("notPicked");
  var li = jQuery(event.currentTarget);
  var input = jQuery('input', li);
  var selectedCategoryLabel = jQuery('#categories_editor p');
  if(li.hasClass("notPicked")){
    li.removeClass("notPicked");           
    input.attr("checked", "checked");
    selectedCategoryLabel.replaceWith("<p class='selected_category'>" + jQuery('#categories_editor .mapLegend h4').text() + "<br />" + jQuery('a',li).text() + "</p>");
  } else {
    input.attr("checked", "");
    selectedCategoryLabel.replaceWith("<p class='selected_category'></p>");
  }
  return false;
};

var showSubCategories = function(event) {
  var $this = jQuery(event.currentTarget);
  var legend = $this.parents('.mapLegend');
  if (legend.css("height") == "76px") {
    legend.css({height: "236px"});
  } else {
    legend.css({height: "76px"});
  }
  return false;
};

var loggedIn = function() {
  var logoutButton = jQuery("<a href='/logout'></a>").append("Logout").addClass("headerButton").addClass("logoutButton");
  jQuery(".loginButton").replaceWith(logoutButton);
  var myAccountButton = jQuery("<a href='/customers/0/settings'></a>").append("My Account").addClass("headerButton").addClass("myaccountButton");
  jQuery(".signupButton").replaceWith(myAccountButton);
  jQuery(".myaccountButton").getWithAjax();
};

var hideLocationResultsInCategory = function(category) {
  jQuery("#locationResults li."+category).hide();
  var markers = eval(category+"Markers");
  if (markers) {
    for (var i in markers) {
      if (typeof markers[i] !== "function") {
        var marker = markers[i];
        markerMgr.removeMarker(marker);
      }
    }
    markerMgr.refresh();
  }
};

var showLocationResultsInCategory = function(category) {
  jQuery("#locationResults li."+category).show();
  var markers = eval("setup"+category+"Markers()");
  if (markers) {
    markerMgr.addMarkers(markers);
    markerMgr.refresh();
  }

};


jQuery.activateLegendItems = function () {
  jQuery(".MapHomepage .mapLegendList").children().click ( function (){
      li = jQuery(this);
      if(li.hasClass("notPicked")){
      showLocationResultsInCategory(jQuery('a',li).attr("class"));
      li.removeClass("notPicked");           
      } else {
      hideLocationResultsInCategory(jQuery('a',li).attr("class"));
      li.addClass("notPicked");           
      }
      return false;
      });
}


jQuery.updateLegend = function(legend, data, options) {
  jQuery("a.previous", legend).attr("href", "/categories/"+data.category.id+"/previous");
  jQuery("h4 img", legend).attr("src", "/images/icons/"+data.category.css_name+"_top.png");
  jQuery("h4 .category_name", legend).text(data.category.name);
  mapLegendList = jQuery("<ul class='mapLegendList'></ul>");
  for (var child in data.category.children) {
    if (data.category.children[child].css_name !== undefined) { 
      var subcategory = data.category.children[child];
      mapLegendList.append(jQuery("<li><a href='#' class='"+subcategory.css_name+"'>"+subcategory.name+"</a><input type='radio' value='"+subcategory.id+"' name='location[category_ids][]' id='location_category_ids_"+subcategory.id+"'></li>"));
    }
  }
  jQuery("ul.mapLegendList", legend).replaceWith(mapLegendList);
  jQuery("a.next", legend).attr("href", "/categories/"+data.category.id+"/next");
};

var updateCategoryEditor = function(data, textStatus) { 
  jQuery.updateLegend(jQuery("#categories_editor .mapLegend"), data);
  jQuery("#categories_editor .mapLegendList > li").click(function(event) { toggleChecked(event); showSubCategories(event); return false; });
  jQuery("#categories_editor .mapLegend h4 input").attr("checked", "checked").attr("id", "location_category_ids_"+data.category.id).attr("value", data.category.id);
  jQuery("#categories_editor .selected_category").text(data.category.name);
};

jQuery.fn.activateBehaviors = function() {
  return this.each(function() {
    var $this = jQuery(this);
     $this.hover (function(){
      jQuery(this).css("background","#eaeaea");           
      return true;
      });
    $this.mouseout (function(){
      jQuery(this).css("background","#fff");           
      return true;
      });
    $this.click ( function(){
      var review = jQuery(".longReview").hide();
      review.empty().append(jQuery(this).next().children().clone()).show(200);
      jQuery(this).siblings().removeClass("pickedItem");
      jQuery(this).addClass("pickedItem");
      return true;
      });
    });
};

jQuery.activateReviewComments = function() {
  jQuery("#ReviewComments > dt").activateBehaviors();
};

var sendAlertSuccessCss = {
   enableActions: function(dataContext) {
       dataContext.filter('#redCloseButton').click(hidePopup).end();
   }
};

var myAccountCss = { 
popupBox: { top: "200px",
            left: "50%",
            marginLeft: " -312px",
            width: "595px",
            height: "auto",
            background: "url(/images/content/popup-createallert-back.png) repeat-y",
            padding: "0 0 0 30px"},
          data: {
topBorder: { selector: "topBorder", css: { top: "-20px",
             left: "0",
             width: "625px",
             height: "20px",
             background: " url(/images/content/popup-createallert-top.png) no-repeat" } },
           botBorder: { selector: "botBorder", css: { bottom: "-20px",
             left: "0",
             width: "625px",
             height: "20px",
             background: " url(/images/content/popup-createallert-bot.png) no-repeat" } },
           h2: { selector: "h2", css: { position: "relative",
             top: "-8px",
             left: "-18px",
             width: "601px",
             height: "32px",
             background: " url(/images/content/popup-myaccount.png) no-repeat",
             textIndent: "-5000px" } }
          },
enableActions: function(dataContext) {
                 dataContext.filter('#popupEditDogCloseButton').click(hidePopup).end();
                 jQuery("#popupEditDogCloseButton", dataContext).click(hidePopup);
                 jQuery(".popupMuProfileProfile a", dataContext).getWithAjax();
                 jQuery(".popupMuProfileChangePass a", dataContext).getWithAjax();
                 jQuery(".popupMuProfileDogs a", dataContext).getWithAjax();
                 jQuery('a.editDog', dataContext).getWithAjax();
                 jQuery('a.contentLostDogAllertBoxPhotoHelpLink', dataContext).getWithAjax();
                 jQuery(".checkBoxContainer div", dataContext).mousedown( function() {
                     changeCheck(jQuery(this));
                     }).each( function() {
                       changeCheckStart(jQuery(this));
                       }).end();
                 jQuery('.address', dataContext).awesomecompleteAddress();
                 jQuery('dt', dataContext).activateBehaviors();
                 jQuery(".checkBoxContainer#twitter_yes div", dataContext).mousedown( function() {
                     jQuery('#twitter_fields').toggle();
                     });
                 jQuery('a.addEmailAddress', dataContext).click(function() {
                     var emailDiv = jQuery('div#emailAddress');
                     var newDiv = emailDiv.clone().attr('id', '');
                     emailDiv.after(newDiv);
                     });
               } 
};


var lostDogCss = { 
popupBox: { top: "100px",
            left: "50%",
            marginLeft: " -312px",
            width: "605px",
            height: "auto",
            paddingLeft: "20px",
            background: " url(/images/content/popup-createallert-back.png) repeat-y"},
            
          data: {
topBorder: { selector: "topBorder", css: { top: "-20px",
             left: "0",
             width: "625px",
             height: "20px",
             background: " url(/images/content/popup-createallert-top.png) no-repeat" } },
           botBorder: { selector: "botBorder", css: { bottom: "-20px",
             left: "0",
             width: "625px",
             height: "20px",
             background: " url(/images/content/popup-createallert-bot.png) no-repeat" } },
           h2: { selector: "h2", css: { position: 'absolute',
             'top': "-5px",
             left: "12px",
             width: "601px",
             height: "32px",
             background: " url(/images/content/popup-lost-dog-wide.png) no-repeat",
             textIndent: "-5000px" } }
          },
enableActions: function(dataContext) {
                 dataContext.filter('#redCloseButton').click(hidePopup).end();
                 jQuery("#redCloseButton", dataContext).click(hidePopup);
                 jQuery(".popupEditDogInfoSubmitActions a", dataContext).click(hidePopup);
                 jQuery("#current_customer_address", dataContext).awesomecompleteAddress(); 
               }
};
var dogsCss = { 
popupBox: { top: "100px",
            left: "50%",
            marginLeft: " -312px",
            width: "595px",
            height: "auto",
            background: " url(/images/content/popup-createallert-back.png) repeat-y",
            padding: "0 0 0 30px" },
          data: {
topBorder: { selector: "topBorder", css: { top: "-20px",
             left: "0",
             width: "625px",
             height: "20px",
             background: " url(/images/content/popup-createallert-top.png) no-repeat" } },
           botBorder: { selector: "botBorder", css: { bottom: "-20px",
             left: "0",
             width: "625px",
             height: "20px",
             background: " url(/images/content/popup-createallert-bot.png) no-repeat" } },
           h2: { selector: "h2", css: { position: 'absolute',
             'top': "-5px",
             left: "12px",
             width: "601px",
             height: "32px",
             background: " url(/images/content/popup-editdog-title.png) no-repeat",
             textIndent: "-5000px" } }
          },
enableActions: function(dataContext) {
                 dataContext.filter('#popupEditDogCloseButton').click(hidePopup).end();
                 jQuery("#popupEditDogCloseButton", dataContext).click(hidePopup);
                 jQuery(".popupEditDogInfoSubmitActions a", dataContext).click(hidePopup);
               }
};

var addLocationCss = { 
enableActions: function(dataContext) {
                  jQuery(".checkBoxContainer div", dataContext).mousedown( function() {
                     changeCheck(jQuery(this));
                     }).each( function() {
                       changeCheckStart(jQuery(this));
                       }).end();
                 dataContext.filter('#popupEditDogCloseButton').click(hidePopup).end();
                 jQuery('.address', dataContext).awesomecompleteAddress();
                 jQuery('#categories_editor .mapLegend h4 img', dataContext).click(showSubCategories);
                 jQuery("#categories_editor .mapLegendList > li", dataContext).click(function(event) { toggleChecked(event); showSubCategories(event); return false; });
                 jQuery("#categories_editor .mapLegend a.previous", dataContext).click(function() {
                     var href = jQuery(this).attr("href");
                     jQuery.get(href, null, updateCategoryEditor, "json");
                     return false;
                     });
                 jQuery("#categories_editor .mapLegend a.next", dataContext).click(function() {
                     var href = jQuery(this).attr("href");
                     jQuery.get(href, null, updateCategoryEditor, "json");
                     return false;
                     });
                 jQuery('.popupEdit',dataContext).click(function() {
                     var href = jQuery(this).attr("href");
                     jQuery.get(href, jQuery('form#new_location').serialize(), updatePopupFromResponse, "html");
                     return false;
                     });
                 jQuery('input#location_address', dataContext).geocodeAddress(true);
               },
map: "edit"
};

var foundLostDogCss = {
popupBox: { top: "100px",
            left: "50%",
            marginLeft: " -312px",
            width: "593px",
            height: "700px",
            background: " url(/images/content/popup-createallert-back.png) repeat-y",
            padding: "0 0 0 30px"
          },
data: { 
topBorder:{ selector: ".topBorder", css: { top: "-20px",
            left: "0",
            width: "625px",
            height: "20px",
            background: " url(/images/content/popup-createallert-top.png) no-repeat" } }, 
          botBorder: { selector: ".botBorder", css: { bottom: "-20px",
            left: "0",
            width: "625px",
            height: "20px",
            background: " url(/images/content/popup-createallert-bot.png) no-repeat" } },
          h2: { selector: "h2", css: { top: "-7px",
            left: "-18px",
            width: "601px",
            height: "32px",
            background: " url(/images/content/popup-createallert-title.png) no-repeat",
            position: "relative",
            textIndent: "-5000px" } },
          h3: { selector: "h3.subtitle", css: { background: " url(/images/content/dogs.png) no-repeat",
            padding: " 33px 40px 15px 133px",
            fontSize: "20px",
            color: "#B0B0B0" } }, 
          h4: { selector: "h4", css: { padding: " 10px 40px 0 0", fontSize: "17px", color: "#666666" } },
          p: { selector: "p", css: { padding: " 10px 40px 20px 0", fontSize: "12px", color: "#666666", width: "548px" } },
          form: { selector: "form", css: { padding: " 10px 40px 30px 0", color: "#666666" } },
          formLabel: { selector: "form label", css: { fontStyle: "normal", fontWeight: "bold", fontSize: "13px" } },
          formTextInputs: { selector: "form input[type=text]", css:  { display: "block",
            fontWeight: "bold",
            color: "#000",
            fontSize: "14px",
            border: " none",
            background: "transparent",
            width: "331px" } },
          formSubmit: { selector: "form input[type=submit]", css: { display: "block",
            cursor: "pointer",
            width: "92px",
            height: "24px",
            margin: "18px 0 18px 0",
            "float": "right" } },
          formSendAlert: { selector: "form#send_alert_form input[type=submit]", css: { background: "url(/images/buttons/sendAlertBtn.gif) no-repeat",
            margin:"12px 0 18px 0", "float": "none" } },
          formDiv: { selector: "form div", css: { paddingTop: " 4px" } },
          pItalic: { selector: ".popupCreateAllertPitalic", css: { fontStyle: "italic" } },
          tips: {selector: ".tips", css: { display: "none" } },
          foundLostDog: { selector: "a.foundLostDog", css: { fontSize: "20px" } },
          results: { selector: ".results", css: { overflow: "auto", height: "500px", width: "582px" } },
          dog: { selector: ".dog", css: { width: "330px", margin: "0 auto 10px auto" } }
      },
enableActions: function (dataContext) {
                 dataContext.filter("#popupEditDogCloseButton").click(hidePopup).end();
                 jQuery("#popupEditDogCloseButton", dataContext).click(hidePopup);
                 jQuery('a.foundLostDog', dataContext).getWithAjax();
                 jQuery('a.alert_community', dataContext).getWithAjax();
                 jQuery('.address', dataContext).awesomecompleteAddress();
                 jQuery('form', dataContext).submit(function(event) {
                     $this = jQuery(this);
                     if ($this.children('#dog_breed_id').val() == ''
                         || $this.children('#dog_color_id').val() == '' ) {
                       jQuery("p.error").remove();
                       jQuery(this).before("<p class='error' style='font-weight: bold;'>Please enter at least breed, color and gender</p>");
                       return false;
                     }
                     return true;
                 });
               }
};

var loginCss = { 
popupBox:  { top: "200px",
             left: "50%",
             marginLeft: " -204px",
             width: "398px",
             height: "268px",
             background: "url(/images/content/popup-login-back.png) repeat-y",
             textAlign: "left",
             padding: "0 0 0 10px" },
           data: {
topBorder: { selector: ".topBorder", css: { top: "-18px",
             left: "0",
             width: "408px",
             height: "18px",
             background: "url(/images/content/popup-login-top.png) no-repeat" } },
           botBorder: { selector: ".botBorder", css: { bottom: "-20px",
             left: "0",
             width: "408px",
             height: "20px",
             background: "url(/images/content/popup-login-bot.png) no-repeat" } },
           h1: { selector: "h1", css: { top: "-7px",
             width: "387px",
             height: "32px",
             background: "url(/images/content/popup-login-title.png) no-repeat" } },
           form: { selector: "form", css: { padding: "10px 0 0 10px", 'float': "left"} },
           formTextField: { selector: "input[type='text'], input[type='password']", css: { 'float': "left",
             fontWeight: "bold",
             color: "#000",
             fontSize: "17px",
             padding: "3px 10px ",
             border: "none",
             background: "#f2f2f2",
             width: "347px",
             height: "23px",
             margin: "4px 0 10px 0" } },
           forgotPassword: { selector: ".forgotPassword", css: { 'float': "left",
             color: "#0099ff",
             fontSize: "10px",
             fontWeight: "bold",
             textDecoration: "none",
             marginBottom: "21px",
             marginTop: "-6px" } },
           loginButton: { selector: "input[type='submit']", css: { position: "absolute",
             bottom: "7px",
             right: "21px",
             border: " none",
             background: " url(/images/content/login-button.png) no-repeat",
             width: "72px",
             height: "19px",
             cursor: "pointer" } },
           formLabel: { selector: "label", css: { 'float': "left",
             fontWeight: "bold",
             fontSize: "14px",
             color: "#666666",
             marginLeft: "3px" } },
           checkboxContainer: { selector: ".checkBoxContainer2", css: { 'float': "left", width: "350px" } },
           cbc2Div: { selector: ".checkBoxContainer2 div", css: { 'float': "left",
             cursor: "pointer",
             background: " url(/images/content/nice-check.png) no-repeat",
             width: "17px",
             margin: "3px 5px 0 0",
             height: "17px" } },
           cbc2Input: { selector: ".checkBoxContainer2 div input", css: { display: "none" } },
           cbc2Span: { selector: ".checkBoxContainer2 span", css: { 'float': "left",
             fontWeight: "bold",
             fontSize: "14px",
             color: "#666666",
             cursor: "default",
             margin: " 4px 0 0 2px" } },
           loginSuccess: { selector: "#login_success", css: { textAlign:"center",
             width:"386px",
             paddingTop: "57px",
             color:"#666666"} } 
           },
enableActions: function (dataContext) {
                 jQuery(".checkBoxContainer2 div", dataContext).mousedown( function() {
                     changeCheck(jQuery(this));
                     });
                 jQuery(".checkBoxContainer2 div", dataContext).each( function() {
                     changeCheckStart(jQuery(this));
                     });
                 dataContext.filter('#closeButton').click(hidePopup).end();
                 jQuery("#closeButton", dataContext).click(hidePopup);
               }
};
var forgotPasswordCss = { 
popupBox:  { top: "200px",
             left: "50%",
             marginLeft: " -204px",
             width: "398px",
             height: "268px",
             background: "url(/images/content/popup-login-back.png) repeat-y",
             textAlign: "left",
             padding: "0 0 0 10px" },
           data: {
topBorder: { selector: ".topBorder", css: { top: "-18px",
             left: "0",
             width: "408px",
             height: "18px",
             background: "url(/images/content/popup-login-top.png) no-repeat" } },
           botBorder: { selector: ".botBorder", css: { bottom: "-20px",
             left: "0",
             width: "408px",
             height: "20px",
             background: "url(/images/content/popup-login-bot.png) no-repeat" } },
           h1: { selector: "h1", css: { top: "-7px",
             width: "387px",
             height: "32px",
             background: "url(/images/content/popup-forgot-password-title.png) no-repeat" } },
           form: { selector: "form", css: { padding: "10px 0 0 10px", 'float': "left"} },
           formTextField: { selector: "input[type='text'], input[type='password']", css: { 'float': "left",
             fontWeight: "bold",
             color: "#000",
             fontSize: "17px",
             padding: "3px 10px ",
             border: "none",
             background: "#f2f2f2",
             width: "347px",
             height: "23px",
             margin: "4px 0 10px 0" } },
           forgotPassword: { selector: ".forgotPassword", css: { 'float': "left",
             color: "#0099ff",
             fontSize: "10px",
             fontWeight: "bold",
             textDecoration: "none",
             marginBottom: "21px",
             marginTop: "-6px" } },
           loginButton: { selector: "input[type='submit']", css: { position: "absolute",
             bottom: "7px",
             right: "21px",
             border: " none",
             background: " url(/images/content/submit-button.png) no-repeat",
             width: "72px",
             height: "19px",
             cursor: "pointer" } },
           formLabel: { selector: "label", css: { 'float': "left",
             fontWeight: "bold",
             fontSize: "14px",
             color: "#666666",
             marginLeft: "3px" } },
           checkboxContainer: { selector: ".checkBoxContainer2", css: { 'float': "left", width: "350px" } },
           cbc2Div: { selector: ".checkBoxContainer2 div", css: { 'float': "left",
             cursor: "pointer",
             background: " url(/images/content/nice-check.png) no-repeat",
             width: "17px",
             margin: "3px 5px 0 0",
             height: "17px" } },
           cbc2Input: { selector: ".checkBoxContainer2 div input", css: { display: "none" } },
           cbc2Span: { selector: ".checkBoxContainer2 span", css: { 'float': "left",
             fontWeight: "bold",
             fontSize: "14px",
             color: "#666666",
             cursor: "default",
             margin: " 4px 0 0 2px" } },
           loginSuccess: { selector: "#login_success", css: { textAlign:"center",
             width:"386px",
             paddingTop: "57px",
             color:"#666666"} } 
           },
enableActions: function (dataContext) {
                 jQuery(".checkBoxContainer2 div", dataContext).mousedown( function() {
                     changeCheck(jQuery(this));
                     });
                 jQuery(".checkBoxContainer2 div", dataContext).each( function() {
                     changeCheckStart(jQuery(this));
                     });
                 dataContext.filter('#closeButton').click(hidePopup).end();
                 jQuery("#closeButton", dataContext).click(hidePopup);
               }
};


var signUpCss = {
popupBox: { top: "200px",
            left: "50%",
            marginLeft: " -203px",
            width: "394px",
            minHeight: "449px",
            background: " url(/images/content/popup-joinus-back.png) repeat-y",
            padding: "0 0 0 11px"},
          data: { topBorder: { selector:".topBorder", css: { top: "-21px",
            left: "0",
            width: "405px",
            height: "21px",
            background: " url(/images/content/popup-joinus-top.png) no-repeat"} },
          botBorder: { selector: ".botBorder", css: { bottom: "-19px",
            left: "0",
            width: "405px",
            height: "19px",
            background: " url(/images/content/popup-joinus-bot.png) no-repeat"} },
          h2: { selector: "h2", css: { position: "relative",
            top: "-10px",
            width: "383px",
            height: "33px",
            background: "url(/images/content/popup-joinus-title.png) no-repeat",
            textIndent: "-5000px" } },
          reqFields: { selector: "span.reqFields", css: { "float": "right",
            marginRight: " 27px",
            fontWeight: "bold",
            fontSize: "14px",
            color: "#666666",
            padding: "1px 10px 0 0",
            background: " url(/images/content/popup-joinus-redstar.png) top right no-repeat" } },
          newCustomerForm: { selector: "form#new_customer", css: { padding: "24px 0 0 16px", "float": "left" } },
          newCustomerLabels: { selector: "label", css: { "float": "left",
            fontWeight: "bold",
            fontSize: "14px",
            color: "#666666",
            padding: "1px 10px 0 0",
            background: " url(/images/content/popup-joinus-redstar.png) top right no-repeat" } },
          newCustomerLabelSpan: { selector: "label span", css: { fontWeight: "normal",
            fontSize: "12px",
            color: "#0099ff" } },
          newCustomerTextField: { selector: "input[type=text], input[type=password]", css: { "float": "left",
            fontWeight: "bold",
            color: "#000",
            fontSize: "17px",
            padding: "3px 10px ",
            border: " none",
            background: "#f2f2f2",
            width: "331px",
            height: "23px",
            margin: "4px 0 10px 0" } },
          checkBox: { selector: ".checkBoxContainer", css: { "float": "left",
            padding: "5px 0 3px 0",
            width: "350px" } },
          checkBoxDiv: { selector: ".checkBoxContainer div", css: { "float": "left",
            cursor: "pointer",
            background: " url(/images/content/nice-check.png) no-repeat",
            width: "17px",
            height: "17px",
            marginLeft: "36px" } },
          checkBoxInput: { selector: ".checkBoxContainer div input", css: { display: "none" } },
          checkBoxSpan: { selector: ".checkBoxContainer span", css: { "float": "left",
            fontWeight: "bold",
            fontSize: "14px",
            color: "#666666",
            padding: "1px 10px 0 0",
            background: " url(/images/content/popup-joinus-redstar.png) top right no-repeat",
            cursor: "default",
            margin: " -1px 0 0 5px" } },
          newCustomerButton: { selector: "input[type=submit]", css: { "float": "left",
            border: " none",
            background: "url(/images/content/submit-button.png) no-repeat",
            width: "73px",
            height: "19px",
            cursor: "pointer",
            margin: "19px 9px 0 4px" } },
          newCustomerCancel: { selector: ".cancelContainer", css: { "float": "left",
            fontSize: " 14px",
            color: "#666666",
            marginTop: "20px" } },
          newCustomerCancelB: { selector: ".cancelContainer b", css: { cursor: "pointer",
            color: "#f99400" } }
          },
enableActions: function(dataContext) {
                 dataContext.filter("#closeButton").click(hidePopup).end();
                 jQuery(".checkBoxContainer div", dataContext).mousedown( function() {
                     changeCheck(jQuery(this));
                     }).each( function() {
                       changeCheckStart(jQuery(this));
                       }).end();
                 jQuery(".cancelContainer b", dataContext).click(hidePopup);
               }
};

var reviewLocationCss = {
enableActions: function(dataContext) {
                  jQuery(".checkBoxContainer div", dataContext).mousedown( function() {
                     changeCheck(jQuery(this));
                     }).each( function() {
                       changeCheckStart(jQuery(this));
                       }).end();
                 dataContext.filter("#popupEditDogCloseButton").click(hidePopup).end();
                 jQuery(".cancelContainer b", dataContext).click(hidePopup);
                 jQuery('.popupEdit',dataContext).click(function() {
                     var href = jQuery(this).attr("href");
                     jQuery.get(href, jQuery('form#new_location').serialize(), updatePopupFromResponse, "html");
                     return false;
                     });
                 jQuery('input#location_address', dataContext).geocodeAddress();
                 jQuery('.rateMe .rating', dataContext).mouseenter(function() {var rating = getRating(this);fillRating(this, rating);}).mouseleave(resetRating);
               },
map: "show"
};

var displayPopup = function(data, popupCss) {
  jQuery("#blanket").css("display","none");
  jQuery("#popUpDiv").css("display","none");  
  jQuery(".niceRadio", data).each( function() {
      changeRadioStart(jQuery(this));
      });

  if (popupCss.enableActions)  {
    popupCss.enableActions(data);
  }
  var popup = jQuery("<div></div>").addClass("popupContent").append(data);
  jQuery(".popupContent").replaceWith(popup);
  jQuery("#popupBackground").css({display: "block"});
  jQuery("#loading").remove();
  jQuery("#popupBox").show(200);
  popupCenter();
  jQuery("form").filter("form:not(#search)").submitWithAjax();
  jQuery("form input[type=file]").change(function() {
      jQuery(this).parents("form").unbind("submit");
      jQuery(this).parents("form").submit(function() { 
        jQuery(this).hide();
        jQuery('#uploading').show();

        // IE7 will stop loading/doing any animations once a form is submitted. 
        // The trick is to reset the image source after it's submitted.
        if (document.images['uploading_gif']) {
         setTimeout("document.images['uploading_gif'].src=document.images['uploading_gif'].src",10);
        }

        return true;
        });
      });

  if (popupCss.map == "edit") {
    jQuery("#new_map").initializeMap().locationEdit(); 
    jQuery("#new_map").categorySelect();
  } else if (popupCss.map == "show") {
    if (map) {
      map.returnToSavedPosition();
    }
    jQuery("#new_map").initializeMap();
  }
  
  datePickerController.cleanUp();
  datePickerController.create(jQuery('input#location_event_start').get(0));
  datePickerController.create(jQuery('input#location_event_end').get(0));
};


var updatePopupFromResponse = function (data, textStatus) {
  var $data = jQuery(data);
  jQuery('#popupBox').removeClass().removeAttr("style");
  jQuery('.Homepage').css('height', '400px').children().hide();
  jQuery('.MapHomepage').children().hide();
  if ($data.is("#search_dogs") || $data.is("#notification_area") ) {
    popupCss = foundLostDogCss;
  } else if ($data.is('#dogs_form')) {
    popupCss = dogsCss;
    jQuery('#popupBox').addClass('popupDogForm');
  } else if ($data.is('#login_success')) {
    popupCss = loginCss;
    loggedIn();
    jQuery('#popupBox').addClass('popupMuLogin');
  } else if ($data.is('#customer_forgot_password')) {
    popupCss = forgotPasswordCss;
    jQuery('#popupBox').addClass('popupMuLogin');
  } else if ($data.is('#login_form')) {
    popupCss = loginCss;
    jQuery('#popupBox').addClass('popupMuLogin');
  } else if ($data.is('#lost_dog_create_alert')) {
    popupCss = lostDogCss;
  } else if ($data.is('.popupLostDogSucsessPhotoContainer')) {
    jQuery('#popupBox').addClass('lostDogAlertSuccess');
    displayPopup($data, sendAlertSuccessCss);
    return; 
  } else if ($data.is('.popupLostDogSucsessFoundPhotoContainer')) {
    jQuery('#popupBox').addClass('lostDogAlertSuccessFound');
    displayPopup($data, sendAlertSuccessCss);
    return; 
  } else if ($data.is('#new_customer') || $data.is('#sent_activation')) {
    jQuery('#popupBox').addClass('popupJoinUs');
    displayPopup($data, signUpCss);
    return;
  } else if ($data.is('#popup_new_location')) {
    jQuery('#popupBox').addClass('popupAddLocation');
    loggedIn();
    displayPopup($data, addLocationCss);
    return;
  } else if ($data.is('#new_location')) {
    jQuery('#popupBox').addClass('popupAddLocation');
    displayPopup($data, reviewLocationCss);
    return;
  } else if ($data.is(".thank_you")) {
    jQuery('#popupBox').addClass('popupCreateAllert').css('min-height', '100px')
    displayPopup($data, foundLostDogCss);
    return;
  } else if ($data.is("#lost_pet") || $data.is("#found_dog_alert_community")){ 
    jQuery('#popupBox').addClass('popupCreateAllert');
    displayPopup($data, foundLostDogCss);
    return;
  } else if ($data.is('#settings') || $data.is('#myDogs')) { 
    jQuery('#popupBox').addClass('popupMuProfile');
    displayPopup($data, myAccountCss);
    return;
  } else if ($data.is("#contact_form") || $data.is("#thankyou"))  {
    jQuery('#popupBox').addClass('popupJoinUsGreen');
    displayPopup($data, myAccountCss);
    return;
  } else if ($data.is("#new_post"))  {
    jQuery('#popupBox').addClass('popupPosts');
    displayPopup($data, myAccountCss);
    return;
  } else if ($data.is("#new_picture") || $data.is("#send_to_friend_form"))  {
    jQuery('#popupBox').addClass('uploadPhotoPopup').addClass('popupEditDogInfo');
    jQuery('.popupEditDogInfoSubmitActions a', $data).click(hidePopup);
    displayPopup($data, myAccountCss);
    return;
  } else if ($data.is(".edit_customer"))  {
    jQuery('#popupBox').addClass('popupMyProfileAcc');
    displayPopup($data, myAccountCss);
    return;
  } else if ($data.is("#reviews"))  {
    jQuery('#popupBox').addClass('popupMorePosts');
    displayPopup($data, myAccountCss);
    return;
  } else if ($data.is('#redirect_to')) {
    if ($data.is('.closePopup')) {
      hidePopup();
      window.location = $data.filter('a').attr('href');
    } else {
      jQuery.get($data.filter('a').attr('href'), null, updatePopupFromResponse, "html");
      // remove loggedin() for all popups and leave only where it should be, for now it's login_success and add_location
      // for prevent showing My Account and Logout buttons when user failed to login
      //loggedIn();
    }
    return;
  } else {
    popupCss = dogsCss;
  }


  var cssData = popupCss.data; 
  for (var rule in cssData) {
    if (cssData[rule].selector) {
      jQuery(cssData[rule].selector, $data).css(cssData[rule].css);
      $data.filter(cssData[rule].selector).css(cssData[rule].css).end();
    }
  }
  jQuery("#popupBox").css(popupCss.popupBox).hide(200);

  displayPopup($data, popupCss);
};

jQuery(document).ready(function(){

    jQuery("#search_params_target").focus(function(){
      if(jQuery(this).val()=='Enter City, State, or Zip Code'){
      jQuery(this).val('');
      }
      return true;
      });
    jQuery("#search_params_target").blur(function(){
      if(jQuery(this).val() === '') {
      jQuery(this).val('Enter City, State, or Zip Code');
      }
      return true;
      }).awesomecomplete({
        typingDelay: 300,
        renderFunction: function(dataItem) {
          if (dataItem === undefined) {
            return '';
          } else {
            if (dataItem.state) {
              return '<p class="completion_option">' + dataItem[this.nameField] + ', ' + dataItem.state.code +  '</p>'
            } else {
              return '<p class="completion_option">' + dataItem[this.nameField] + '</p>';
            } 
          }
        },
        dataMethod: function(term, $awesomecomplete) { 
          jQuery.get('/auto_complete_for_search_params_target', $awesomecomplete.parents('form').serialize(), function (data, textStatus) {
            $awesomecomplete.onData(data);
          }, "json");
        },
        valueFunction: function(dataItem) {
          if (dataItem === undefined) {
            return '';
          } else {
            if (dataItem.state) {
              return dataItem[this.nameField] + ', ' + dataItem.state.code;
            } else {
              return dataItem[this.nameField]
            } 
          }
        } 
      });
    jQuery('a.contact-us').getWithAjax();
    jQuery(".myaccountButton").getWithAjax();
    jQuery(".signupButton").getWithAjax();
    jQuery(".loginButton").getWithAjax();
    jQuery(".addLocation").getWithAjax();
    jQuery('a#found_lost_dog').getWithAjax();
    jQuery('a#haveLostDogBtn').getWithAjax();
    jQuery('a.editDog').getWithAjax();
    jQuery('a.addRev').getWithAjax();
    jQuery('a.addPhotoButton').getWithAjax();
    jQuery('a.sendToFriend').getWithAjax();
    jQuery('a.edit_location').getWithAjax();
    jQuery('a.moreRev').getWithAjax();
    jQuery('a.rateReview').getWithAjax();
    jQuery('a.edit_profile_reminder').getWithAjax();
    jQuery('a.edit_profile_login_success').getWithAjax();
    jQuery('a.send_to_friend_link').getWithAjax();
    jQuery('a.forgotPassword').getWithAjax();
    jQuery('a#profile').getWithAjax();
    jQuery('a#change-password').getWithAjax();
    jQuery('a#dogs').getWithAjax();


    jQuery('.button-to').submit(function() {
        $this = jQuery(this);
        jQuery.get(this.action, null, updatePopupFromResponse, "html");
        return false;
        });

    jQuery(".MapHomepage .mapLegend a.previous").linkToScript();
    jQuery(".MapHomepage .mapLegend a.next").linkToScript();
    jQuery(".foundedLocations .more_details").linkToScript();
    jQuery(".menuItem").linkToScript();


    jQuery("#addLocationSubmit").click (function(){
        hidePopup();
        return true;
        });


    document.onkeydown = function(e) {
      if(jQuery.browser.msie) { 
        keycode = event.keyCode;
      } else { 
        keycode = e.which;
      }
      if(keycode == 27){
        hidePopup();
      }
    };
    

    
});


/*
ôóíêöèÿ öåíòðèðîâàíèÿ ïîïàïà ñ ó÷¸òîì ñêðîëëà
*/

function popupCenter() {

var	wsize = windowWorkSize(),                                               // ðàçìåðû "ðàáî÷åé îáëàñòè"
	testElem = jQuery("#popupBox"),                        // ëîæèì íàø áëîê â ïåðåìåííóþ                                   
	testElemHei =  testElem.find('.popupContent').height();   
	
		topPosPure = wsize[1]/2 - testElemHei/2 + (document.body.scrollTop || document.documentElement.scrollTop);
		topPos = wsize[1]/2 - testElemHei/2 + (document.body.scrollTop || document.documentElement.scrollTop) + "px";// öåíòðèðóåì áëîê ïî âåðòèêàëè + ñêðîëë
		
		if ( topPosPure < 0)
		{
			testElem.css('top','20px' );
		}
		else
		{
			testElem.css('top',topPos );
		}


// ôóíöèÿ îïðåäåëåíèÿ "ðàáî÷åãî ïðîñòðàíñòâà"
function windowWorkSize(){
var wwSize = new Array();
	if (window.innerHeight !== undefined) wwSize= [window.innerWidth,window.innerHeight]    // äëÿ îñíîâíûõ áðàóçåðîâ
		else	
			{	// äëÿ "îñîáî îäàð¸ííûõ" (ÈÅ6-8)
				wwSizeIE = (document.body.clientWidth) ? document.body : document.documentElement; 
				wwSize= [wwSizeIE.clientWidth, wwSizeIE.clientHeight];
			};
	return wwSize;
};
}

/**
 * Awesomecomplete â€” A lightweight, simple autocomplete plugin
 *  Clint Tseng (clint@dontexplain.com) â€” 2009-08-20
 *    I think licenses are dumb and superfluous. I'm releasing this into the
 *    wild under public domain, but please do let me know what you think!
 */

(function($)
{
    var ident = 0;

    // Initializer. Call on a text field to make things go.
    $.fn.awesomecomplete = function(options)
    {
        var options = $.extend({}, $.fn.awesomecomplete.defaults, options);

        return this.each(function()
        {
            var $this = $(this);
            $this.attr('autocomplete', 'off');
            var config = $.meta ? $.extend({}, options, $this.data()) : options;
            $this.data('awesomecomplete-config', config);

            var $attachTo = $(config.attachTo || $this);
            var $list = $('<ul/>').addClass(config.suggestionListClass)
                                  .insertAfter($attachTo)
                                  .hide()
                                  .css({'width': $attachTo.innerWidth(), 'margin-top': $attachTo.outerHeight()});
            $this.data('awesomecomplete-list', $list);

            var typingDelayPointer;
            var suppressKey = false;
            $this.keyup(function(event)
            {
                if (suppressKey)
                {
                    suppressKey = false;
                    return;
                }

                // ignore arrow keys, shift
                if ( ((event.which > 36) && (event.which < 41)) ||
                     (event.which == 16) )
                    return;

                if (config.typingDelay > 0)
                {
                    clearTimeout(typingDelayPointer);
                    typingDelayPointer = setTimeout(function() { processInput($this); });
                }
                else
                {
                    processInput($this);
                }
            });

            $this.keydown(function(event)
            {
                // enter = 13; up = 38; down = 40; esc = 27
                var $active = $list.children('li.' + config.activeItemClass);
                switch (event.which)
                {
                    case 13:
                        if (($active.length !== 0) && ($list.is(':visible')))
                        {
                            event.preventDefault();
                            $this.val($active.data('awesomecomplete-value'));
                            config.onComplete($active.data('awesomecomplete-dataItem'));
                            $list.hide();
                        }
                        $list.hide();
                        suppressKey = true;
                        break;
                    case 38:
                        event.preventDefault();
                        if ($active.length === 0)
                        {
                            $list.children('li:last-child').addClass(config.activeItemClass);
                        }
                        else
                        {
                            $active.prev().addClass(config.activeItemClass);
                            $active.removeClass(config.activeItemClass);
                        }
                        break;
                    case 40:
                        event.preventDefault();
                        if ($active.length === 0)
                        {
                            $list.children('li:first-child').addClass(config.activeItemClass);
                        }
                        else if ($active.is(':not(:last-child)'))
                        {
                            $active.next().addClass(config.activeItemClass);
                            $active.removeClass(config.activeItemClass);
                        }
                        break;
                    case 27:
                        $list.hide();
                        suppressKey = true;
                        break;
                }
            });

            // stupid hack to get around loss of focus on mousedown
            var mouseDown = false;
            var blurWait = false;
            $(document).bind('mousedown.awesomecomplete' + ++ident, function()
            {
                mouseDown = true;
            });
            $(document).bind('mouseup.awesomecomplete' + ident, function()
            {
                mouseDown = false;
                if (blurWait)
                {
                    blurWait = false;
                    $list.hide();
                }
            });
            $this.blur(function()
            {
                if (mouseDown)
                {
                    blurWait = true;
                }
                else
                {
                    var $active = $list.children('li.' + config.activeItemClass);
                    if ($list.is(':visible') && ($active.length !== 0))
                        $this.val($active.data('awesomecomplete-value'));
                    config.onComplete($active.data('awesomecomplete-dataItem'));
                    $list.hide();
                }
            });
            $this.focus(function()
            {
                if ($list.children(':not(.' + config.noResultsClass + ')').length > 0)
                    $list.show();
            });
        });
    };

    // Data callback.  If you're using callbacks to a server,
    // call this on the autocompleted text field to complete the
    // callback process after you have your matching items.
    $.fn.onData = function(data, term)
    {
        return this.each(function()
        {
            var $this = $(this);
            processData($this, data, (term || $this.val()));
        });
    };


// private helpers
    var processInput = function($this)
    {
        if (typeof $this.data('awesomecomplete-config').dataMethod === 'function')
            $this.data('awesomecomplete-config').dataMethod($this.val(), $this);
        else
            processData($this, $this.data('awesomecomplete-config').staticData, $this.val());
    };
    
    var processData = function($this, data, term)
    {
        var $list = $this.data('awesomecomplete-list');
        $list.empty().hide();
        if (term === '')
            return;

        var config = $this.data('awesomecomplete-config');

        var results = [];
        for (var item = 0; item < data.length; item++)
        {
            var dataItem = jQuery.extend({}, data[item]);
            var matchCount = 0;

            var maxFieldMatches = 0;
            var topMatch = null;
            var matchedTerms = [];

            for (var field in dataItem)
            {
                if ((typeof dataItem[field] === 'function') || (typeof dataItem[field] === 'object'))
                    continue;

                for (var j = 0; j < config.dontMatch.length; j++)
                    if (field == config.dontMatch[j])
                        continue;

                var dataString = dataItem[field].toString();
                var terms = [ term ];
                if (config.splitTerm)
                    terms = term.split(config.wordDelimiter);

                for (var j = 0; j < terms.length; j++)
                {
                    if (terms[j] === '')
                        continue;

                    terms[j] = terms[j].replace(/[\\*+?|{}()^$.#]/g, '\\$1');
                    var regex = new RegExp('(' + terms[j] + ')', (config.ignoreCase ? 'ig' : 'g'));

                    var matches = [];
                    if (matches = dataString.match(regex))
                    {
                        matchCount += matches.length;

                        if ((field != config.nameField) && (matches.length > maxFieldMatches))
                        {
                            maxFieldMatches = matches.length;
                            topMatch = field;
                            matchedTerms[j] = true;
                        }
                    }
                }

                if (config.highlightMatches)
                {
                    var regex = new RegExp('(' + terms.join('|') + ')', (config.ignoreCase ? 'ig' : 'g'));
                    dataItem[field] = dataString.replace(regex, '<span class="' + config.highlightClass + '">$1</span>');
                }
            }

            var matchedTermCount = 0;
            for (var j = 0; j < matchedTerms.length; j++)
                if (matchedTerms[j] === true)
                    matchedTermCount++;

            if (matchCount > 0)
                results.push({
                    dataItem: dataItem,
                    originalDataItem: data[item],
                    matchCount: matchCount,
                    topMatch: topMatch,
                    matchedTermCount: matchedTermCount
                });
        }

        results.sort(function(a, b)
        {
            return (a.matchedTermCount == b.matchedTermCount) ?
                   (b.matchCount - a.matchCount) :
                   (b.matchedTermCount - a.matchedTermCount);
        });
        results = results.slice(0, config.resultLimit);

        for (var i in results)
        {
            if ((typeof results[i] === 'function')) 
                 continue;
            var item = $('<li>' + config.renderFunction(results[i].dataItem, results[i].topMatch, results[i].originalDataItem) + '</li>');
            item.data('awesomecomplete-dataItem', results[i].originalDataItem);
            item.data('awesomecomplete-value', config.valueFunction(results[i].originalDataItem));
            item.appendTo($list);
            item.click(function() {
                $this.val($(this).data('awesomecomplete-value'));
            });
            item.mouseover(function() {
              $(this).addClass(config.activeItemClass).siblings().removeClass(config.activeItemClass);
            });
        }

        if ((config.noResultsMessage !== undefined) && (results.length == 0))
            $list.append($('<li class="' + config.noResultsClass + '">' + config.noResultsMessage + '</li>'));

        if ((results.length > 0) || (config.noResultsMessage !== undefined))
            $list.show();
    };

// default functions
    var defaultRenderFunction = function(dataItem, topMatch)
    {
        if (topMatch === this.nameField)
            return '<p class="title">' + dataItem[this.nameField] + '</p>';
        else
            return '<p class="title">' + dataItem[this.nameField] + '</p>' +
                   '<p class="matchRow"><span class="matchedField">' + this.topMatch + '</span>: ' +
                        dataItem[this.topMatch] + '</p>';
    };
    
    var defaultValueFunction = function(dataItem)
    {
        return dataItem[this.nameField];
    };

    $.fn.awesomecomplete.defaults = {
        activeItemClass: 'active',
        attachTo: undefined,
        dataMethod: undefined,
        dontMatch: [],
        highlightMatches: true,
        highlightClass: 'match',
        ignoreCase: true,
        nameField: 'name',
        noResultsClass: 'noResults',
        noResultsMessage: undefined,
        onComplete: function(dataItem) {},
        splitTerm: true,
        staticData: [],
        suggestionListClass: "autocomplete",
        renderFunction: defaultRenderFunction,
        resultLimit: 10,
        typingDelay: 0,
        valueFunction: defaultValueFunction,
        wordDelimiter: /[^\da-z]+/ig
    };
})(jQuery);


function createDraggableMarkerAt(latlng) {
  var the_marker;
    the_marker = new GMarker(latlng, { draggable: true });
    the_marker.enableDragging();
    GEvent.addListener(the_marker,"dragend", function(latlng) {
      var geoCoder = new GClientGeocoder();
      geoCoder.getLocations(latlng, function(response) {
        if (!response || response.Status.code != 200) {
          the_marker.hide();
          the_marker.openInfoWindowHtml("Sorry, we couldn't place the pin exactly there");
        } else {
          place = response.Placemark[0];
          jQuery('.address').val(place.address);
        }
      });
    }); 
  return the_marker;
}

function dropMoveablePin(map, lat, lng) {
  var marker = createDraggableMarkerAt(new GLatLng(lat, lng));
  map.addOverlay(marker);
  return marker;
}

function dropPin(map, lat, lng, options) {
  var point = new GLatLng(lat, lng);
  var markerOpts = {};
  if (options && options.titleText && options.markerIcon) {
    markerOpts = {title: options.titleText, icon: options.markerIcon};
  }
  var marker = new GMarker(point, markerOpts);
	
  if (options) {
    if (options.htmlContent) {
        var infoWindowMarkup = options.htmlContent;
    } else {
      if (options.link && options.titleText) {
        var infoWindowMarkup = "<a href='"+options.link+"'>"+options.titleText+"</a>";
      }
      if (options.address) {
        infoWindowMarkup = infoWindowMarkup + "<address>"+options.address+"</address>";
      }
    }
    marker.bindInfoWindowHtml(infoWindowMarkup);
  }
  return marker;
}


function centerMapOnMarker(map, marker) {
  try {
    if(map.getCenter() != marker.getLatLng()) {
      map.setCenter(marker.getLatLng(), 15);
    }
    map.savePosition();
  } catch(err) {
  }
}



var renderDataItem = function(dataItem) {
  if (dataItem === undefined) {
    return '';
  } else {
    return '<p class="completion_option">' + dataItem[this.nameField] + '</p>';
  }
};

var updateMap = function(dataItem) {
  if (dataItem && typeof(map) !== 'undefined') {
    marker = dropMoveablePin(map, dataItem.Point.coordinates[1], dataItem.Point.coordinates[0]);
    centerMapOnMarker(map, marker);
  }
};

jQuery.fn.awesomecompleteAddress = function() {
  this.awesomecomplete({ 
    nameField: 'address',
    typingDelay: 600,
    renderFunction: renderDataItem,
    dataMethod: function(term, $awesomecomplete) {
      var geocoder = new GClientGeocoder(); 
      geocoder.getLocations(term, function(response) {
        if (response.Placemark) {
          possible_completions = jQuery.map(response.Placemark, function(place) {
            if (place.AddressDetails.Country) {
              if (place.AddressDetails.Country.CountryNameCode != 'US') {
                return undefined;
              }
            } else {
              return undefined;
            }
            return place;
          });
          updateMap(possible_completions[0]);
          $awesomecomplete.onData(possible_completions);
        }
      });
    }
  });
  return this;
};

jQuery(document).ready(function () {
  jQuery('.address').awesomecompleteAddress();
});


var getRating = function(elem) {
  return jQuery.makeArray(jQuery(elem).attr('class'))[0];
};

var fillRating = function(li, rating) {
  var rateMe = jQuery(li).parents('.rateMe');
  jQuery('.rating', rateMe).each(function(i, elem) {
      if ( rating >= getRating(elem) ) {
        jQuery(elem).addClass('on');
      } else {
        jQuery(elem).removeClass('on');
      }
  });
};

var rateIt = function(location_id, rating) {
  jQuery.get('/locations/'+ location_id+ '/rate_location', {rating: rating}, function(rating) { 
      jQuery('#rating').empty().append(rating);
      fillRating(rating);
  });
  jQuery('.rateMe .rating').unbind("click").unbind("mouseenter").unbind("mouseleave");
};

var resetRating = function() {
  var rateMe = jQuery(this).parents('.rateMe');
  jQuery('.rating', rateMe).removeClass('on');
};

jQuery(document).ready(function() {
  jQuery('.rateMe .rating').mouseenter(function() {var rating = getRating(this);fillRating(this, rating);}).mouseleave(resetRating);
  jQuery('.rateMe.done .rating').unbind("click").unbind("mouseenter").unbind("mouseleave");
});


jQuery(document).ready(function(){
    jQuery(".checkBoxContainer div").mousedown( function() {
      changeCheck(jQuery(this));
    });

    jQuery(".checkBoxContainer div").each( function() {
      changeCheckStart(jQuery(this));
    });
});

function changeCheck(el) {
  var el = el,
      input = el.find("input").eq(0);
  if(! input.attr("checked")) {
    el.css("background-position","0 -17px");    
    el.addClass("customCheckBoxChecked");
    input.attr("checked", true);
  } else {
    el.css("background-position","0 0");    
    input.attr("checked", ""); 
    el.removeClass("customCheckBoxChecked");
  }
  return true;
}

function changeCheckStart(el) {
  var el = el,
      input = el.find("input").eq(0);
  if(input.val()=="1" && input.attr("checked") ) {
    el.css("background-position","0 -17px");    
    el.addClass("customCheckBoxChecked");
  }
  return true;
}


	jQuery(document).ready(function(){
	 
	jQuery(".checkBoxContainer2 div").mousedown(
	function() {
	 
	     changeCheck2(jQuery(this));
	      
	});
	 
	 
	jQuery(".checkBoxContainer2 div").each(
	/* ïðè çàãðóçêå ñòðàíèöû íóæíî ïðîâåðèòü êàêîå çíà÷åíèå èìååò ÷åêáîêñ è â ñîîòâåòñòâèè ñ íèì âûñòàâèòü âèä */
	function() {
	      
	     changeCheckStart2(jQuery(this));
	      
	});
	 
	                                        });
	 
	function changeCheck2(el2)
	/*
	    ôóíêöèÿ ñìåíû âèäà è çíà÷åíèÿ ÷åêáîêñà
	    el - span êîíòåéíåð äÿë îáû÷íîãî ÷åêáîêñà
	    input - ÷åêáîêñ
	*/
	{
	     var el2 = el2,
	          input = el2.find("input").eq(0);
	     if(input.val()=="0")
	     {
	          el2.css("background-position","0 -23px");    
	          input.val("1");
	     }
	     else
	     {
	          el2.css("background-position","0 0");    
	          input.val("0");
	     }
	     return true;
	}
	 
	function changeCheckStart2(el2)
	/*
	    åñëè çíà÷åíèå óñòàíîâëåíî â on, ìåíÿåì âèä ÷åêáîêñà íà âêëþ÷åííûé
	*/
	{
	     var el2 = el2,
	          input = el2.find("input").eq(0);
	     if(input.val()=="1")
	     {
	          el2.css("background-position","0 -23px");    
	     }
	     return true;
	}
	 

ï»¿jQuery(document).ready(function(){
  jQuery(".niceRadio").each( function() {
    changeRadioStart(jQuery(this));
  });
});

function changeRadio(el) {
  var el = el,
      input = el.find("input").eq(0);
  var nm=input.attr("name");

  jQuery(".niceRadio input").each( function() {
      if(jQuery(this).attr("name")==nm) {
      jQuery(this).parent().removeClass("radioChecked");
      }
      });					  
  if(el.attr("class").indexOf("niceRadioDisabled")==-1) {	
    el.addClass("radioChecked");
    input.attr("checked", true);
  }
  return true;
}

function changeVisualRadio(input) {
  var wrapInput = input.parent();
  var nm=input.attr("name");

  jQuery(".niceRadio input").each(function() {
      if(jQuery(this).attr("name")==nm) {
      jQuery(this).parent().removeClass("radioChecked");
      }
      });

  if(input.attr("checked")) {
    wrapInput.addClass("radioChecked");
  }
}

function changeRadioStart(el) {
  try {
    var el = el,
        radioName = el.attr("name"),
        radioId = el.attr("id"),
        radioChecked = el.attr("checked"),
        radioDisabled = el.attr("disabled"),
        radioTab = el.attr("tabindex");
        radioValue = el.attr("value");
    if(radioChecked)
      el.after("<span class='niceRadio radioChecked'>"+
          "<input type='radio'"+
          "name='"+radioName+"'"+
          "id='"+radioId+"'"+
          "checked='"+radioChecked+"'"+
          "tabindex='"+radioTab+"'"+
          "value='"+radioValue+"' /></span>");
    else
      el.after("<span class='niceRadio'>"+
          "<input type='radio'"+
          "name='"+radioName+"'"+
          "id='"+radioId+"'"+
          "tabindex='"+radioTab+"'"+
          "value='"+radioValue+"' /></span>");

    if(radioDisabled) {
      el.next().addClass("niceRadioDisabled");
      el.next().find("input").eq(0).attr("disabled","disabled");
    }

    el.next().bind("mousedown", function(e) { changeRadio(jQuery(this)) });
    el.next().find("input").eq(0).bind("change", function(e) { changeVisualRadio(jQuery(this)) });
    if(jQuery.browser.msie) {
      el.next().find("input").eq(0).bind("click", function(e) { changeVisualRadio(jQuery(this)) });	
    }
    el.remove();
  } catch(e) {
  }
  return true;
}


/*
        DatePicker v4.4 by frequency-decoder.com

        Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/)

        Please credit frequency-decoder in any derivative work - thanks.
        
        You are free:

        * to copy, distribute, display, and perform the work
        * to make derivative works
        * to make commercial use of the work

        Under the following conditions:

                by Attribution.
                --------------
                You must attribute the work in the manner specified by the author or licensor.

                sa
                --
                Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one.

        * For any reuse or distribution, you must make clear to others the license terms of this work.
        * Any of these conditions can be waived if you get permission from the copyright holder.
*/
var datePickerController;

(function() {

// Detect the browser language
datePicker.languageinfo = navigator.language ? navigator.language : navigator.userLanguage;
datePicker.languageinfo = datePicker.languageinfo ? datePicker.languageinfo.toLowerCase().replace(/-[a-z]+$/, "") : 'en';

// Load the appropriate language file
var scriptFiles = document.getElementsByTagName('head')[0].getElementsByTagName('script');
var loc = scriptFiles[scriptFiles.length - 1].src.substr(0, scriptFiles[scriptFiles.length - 1].src.lastIndexOf("/")) + "/lang/" + datePicker.languageinfo + ".js";

var script  = document.createElement('script');
script.type = "text/javascript";
script.src  = loc;
script.setAttribute("charset", "utf-8");
/*@cc_on
/*@if(@_win32)
        var bases = document.getElementsByTagName('base');
        if (bases.length && bases[0].childNodes.length) {
                bases[0].appendChild(script);
        } else {
                document.getElementsByTagName('head')[0].appendChild(script);
        };
@else @*/
document.getElementsByTagName('head')[0].appendChild(script);
/*@end
@*/
script  = null;

// Defaults should the locale file not load
datePicker.months       = ["January","February","March","April","May","June","July","August","September","October","November","December"];
datePicker.fullDay      = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
datePicker.titles       = ["Previous month","Next month","Previous year","Next year", "Today", "Show Calendar"];

datePicker.getDaysPerMonth = function(nMonth, nYear) {
        nMonth = (nMonth + 12) % 12;
        return (((0 == (nYear%4)) && ((0 != (nYear%100)) || (0 == (nYear%400)))) && nMonth == 1) ? 29: [31,28,31,30,31,30,31,31,30,31,30,31][nMonth];
};

function datePicker(options) {

        this.defaults          = {};
        for(opt in options) { this[opt] = this.defaults[opt] = options[opt]; };
        
        this.date              = new Date();
        this.yearinc           = 1;
        this.timer             = null;
        this.pause             = 1000;
        this.timerSet          = false;
        this.fadeTimer         = null;
        this.interval          = new Date();
        this.firstDayOfWeek    = this.defaults.firstDayOfWeek = this.dayInc = this.monthInc = this.yearInc = this.opacity = this.opacityTo = 0;
        this.dateSet           = null;
        this.visible           = false;
        this.disabledDates     = [];
        this.enabledDates      = [];
        this.nbsp              = String.fromCharCode( 160 );
        var o = this;

        o.events = {
                onblur:function(e) {
                        o.removeKeyboardEvents();
                },
                onfocus:function(e) {
                        o.addKeyboardEvents();
                },
                onkeydown: function (e) {
                        o.stopTimer();
                        if(!o.visible) return false;

                        if(e == null) e = document.parentWindow.event;
                        var kc = e.keyCode ? e.keyCode : e.charCode;

                        if( kc == 13 ) {
                                // close (return)
                                var td = document.getElementById(o.id + "-date-picker-hover");
                                if(!td || td.className.search(/out-of-range|day-disabled/) != -1) return o.killEvent(e);
                                o.returnFormattedDate();
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 27) {
                                // close (esc)
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 32 || kc == 0) {
                                // today (space)
                                o.date =  new Date();
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        // Internet Explorer fires the keydown event faster than the JavaScript engine can
                        // update the interface. The following attempts to fix this.
                        /*@cc_on
                        @if(@_win32)
                                if(new Date().getTime() - o.interval.getTime() < 100) return o.killEvent(e);
                                o.interval = new Date();
                        @end
                        @*/

                        if ((kc > 49 && kc < 56) || (kc > 97 && kc < 104)) {
                                if (kc > 96) kc -= (96-48);
                                kc -= 49;
                                o.firstDayOfWeek = (o.firstDayOfWeek + kc) % 7;
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        if ( kc < 37 || kc > 40 ) return true;

                        var d = new Date( o.date ).valueOf();

                        if ( kc == 37 ) {
                                // ctrl + left = previous month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() - 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 1 );
                                };
                        } else if ( kc == 39 ) {
                                // ctrl + right = next month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() + 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 1 );
                                };
                        } else if ( kc == 38 ) {
                                // ctrl + up = next year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() + 1)) );
                                        d.setFullYear( d.getFullYear() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 7 );
                                };
                        } else if ( kc == 40 ) {
                                // ctrl + down = prev year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() - 1)) );
                                        d.setFullYear( d.getFullYear() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 7 );
                                };
                        };

                        var tmpDate = new Date(d);

                        if(o.outOfRange(tmpDate)) return o.killEvent(e);
                        
                        var cacheDate = new Date(o.date);
                        o.date = tmpDate;

                        if(cacheDate.getFullYear() != o.date.getFullYear() || cacheDate.getMonth() != o.date.getMonth()) o.updateTable();
                        else {
                                o.disableTodayButton();
                                var tds = o.table.getElementsByTagName('td');
                                var txt;
                                var start = o.date.getDate() - 6;
                                if(start < 0) start = 0;

                                for(var i = start, td; td = tds[i]; i++) {
                                        txt = Number(td.firstChild.nodeValue);
                                        if(isNaN(txt) || txt != o.date.getDate()) continue;
                                        o.removeHighlight();
                                        td.id = o.id + "-date-picker-hover";
                                        td.className = td.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                                };
                        };
                        return o.killEvent(e);
                },
                gotoToday: function(e) {
                        o.date = new Date();
                        o.updateTable();
                        return o.killEvent(e);
                },
                onmousedown: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        var found = false;
                        while(el.parentNode) {
                                if(el.id && (el.id == "fd-"+o.id || el.id == "fd-but-"+o.id)) {
                                        found = true;
                                        break;
                                };
                                try {
                                        el = el.parentNode;
                                } catch(err) {
                                        break;
                                };
                        };
                        if(found) return true;
                        o.stopTimer();
                        datePickerController.hideAll();
                },
                onmouseover: function(e) {
                        o.stopTimer();
                        var txt = this.firstChild.nodeValue;
                        if(this.className == "out-of-range" || txt.search(/^[\d]+$/) == -1) return;
                        
                        o.removeHighlight();
                        
                        this.id = o.id+"-date-picker-hover";
                        this.className = this.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                        
                        o.date.setDate(this.firstChild.nodeValue);
                        o.disableTodayButton();
                },
                onclick: function(e) {
                        if(o.opacity != o.opacityTo || this.className.search(/out-of-range|day-disabled/) != -1) return false;
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;
                        while ( el.nodeType != 1 ) el = el.parentNode;
                        var d = new Date( o.date );
                        var txt = el.firstChild.data;
                        if(txt.search(/^[\d]+$/) == -1) return;
                        var n = Number( txt );
                        if(isNaN(n)) { return true; };
                        d.setDate( n );
                        o.date = d;
                        o.returnFormattedDate();
                        if(!o.staticPos) o.hide();
                        o.stopTimer();
                        return o.killEvent(e);
                },
                incDec: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        if(el && el.className && el.className.search('fd-disabled') != -1) { return false; }
                        datePickerController.addEvent(document, "mouseup", o.events.clearTimer);
                        o.timerInc      = 800;
                        o.dayInc        = arguments[1];
                        o.yearInc       = arguments[2];
                        o.monthInc      = arguments[3];
                        o.timerSet      = true;

                        o.updateTable();
                        return true;
                },
                clearTimer: function(e) {
                        o.stopTimer();
                        o.timerInc      = 1000;
                        o.yearInc       = 0;
                        o.monthInc      = 0;
                        o.dayInc        = 0;
                        datePickerController.removeEvent(document, "mouseup", o.events.clearTimer);
                }
        };
        o.stopTimer = function() {
                o.timerSet = false;
                window.clearTimeout(o.timer);
        };
        o.removeHighlight = function() {
                if(document.getElementById(o.id+"-date-picker-hover")) {
                        document.getElementById(o.id+"-date-picker-hover").className = document.getElementById(o.id+"-date-picker-hover").className.replace("date-picker-hover", "");
                        document.getElementById(o.id+"-date-picker-hover").id = "";
                };
        };
        o.reset = function() {
                for(def in o.defaults) { o[def] = o.defaults[def]; };
        };
        o.setOpacity = function(op) {
                o.div.style.opacity = op/100;
                o.div.style.filter = 'alpha(opacity=' + op + ')';
                o.opacity = op;
        };
        o.fade = function() {
                window.clearTimeout(o.fadeTimer);
                o.fadeTimer = null;
                delete(o.fadeTimer);
                
                var diff = Math.round(o.opacity + ((o.opacityTo - o.opacity) / 4));

                o.setOpacity(diff);

                if(Math.abs(o.opacityTo - diff) > 3 && !o.noTransparency) {
                        o.fadeTimer = window.setTimeout(o.fade, 50);
                } else {
                        o.setOpacity(o.opacityTo);
                        if(o.opacityTo == 0) {
                                o.div.style.display = "none";
                                o.visible = false;
                        } else {
                                o.visible = true;
                        };
                };
        };
        o.killEvent = function(e) {
                e = e || document.parentWindow.event;
                
                if(e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                };
                
                /*@cc_on
                @if(@_win32)
                e.cancelBubble = true;
                e.returnValue = false;
                @end
                @*/
                return false;
        };
        o.getElem = function() {
                return document.getElementById(o.id.replace(/^fd-/, '')) || false;
        };
        o.setRangeLow = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.low = o.defaults.low = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setRangeHigh = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.high = o.defaults.high = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDays = function(dayArray) {
                o.disableDays = o.defaults.disableDays = dayArray;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01])$/) != -1) fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = fin;
                        o.enabledDates = [];
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.setEnabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01]|\*\*)$/) != -1 && dateArray[i] != "********") fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = [];
                        o.enabledDates = fin;
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.getDisabledDates = function(y, m) {
                if(o.enabledDates.length) return o.getEnabledDates(y, m);
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                for(var i = o.disabledDates.length; i-- ;) {
                        var tmp = o.disabledDates[i].replace("****", y).replace("**", m);
                        if(tmp < Number(String(y)+m+"01") || tmp > Number(y+String(m)+d)) continue;
                        obj[tmp] = 1;
                };
                return obj;
        };
        o.getEnabledDates = function(y, m) {
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                var day,tmp,de,me,ye,disabled;
                for(var dd = 1; dd <= d; dd++) {
                        day = dd < 10 ? "0" + String(dd) : dd;
                        disabled = true;
                        for(var i = o.enabledDates.length; i-- ;) {
                                tmp = o.enabledDates[i];
                                ye  = String(o.enabledDates[i]).substr(0,4);
                                me  = String(o.enabledDates[i]).substr(4,2);
                                de  = String(o.enabledDates[i]).substr(6,2);

                                if(ye == y && me == m && de == day) {
                                        disabled = false;
                                        break;
                                }
                                
                                if(ye == "****" || me == "**" || de == "**") {
                                        if(ye == "****") tmp = tmp.replace(/^\*\*\*\*/, y);
                                        if(me == "**")   tmp = tmp = tmp.substr(0,4) + String(m) + tmp.substr(6,2);
                                        if(de == "**")   tmp = tmp.replace(/\*\*/, day);

                                        if(tmp == String(y + String(m) + day)) {
                                                disabled = false;
                                                break;
                                        };
                                };
                        };
                        if(disabled) obj[String(y + String(m) + day)] = 1;
                };
                return obj;
        };
        o.setFirstDayOfWeek = function(e) {
                if ( e == null ) e = document.parentWindow.event;
                var elem = e.target != null ? e.target : e.srcElement;
                if(elem.tagName.toLowerCase() != "th") {
                        while(elem.tagName.toLowerCase() != "th") elem = elem.parentNode;
                };
                var cnt = 0;
                while(elem.previousSibling) {
                        elem = elem.previousSibling;
                        if(elem.tagName.toLowerCase() == "th") cnt++;
                };
                o.firstDayOfWeek = (o.firstDayOfWeek + cnt) % 7;
                o.updateTableHeaders();
                return o.killEvent(e);
        };
        o.truePosition = function(element) {
                var pos = o.cumulativeOffset(element);
                if(window.opera) { return pos; }
                var iebody      = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
                var dsocleft    = document.all ? iebody.scrollLeft : window.pageXOffset;
                var dsoctop     = document.all ? iebody.scrollTop  : window.pageYOffset;
                var posReal     = o.realOffset(element);
                return [pos[0] - posReal[0] + dsocleft, pos[1] - posReal[1] + dsoctop];
        };
        o.realOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.scrollTop  || 0;
                        l += element.scrollLeft || 0;
                        element = element.parentNode;
                } while (element);
                return [l, t];
        };
        o.cumulativeOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.offsetTop  || 0;
                        l += element.offsetLeft || 0;
                        element = element.offsetParent;
                } while (element);
                return [l, t];
        };
        o.resize = function() {
                if(!o.created || !o.getElem()) return;
                
                o.div.style.visibility = "hidden";
                if(!o.staticPos) { o.div.style.left = o.div.style.top = "0px"; }
                o.div.style.display = "block";
                
                var osh = o.div.offsetHeight;
                var osw = o.div.offsetWidth;
                
                o.div.style.visibility = "visible";
                o.div.style.display = "none";
                
                if(!o.staticPos) {
                        var elem          = document.getElementById('fd-but-' + o.id);
                        var pos           = o.truePosition(elem);
                        var trueBody      = (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body;
                        var scrollTop     = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollTop;
                        var scrollLeft    = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollLeft;

                        if(parseInt(trueBody.clientWidth+scrollLeft) < parseInt(osw+pos[0])) {
                                o.div.style.left = Math.abs(parseInt((trueBody.clientWidth+scrollLeft) - osw)) + "px";
                        } else {
                                o.div.style.left  = pos[0] + "px";
                        };

                        if(parseInt(trueBody.clientHeight+scrollTop) < parseInt(osh+pos[1]+elem.offsetHeight+2)) {
                                o.div.style.top   = Math.abs(parseInt(pos[1] - (osh + 2))) + "px";
                        } else {
                                o.div.style.top   = Math.abs(parseInt(pos[1] + elem.offsetHeight + 2)) + "px";
                        };
                };
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(o.staticPos) return;
                o.iePopUp.style.top    = o.div.style.top;
                o.iePopUp.style.left   = o.div.style.left;
                o.iePopUp.style.width  = osw + "px";
                o.iePopUp.style.height = (osh - 2) + "px";
                @end
                @*/
        };
        o.equaliseDates = function() {
                var clearDayFound = false;
                var tmpDate;
                for(var i = o.low; i <= o.high; i++) {
                        tmpDate = String(i);
                        if(!o.disableDays[new Date(tmpDate.substr(0,4), tmpDate.substr(6,2), tmpDate.substr(4,2)).getDay() - 1]) {
                                clearDayFound = true;
                                break;
                        };
                };
                if(!clearDayFound) o.disableDays = o.defaults.disableDays = [0,0,0,0,0,0,0];
        };
        o.outOfRange = function(tmpDate) {
                if(!o.low && !o.high) return false;

                var level = false;
                if(!tmpDate) {
                        level = true;
                        tmpDate = o.date;
                };
                
                var d  = (tmpDate.getDate() < 10) ? "0" + tmpDate.getDate() : tmpDate.getDate();
                var m  = ((tmpDate.getMonth() + 1) < 10) ? "0" + (tmpDate.getMonth() + 1) : tmpDate.getMonth() + 1;
                var y  = tmpDate.getFullYear();
                var dt = String(y)+String(m)+String(d);

                if(o.low && parseInt(dt) < parseInt(o.low)) {
                        if(!level) return true;
                        o.date = new Date(o.low.substr(0,4), o.low.substr(4,2)-1, o.low.substr(6,2), 5, 0, 0);
                        return false;
                };
                if(o.high && parseInt(dt) > parseInt(o.high)) {
                        if(!level) return true;
                        o.date = new Date( o.high.substr(0,4), o.high.substr(4,2)-1, o.high.substr(6,2), 5, 0, 0);
                };
                return false;
        };
        o.createButton = function() {
                if(o.staticPos) { return; };
                
                var but;
                
                if(!document.getElementById("fd-but-" + o.id)) {
                        var inp = o.getElem();
                        
                        but = document.createElement('a');
                        but.href = "#";

                        var span = document.createElement('span');
                        span.appendChild(document.createTextNode(String.fromCharCode( 160 )));

                        but.className = "date-picker-control";
                        but.title = (typeof(fdLocale) == "object" && options.locale && fdLocale.titles.length > 5) ? fdLocale.titles[5] : "";

                        but.id = "fd-but-" + o.id;
                        but.appendChild(span);

                        if(inp.nextSibling) {
                                inp.parentNode.insertBefore(but, inp.nextSibling);
                        } else {
                                inp.parentNode.appendChild(but);
                        };
                } else {
                        but = document.getElementById("fd-but-" + o.id);
                };

                but.onclick = but.onpress = function(e) {
                        e = e || window.event;
                        var inpId = this.id.replace('fd-but-','');
                        try { var dp = datePickerController.getDatePicker(inpId); } catch(err) { return false; };

                        if(e.type == "press") {
                                var kc = e.keyCode != null ? e.keyCode : e.charCode;
                                if(kc != 13) { return true; };
                                if(dp.visible) {
                                        hideAll();
                                        return false;
                                };
                        };

                        if(!dp.visible) {
                                datePickerController.hideAll(inpId);
                                dp.show();
                        } else {
                                datePickerController.hideAll();
                        };
                        return false;
                };
                but = null;
        },
        o.create = function() {
                
                function createTH(details) {
                        var th = document.createElement('th');
                        if(details.thClassName) th.className = details.thClassName;
                        if(details.colspan) {
                                /*@cc_on
                                /*@if (@_win32)
                                th.setAttribute('colSpan',details.colspan);
                                @else @*/
                                th.setAttribute('colspan',details.colspan);
                                /*@end
                                @*/
                        };
                        /*@cc_on
                        /*@if (@_win32)
                        th.unselectable = "on";
                        /*@end@*/
                        return th;
                };
                
                function createThAndButton(tr, obj) {
                        for(var i = 0, details; details = obj[i]; i++) {
                                var th = createTH(details);
                                tr.appendChild(th);
                                var but = document.createElement('span');
                                but.className = details.className;
                                but.id = o.id + details.id;
                                but.appendChild(document.createTextNode(details.text));
                                but.title = details.title || "";
                                if(details.onmousedown) but.onmousedown = details.onmousedown;
                                if(details.onclick)     but.onclick     = details.onclick;
                                if(details.onmouseout)  but.onmouseout  = details.onmouseout;
                                th.appendChild(but);
                        };
                };
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(!document.getElementById("iePopUpHack")) {
                                o.iePopUp = document.createElement('iframe');
                                o.iePopUp.src = "javascript:'<html></html>';";
                                o.iePopUp.setAttribute('className','iehack');
                                o.iePopUp.scrolling="no";
                                o.iePopUp.frameBorder="0";
                                o.iePopUp.name = o.iePopUp.id = "iePopUpHack";
                                document.body.appendChild(o.iePopUp);
                        } else {
                                o.iePopUp = document.getElementById("iePopUpHack");
                        };
                @end
                @*/
                
                if(typeof(fdLocale) == "object" && o.locale) {
                        datePicker.titles  = fdLocale.titles;
                        datePicker.months  = fdLocale.months;
                        datePicker.fullDay = fdLocale.fullDay;
                        // Optional parameters
                        if(fdLocale.dayAbbr) datePicker.dayAbbr = fdLocale.dayAbbr;
                        if(fdLocale.firstDayOfWeek) o.firstDayOfWeek = o.defaults.firstDayOfWeek = fdLocale.firstDayOfWeek;
                };
                
                o.div = document.createElement('div');
                o.div.style.zIndex = 9999;
                o.div.id = "fd-"+o.id;
                o.div.className = "datePicker";
                
                if(!o.staticPos) {
                        document.getElementsByTagName('body')[0].appendChild(o.div);
                } else {
                        elem = o.getElem();
                        if(!elem) {
                                o.div = null;
                                return;
                        };
                        o.div.className += " staticDP";
                        o.div.setAttribute("tabIndex", "0");
                        o.div.onfocus = o.events.onfocus;
                        o.div.onblur  = o.events.onblur;
                        elem.parentNode.insertBefore(o.div, elem.nextSibling);
                        if(o.hideInput && elem.type && elem.type == "text") elem.setAttribute("type", "hidden");
                };
                
                //var nbsp = String.fromCharCode( 160 );
                var tr, row, col, tableHead, tableBody;

                o.table = document.createElement('table');
                o.div.appendChild( o.table );
                
                tableHead = document.createElement('thead');
                o.table.appendChild( tableHead );
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                // Title Bar
                o.titleBar = createTH({thClassName:"date-picker-title", colspan:7});
                tr.appendChild( o.titleBar );
                tr = null;
                
                var span = document.createElement('span');
                span.className = "month-display";
                o.titleBar.appendChild(span);

                span = document.createElement('span');
                span.className = "year-display";
                o.titleBar.appendChild(span);

                span = null;
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                createThAndButton(tr, [{className:"prev-but", id:"-prev-year-but", text:"\u00AB", title:datePicker.titles[2], onmousedown:function(e) { o.events.incDec(e,0,-1,0); }, onmouseout:o.events.clearTimer },{className:"prev-but", id:"-prev-month-but", text:"\u2039", title:datePicker.titles[0], onmousedown:function(e) { o.events.incDec(e,0,0,-1); }, onmouseout:o.events.clearTimer },{colspan:3, className:"today-but", id:"-today-but", text:datePicker.titles.length > 4 ? datePicker.titles[4] : "Today", onclick:o.events.gotoToday},{className:"next-but", id:"-next-month-but", text:"\u203A", title:datePicker.titles[1], onmousedown:function(e) { o.events.incDec(e,0,0,1); }, onmouseout:o.events.clearTimer },{className:"next-but", id:"-next-year-but", text:"\u00BB", title:datePicker.titles[3], onmousedown:function(e) { o.events.incDec(e,0,1,0); }, onmouseout:o.events.clearTimer }]);

                tableBody = document.createElement('tbody');
                o.table.appendChild( tableBody );

                for(var rows = 0; rows < 7; rows++) {
                        row = document.createElement('tr');

                        if(rows != 0) tableBody.appendChild(row);
                        else          tableHead.appendChild(row);
                        
                        for(var cols = 0; cols < 7; cols++) {
                                col = (rows == 0) ? document.createElement('th') : document.createElement('td');

                                row.appendChild(col);
                                if(rows != 0) {
                                        col.appendChild(document.createTextNode(o.nbsp));
                                        col.onmouseover = o.events.onmouseover;
                                        col.onclick = o.events.onclick;
                                } else {
                                        col.className = "date-picker-day-header";
                                        col.scope = "col";
                                };
                                col = null;
                        };
                        row = null;
                };

                // Table headers
                var but;
                var ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                for ( var y = 0; y < 7; y++ ) {
                        if(y > 0) {
                                but = document.createElement("span");
                                but.className = "fd-day-header";
                                but.onclick = ths[y].onclick = o.setFirstDayOfWeek;
                                but.appendChild(document.createTextNode(o.nbsp));
                                ths[y].appendChild(but);
                                but = null;
                        } else {
                                ths[y].appendChild(document.createTextNode(o.nbsp));
                        };
                };
                
                o.ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                o.trs = o.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
                
                o.updateTableHeaders();
                
                tableBody = tableHead = tr = createThAndButton = createTH = null;

                if(o.low && o.high && (o.high - o.low < 7)) { o.equaliseDates(); };
                
                o.created = true;
                
                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.addEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');
                                datePickerController.addEvent(mmN, "change", o.changeHandler);
                                datePickerController.addEvent(ddN, "change", o.changeHandler);
                        };
                        
                        o.show();
                } else {
                        o.createButton();
                        o.resize();
                        o.fade();
                };
        };
        o.changeHandler = function() {
                o.setDateFromInput();
                o.updateTable();
        };
        o.setDateFromInput = function() {
                function m2c(val) {
                        return String(val).length < 2 ? "00".substring(0, 2 - String(val).length) + String(val) : val;
                };

                o.dateSet = null;
                
                var elem = o.getElem();
                if(!elem) return;

                if(!o.splitDate) {
                        var date = datePickerController.dateFormat(elem.value, o.format.search(/m-d-y/i) != -1);
                } else {
                        var mmN = document.getElementById(o.id+'-mm');
                        var ddN = document.getElementById(o.id+'-dd');
                        var tm = parseInt(mmN.tagName.toLowerCase() == "input"  ? mmN.value  : mmN.options[mmN.selectedIndex].value, 10);
                        var td = parseInt(ddN.tagName.toLowerCase() == "input"  ? ddN.value  : ddN.options[ddN.selectedIndex].value, 10);
                        var ty = parseInt(elem.tagName.toLowerCase() == "input" ? elem.value : elem.options[elem.selectedIndex || 0].value, 10);
                        var date = datePickerController.dateFormat(tm + "/" + td + "/" + ty, true);
                };

                var badDate = false;
                if(!date) {
                        badDate = true;
                        date = String(new Date().getFullYear()) + m2c(new Date().getMonth()+1) + m2c(new Date().getDate());
                };

                var d,m,y;
                y = Number(date.substr(0, 4));
                m = Number(date.substr(4, 2)) - 1;
                d = Number(date.substr(6, 2));

                var dpm = datePicker.getDaysPerMonth(m, y);
                if(d > dpm) d = dpm;

                if(new Date(y, m, d) == 'Invalid Date' || new Date(y, m, d) == 'NaN') {
                        badDate = true;
                        o.date = new Date();
                        o.date.setHours(5);
                        return;
                };

                o.date = new Date(y, m, d);
                o.date.setHours(5);

                if(!badDate) o.dateSet = new Date(o.date);
                m2c = null;
        };
        o.setSelectIndex = function(elem, indx) {
                var len = elem.options.length;
                indx = Number(indx);
                for(var opt = 0; opt < len; opt++) {
                        if(elem.options[opt].value == indx) {
                                elem.selectedIndex = opt;
                                return;
                        };
                };
        },
        o.returnFormattedDate = function() {

                var elem = o.getElem();
                if(!elem) return;
                
                var d                   = (o.date.getDate() < 10) ? "0" + o.date.getDate() : o.date.getDate();
                var m                   = ((o.date.getMonth() + 1) < 10) ? "0" + (o.date.getMonth() + 1) : o.date.getMonth() + 1;
                var yyyy                = o.date.getFullYear();
                var disabledDates       = o.getDisabledDates(yyyy, m);
                var weekDay             = ( o.date.getDay() + 6 ) % 7;

                if(!(o.disableDays[weekDay] || String(yyyy)+m+d in disabledDates)) {

                        if(o.splitDate) {
                                var ddE = document.getElementById(o.id+"-dd");
                                var mmE = document.getElementById(o.id+"-mm");

                                if(ddE.tagName.toLowerCase() == "input") { ddE.value = d; }
                                else { o.setSelectIndex(ddE, d); /*ddE.selectedIndex = d - 1;*/ };
                                
                                if(mmE.tagName.toLowerCase() == "input") { mmE.value = m; }
                                else { o.setSelectIndex(mmE, m); /*mmE.selectedIndex = m - 1;*/ };
                                
                                if(elem.tagName.toLowerCase() == "input") elem.value = yyyy;
                                else {
                                        o.setSelectIndex(elem, yyyy); /*
                                        for(var opt = 0; opt < elem.options.length; opt++) {
                                                if(elem.options[opt].value == yyyy) {
                                                        elem.selectedIndex = opt;
                                                        break;
                                                };
                                        };
                                        */
                                };
                        } else {
                                elem.value = o.format.replace('y',yyyy).replace('m',m).replace('d',d).replace(/-/g,o.divider);
                        };
                        if(!elem.type || elem.type && elem.type != "hidden"){ elem.focus(); }
                        if(o.staticPos) {
                                o.dateSet = new Date( o.date );
                                o.updateTable();
                        };
                        
                        // Programmatically fire the onchange event
                        if(document.createEvent) {
                                var onchangeEvent = document.createEvent('HTMLEvents');
                                onchangeEvent.initEvent('change', true, false);
                                elem.dispatchEvent(onchangeEvent);
                        } else if(document.createEventObject) {
                                elem.fireEvent('onchange');
                        };
                };
        };
        o.disableTodayButton = function() {
                var today = new Date();
                document.getElementById(o.id + "-today-but").className = document.getElementById(o.id + "-today-but").className.replace("fd-disabled", "");
                if(o.outOfRange(today) || (o.date.getDate() == today.getDate() && o.date.getMonth() == today.getMonth() && o.date.getFullYear() == today.getFullYear())) {
                        document.getElementById(o.id + "-today-but").className += " fd-disabled";
                        document.getElementById(o.id + "-today-but").onclick = null;
                } else {
                        document.getElementById(o.id + "-today-but").onclick = o.events.gotoToday;
                };
        };
        o.updateTableHeaders = function() {
                var d, but;
                var ths = o.ths;
                for ( var y = 0; y < 7; y++ ) {
                        d = (o.firstDayOfWeek + y) % 7;
                        ths[y].title = datePicker.fullDay[d];

                        if(y > 0) {
                                but = ths[y].getElementsByTagName("span")[0];
                                but.removeChild(but.firstChild);
                                but.appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                                but.title = datePicker.fullDay[d];
                                but = null;
                        } else {
                                ths[y].removeChild(ths[y].firstChild);
                                ths[y].appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                        };
                };
                o.updateTable();
        };

        o.updateTable = function(noCallback) {

                if(o.timerSet) {
                        var d = new Date(o.date);
                        d.setDate( Math.min(d.getDate()+o.dayInc, datePicker.getDaysPerMonth(d.getMonth()+o.monthInc,d.getFullYear()+o.yearInc)) );
                        d.setMonth( d.getMonth() + o.monthInc );
                        d.setFullYear( d.getFullYear() + o.yearInc );
                        o.date = d;
                };
                
                if(!noCallback && "onupdate" in datePickerController && typeof(datePickerController.onupdate) == "function") datePickerController.onupdate(o);

                o.outOfRange();
                o.disableTodayButton();
                
                // Set the tmpDate to the second day of this month (to avoid daylight savings time madness on Windows)
                var tmpDate = new Date( o.date.getFullYear(), o.date.getMonth(), 2 );
                tmpDate.setHours(5);

                var tdm = tmpDate.getMonth();
                var tdy = tmpDate.getFullYear();

                // Do the disableDates for this year and month
                var disabledDates = o.getDisabledDates(o.date.getFullYear(), o.date.getMonth() + 1);

                var today = new Date();

                // Previous buttons out of range
                var b = document.getElementById(o.id + "-prev-year-but");
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy - 1), Number(tdm), datePicker.getDaysPerMonth(Number(tdm), tdy-1)))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == -1) o.stopTimer();
                };

                b = document.getElementById(o.id + "-prev-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, (Number(tdm) - 1), datePicker.getDaysPerMonth(Number(tdm)-1, tdy)))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == -1)  o.stopTimer();
                };

                // Next buttons out of range
                b= document.getElementById(o.id + "-next-year-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy + 1), Number(tdm), 1))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == 1)  o.stopTimer();
                };

                b = document.getElementById(o.id + "-next-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, Number(tdm) + 1, 1))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == 1)  o.stopTimer();
                };

                b = null;
                
                var cd = o.date.getDate();
                var cm = o.date.getMonth();
                var cy = o.date.getFullYear();
                
                // Title Bar
                var span = o.titleBar.getElementsByTagName("span");
                while(span[0].firstChild) span[0].removeChild(span[0].firstChild);
                while(span[1].firstChild) span[1].removeChild(span[1].firstChild);
                span[0].appendChild(document.createTextNode(datePicker.months[cm] + o.nbsp));
                span[1].appendChild(document.createTextNode(cy));

                tmpDate.setDate( 1 );
                        
                var dt, cName, td, tds, i;
                var weekDay = ( tmpDate.getDay() + 6 ) % 7;
                var firstColIndex = (( (weekDay - o.firstDayOfWeek) + 7 ) % 7) - 1;
                var dpm = datePicker.getDaysPerMonth(cm, cy);

                var todayD = today.getDate();
                var todayM = today.getMonth();
                var todayY = today.getFullYear();
                
                var c = "class";
                /*@cc_on
                @if(@_win32)
                c = "className";
                @end
                @*/

                var stub = String(tdy) + (String(tdm+1).length < 2 ? "0" + (tdm+1) : tdm+1);
                
                for(var row = 0; row < 6; row++) {

                        tds = o.trs[row].getElementsByTagName('td');

                        for(var col = 0; col < 7; col++) {
                        
                                td = tds[col];
                                td.removeChild(td.firstChild);

                                td.setAttribute("id", "");
                                td.setAttribute("title", "");

                                i = (row * 7) + col;
                        
                                if(i > firstColIndex && i <= (firstColIndex + dpm)) {
                                        dt = i - firstColIndex;

                                        tmpDate.setDate(dt);
                                        td.appendChild(document.createTextNode(dt));
                                        
                                        if(o.outOfRange(tmpDate)) {
                                                td.setAttribute(c, "out-of-range");
                                        } else {

                                                cName = [];
                                                weekDay = ( tmpDate.getDay() + 6 ) % 7;

                                                if(dt == todayD && tdm == todayM && tdy == todayY) {
                                                        cName.push("date-picker-today");
                                                };

                                                if(o.dateSet != null && o.dateSet.getDate() == dt && o.dateSet.getMonth() == tdm && o.dateSet.getFullYear() == tdy) {
                                                        cName.push("date-picker-selected-date");
                                                };
                                                
                                                if(o.disableDays[weekDay] || stub + String(dt < 10 ? "0" + dt : dt) in disabledDates) {
                                                        cName.push("day-disabled");
                                                } else if(o.highlightDays[weekDay]) {
                                                        cName.push("date-picker-highlight");
                                                };
                                                
                                                if(cd == dt) {
                                                        td.setAttribute("id", o.id + "-date-picker-hover");
                                                        cName.push("date-picker-hover");
                                                };
                                                
                                                cName.push("dm-" + dt + '-' + (tdm + 1) + " " + " dmy-" + dt + '-' + (tdm + 1) + '-' + tdy);
                                                td.setAttribute(c, cName.join(' '));
                                                td.setAttribute("title", datePicker.months[cm] + o.nbsp + dt + "," + o.nbsp + cy);
                                        };
                                } else {
                                        td.appendChild(document.createTextNode(o.nbsp));
                                        td.setAttribute(c, "date-picker-unused");
                                };
                        };
                };

                if(o.timerSet) {
                        o.timerInc = 50 + Math.round(((o.timerInc - 50) / 1.8));
                        o.timer = window.setTimeout(o.updateTable, o.timerInc);
                };
        };
        o.addKeyboardEvents = function() {
                datePickerController.addEvent(document, "keypress", o.events.onkeydown);
                /*@cc_on
                @if(@_win32)
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                @end
                @*/
                if(window.devicePixelRatio) {
                        datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                        datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                };
        };
        o.removeKeyboardEvents =function() {
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.removeEvent(document, "keydown",  o.events.onkeydown);
        };
        o.show = function() {
                var elem = o.getElem();
                if(!elem || o.visible || elem.disabled) return;

                o.reset();
                o.setDateFromInput();
                o.updateTable();
                
                if(!o.staticPos) o.resize();
                
                datePickerController.addEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);

                if(!o.staticPos) { o.addKeyboardEvents(); };
                
                o.opacityTo = o.noTransparency ? 99 : 90;
                o.div.style.display = "block";
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(!o.staticPos) o.iePopUp.style.display = "block";
                @end
                @*/

                o.fade();
                o.visible = true;
        };
        o.hide = function() {
                if(!o.visible) return;
                o.stopTimer();
                if(o.staticPos) return;
                
                datePickerController.removeEvent(document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",  o.events.clearTimer);
                o.removeKeyboardEvents();
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp.style.display = "none";
                @end
                @*/
                
                o.opacityTo = 0;
                o.fade();
                o.visible = false;
                var elem = o.getElem();
                if(!elem.type || elem.type && elem.type != "hidden") { elem.focus(); };
        };
        o.destroy = function() {
                // Cleanup for Internet Explorer
                datePickerController.removeEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",   o.events.clearTimer);
                o.removeKeyboardEvents();

                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.removeEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');

                                datePickerController.removeEvent(mmN, "change", o.changeHandler);
                                datePickerController.removeEvent(ddN, "change", o.changeHandler);
                        };
                        o.div.onfocus = o.div.onblur = null;
                };
                
                var ths = o.table.getElementsByTagName("th");
                for(var i = 0, th; th = ths[i]; i++) {
                        th.onmouseover = th.onmouseout = th.onmousedown = th.onclick = null;
                };
                
                var tds = o.table.getElementsByTagName("td");
                for(var i = 0, td; td = tds[i]; i++) {
                        td.onmouseover = td.onclick = null;
                };

                var butts = o.table.getElementsByTagName("span");
                for(var i = 0, butt; butt = butts[i]; i++) {
                        butt.onmousedown = butt.onclick = butt.onkeypress = null;
                };
                
                o.ths = o.trs = null;
                
                clearTimeout(o.fadeTimer);
                clearTimeout(o.timer);
                o.fadeTimer = o.timer = null;
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp = null;
                @end
                @*/
                
                if(!o.staticPos && document.getElementById(o.id.replace(/^fd-/, 'fd-but-'))) {
                        var butt = document.getElementById(o.id.replace(/^fd-/, 'fd-but-'));
                        butt.onclick = butt.onpress = null;
                };
                
                if(o.div && o.div.parentNode) {
                        o.div.parentNode.removeChild(o.div);
                };
                
                o.titleBar = o.table = o.div = null;
                o = null;
        };
        o.create();
};

datePickerController = function() {
        var datePickers = {};
        var uniqueId    = 0;
        
        var addEvent = function(obj, type, fn) {
                if( obj.attachEvent ) {
                        obj["e"+type+fn] = fn;
                        obj[type+fn] = function(){obj["e"+type+fn]( window.event );};
                        obj.attachEvent( "on"+type, obj[type+fn] );
                } else {
                        obj.addEventListener( type, fn, true );
                };
        };
        var removeEvent = function(obj, type, fn) {
                try {
                        if( obj.detachEvent ) {
                                obj.detachEvent( "on"+type, obj[type+fn] );
                                obj[type+fn] = null;
                        } else {
                                obj.removeEventListener( type, fn, true );
                        };
                } catch(err) {};
        };
        var hideAll = function(exception) {
                var dp;
                for(dp in datePickers) {
                        if(!datePickers[dp].created || datePickers[dp].staticPos) continue;
                        if(exception && exception == datePickers[dp].id) { continue; };
                        if(document.getElementById(datePickers[dp].id))  { datePickers[dp].hide(); };
                };
        };
        var cleanUp = function() {
                var dp;
                for(dp in datePickers) {
			datePickers[dp].destroy();
			datePickers[dp] = null;
			delete datePickers[dp];
                };
        };
        var destroy = function() {
                for(dp in datePickers) {
                        if(!datePickers[dp].created) continue;
                        datePickers[dp].destroy();
                        datePickers[dp] = null;
                        delete datePickers[dp];
                };
                datePickers = null;
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(document.getElementById("iePopUpHack")) {
                                document.body.removeChild(document.getElementById("iePopUpHack"));
                        };
                @end
                @*/
                datePicker.script = null;
                removeEvent(window, 'load', datePickerController.create);
                removeEvent(window, 'unload', datePickerController.destroy);
        };
        var dateFormat = function(dateIn, favourMDY) {
                var dateTest = [
                        { regExp:/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, d:1, m:3, y:5 },  // dmy
                        { regExp:/^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, d:3, m:1, y:5 },  // mdy
                        { regExp:/^(\d\d\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/,    d:5, m:3, y:1 }   // ymd
                        ];

                var start;
                var cnt = 0;
                while(cnt < 3) {
                        start = (cnt + (favourMDY ? 4 : 3)) % 3;
                        if(dateIn.match(dateTest[start].regExp)) {
                                res = dateIn.match(dateTest[start].regExp);
                                y = res[dateTest[start].y];
                                m = res[dateTest[start].m];
                                d = res[dateTest[start].d];
                                if(m.length == 1) m = "0" + m;
                                if(d.length == 1) d = "0" + d;
                                if(y.length != 4) y = (parseInt(y) < 50) ? '20' + y : '19' + y;
                                return String(y)+m+d;
                        };
                        cnt++;
                };
                return 0;
        };
        var joinNodeLists = function() {
                if(!arguments.length) { return []; }
                var nodeList = [];
                for (var i = 0; i < arguments.length; i++) {
                        for (var j = 0, item; item = arguments[i][j]; j++) {
                                nodeList[nodeList.length] = item;
                        };
                };
                return nodeList;
        };
        var addDatePicker = function(inpId, options) {
                if(!(inpId in datePickers)) {
                        datePickers[inpId] = new datePicker(options);
                };
        };
        var getDatePicker = function(inpId) {
                if(!(inpId in datePickers)) { throw "No datePicker has been created for the form element with an id of '" + inpId.toString() + "'"; };
                return datePickers[inpId];
        };
        var grepRangeLimits = function(sel) {
                var range = [];
                for(var i = 0; i < sel.options.length; i++) {
                        if(sel.options[i].value.search(/^\d\d\d\d$/) == -1) { continue; };
                        if(!range[0] || Number(sel.options[i].value) < range[0]) { range[0] = Number(sel.options[i].value); };
                        if(!range[1] || Number(sel.options[i].value) > range[1]) { range[1] = Number(sel.options[i].value); };
                };
                return range;
        };
        var create = function(inp) {
                if(!(typeof document.createElement != "undefined" && typeof document.documentElement != "undefined" && typeof document.documentElement.offsetWidth == "number")) return;

                var inputs  = (inp && inp.tagName) ? [inp] : joinNodeLists(document.getElementsByTagName('input'), document.getElementsByTagName('select'));
                var regExp1 = /disable-days-([1-7]){1,6}/g;             // the days to disable
                var regExp2 = /no-transparency/g;                       // do not use transparency effects
                var regExp3 = /highlight-days-([1-7]){1,7}/g;           // the days to highlight in red
                var regExp4 = /range-low-(\d\d\d\d-\d\d-\d\d)/g;        // the lowest selectable date
                var regExp5 = /range-high-(\d\d\d\d-\d\d-\d\d)/g;       // the highest selectable date
                var regExp6 = /format-(d-m-y|m-d-y|y-m-d)/g;            // the input/output date format
                var regExp7 = /divider-(dot|slash|space|dash)/g;        // the character used to divide the date
                var regExp8 = /no-locale/g;                             // do not attempt to detect the browser language
                var regExp9 = /no-fade/g;                               // always show the datepicker
                var regExp10 = /hide-input/g;                           // hide the input
                
                for(var i=0, inp; inp = inputs[i]; i++) {
                        if(inp.className && (inp.className.search(regExp6) != -1 || inp.className.search(/split-date/) != -1) && ((inp.tagName.toLowerCase() == "input" && (inp.type == "text" || inp.type == "hidden")) || inp.tagName.toLowerCase() == "select")) {

                                
                                if(!inp.id) { inp.id = "fdDatePicker-" + uniqueId++; };
                                
                                var options = {
                                        id:inp.id,
                                        low:"",
                                        high:"",
                                        divider:"/",
                                        format:"d-m-y",
                                        highlightDays:[0,0,0,0,0,1,1],
                                        disableDays:[0,0,0,0,0,0,0],
                                        locale:inp.className.search(regExp8) == -1,
                                        splitDate:0,
                                        noTransparency:inp.className.search(regExp2) != -1,
                                        staticPos:inp.className.search(regExp9) != -1,
                                        hideInput:inp.className.search(regExp10) != -1
                                };

                                if(!options.staticPos) {
                                        options.hideInput = false;
                                } else {
                                        options.noTransparency = true;
                                };
                                
                                // Split the date into three parts ?
                                if(inp.className.search(/split-date/) != -1) {
                                        if(document.getElementById(inp.id+'-dd') && document.getElementById(inp.id+'-mm') && document.getElementById(inp.id+'-dd').tagName.search(/input|select/i) != -1 && document.getElementById(inp.id+'-mm').tagName.search(/input|select/i) != -1) {
                                                options.splitDate = 1;
                                        };
                                };
                                
                                // Date format(variations of d-m-y)
                                if(inp.className.search(regExp6) != -1) {
                                        options.format = inp.className.match(regExp6)[0].replace('format-','');
                                };
                                
                                // What divider to use, a "/", "-", "." or " "
                                if(inp.className.search(regExp7) != -1) {
                                        var dividers = { dot:".", space:" ", dash:"-", slash:"/" };
                                        options.divider = (inp.className.search(regExp7) != -1 && inp.className.match(regExp7)[0].replace('divider-','') in dividers) ? dividers[inp.className.match(regExp7)[0].replace('divider-','')] : "/";
                                };

                                // The days to highlight
                                if(inp.className.search(regExp3) != -1) {
                                        var tmp = inp.className.match(regExp3)[0].replace(/highlight-days-/, '');
                                        options.highlightDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.highlightDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The days to disable
                                if(inp.className.search(regExp1) != -1) {
                                        var tmp = inp.className.match(regExp1)[0].replace(/disable-days-/, '');
                                        options.disableDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.disableDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The lower limit
                                if(inp.className.search(/range-low-today/i) != -1) {
                                        options.low = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp4) != -1) {
                                        options.low = datePickerController.dateFormat(inp.className.match(regExp4)[0].replace(/range-low-/, ''), false);
                                        if(!options.low) {
                                                options.low = '';
                                        };
                                };

                                // The higher limit
                                if(inp.className.search(/range-high-today/i) != -1 && inp.className.search(/range-low-today/i) == -1) {
                                        options.high = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp5) != -1) {
                                        options.high = datePickerController.dateFormat(inp.className.match(regExp5)[0].replace(/range-high-/, ''), false);
                                        if(!options.high) {
                                                options.high = '';
                                        };
                                };

                                // Always round lower & higher limits if a selectList involved
                                if(inp.tagName.search(/select/i) != -1) {
                                        var range = grepRangeLimits(inp);
                                        options.low  = options.low  ? range[0] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[0] + "/01/01");
                                        options.high = options.high ? range[1] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[1] + "/12/31");
                                };

                                addDatePicker(inp.id, options);
                        };
                };
        }
        
        return {
                addEvent:addEvent,
                removeEvent:removeEvent,
                create:create,
                destroy:destroy,
                cleanUp:cleanUp,
                addDatePicker:addDatePicker,
                getDatePicker:getDatePicker,
                dateFormat:dateFormat,
                datePickers:datePickers,
                hideAll:hideAll
        };
}();

})();

datePickerController.addEvent(window, 'load', datePickerController.create);
datePickerController.addEvent(window, 'unload', datePickerController.destroy);
