
function CSIShowAd(ValueHost ,
                   ValueID ,
                   ValueVersion,
                   ValueBannerType,
                   ValueNoText,
                   ValueBannerSizeOrder, 
                   ValueAID,
                   ValueWidths_Heights,
                   ValueCategory,
                   ValueHCat,
                   ValueKeyCodes) {
           var rval = ValueShowAd(ValueHost,ValueID,ValueVersion,ValueBannerType,null,ValueCategory,null,
			            null,null,null,null,ValueHCat,null,
			            null,ValueAID,null,null,null,null,null,
			            null,null,ValueBannerSizeOrder,ValueNoText,null,null,
			            null,null,null,null,null,null,ValueWidths_Heights,ValueKeyCodes);
	    var firstval = rval.indexOf('SRC="')+5;
	    //alert(firstval);
	    var temp = rval.substring(firstval);
	    //alert(temp);
	    var secondval = temp.indexOf('"')+firstval;  
	    //alert(secondval);
	    return rval.substring(firstval,secondval-2)+"html";
}


function ValueShowAd(	
            paramValueHost,
            paramValueID,
            paramValueVersion,
			paramValueBannerType,
			paramValueSecure,
			paramValueCategory,
			paramValueBorder,
			paramValuePlacement,
			paramValueKWParam,
			paramValueKeywords,
			paramValueKeyCode,
			paramValueHCat,
			paramValuePBhav,
			paramValueTagCascade,
			paramValueAID,
			paramValuePID,
			paramcontentURL,
			paramValueFeed,
			paramValueWidth,
			paramValueHeight,
			paramValueIFrame,
			paramValueIFrameMSizes,
			paramValueBannerSizeOrder,
			paramValueNoText,
			paramValueTargetCurrent,
			paramValueCacheBanners,
			paramValueServer,
			paramValueBgColor,
			paramValueLinkColor,
			paramValueAlinkColor,
			paramValueVlinkColor,
			paramValueVersion,
			paramValueWidths_Heights,
			paramValueKeyCodes) {
			
  ValueFullVersion = paramValueVersion + ".20";
  ValueOptions = '&v=' + ValueFullVersion;
  ValueFullOptions = '';
  ValueTextTest = 0;
  ValueProtocol = "http://";
  ValueBannerType = paramValueBannerType || "js";
  ValueNetworkDisableNoCache = 0 || 0; 

  if (paramValueSecure) ValueProtocol = "https://";
  if (paramValueCategory) ValueOptions += '&c=' + paramValueCategory;
  if (paramValueBorder)   ValueOptions += '&border=1';
  if (paramValuePlacement) ValueFullOptions += '&p=' + paramValuePlacement; 
  if (paramValueKWParam)  ValueOptions += '&r=' + paramValueKWParam;
  if (paramValueKeywords) ValueOptions += '&k=' + escape(paramValueKeywords);
  if (paramValueKeyCode) ValueOptions += '&' + paramValueKeyCode;
  if (paramValueHCat) ValueOptions += '&hcat=' + paramValueHCat;
  if (paramValuePBhav) ValueOptions += '&pbhav=' + paramValuePBhav;
  if (paramValueTagCascade) ValueOptions += '&tc=' + paramValueTagCascade;
  if (paramValueAID) ValueFullOptions += '&aid=' + paramValueAID;
  if (paramValuePID) ValueFullOptions += '&pid=' + paramValuePID;
  if (paramcontentURL) ValueOptions += '&getvid=1';
  if (paramValueFeed) ValueOptions += '&feed=' + paramValueFeed;

  if (paramValueKeyCodes) {
    var tempKC = paramValueKeyCodes.join("&"); 
    ValueOptions += '&' + tempKC;
  }

  ValueSizes = '';
  HardSize = 1;

  if (paramValueWidth) {
    ValueWidth = paramValueWidth;
  } else {
    ValueWidth = '';
  }

  if (paramValueHeight) {
    ValueHeight = paramValueHeight;
  } else {
    ValueHeight = '';
  }

  ValueIFrame = paramValueIFrame || 0;
  ValueIFrameMSizes = paramValueIFrameMSizes || 0;

  if (ValueBannerType != 'pop') {

    //non pops should default to type js
    ValueBannerType = 'js';

    //if 'Width' and 'Height' are passed in, use them
    //otherwise, use Width_Height if it exists

    if (ValueWidth && ValueHeight) {
      ValueSizes = '&size=' + ValueWidth + 'x' + ValueHeight;
    } else if (paramValueWidths_Heights) {
      if (ValueIFrame) {
        //Using IFrame will normally disable using MSizes, but an optional
        //parameter IFrameMSizes allows them both to be used.
        var firstSize = paramValueWidths_Heights[0];
        if (ValueIFrameMSizes) {
          ValueSizes = '&msizes=' + paramValueWidths_Heights.join(",");
        } else {
          ValueSizes = '&size=' + firstSize;
        }
        //Set Width & Height for the IFrame
        var firstSizeArray = firstSize.split('x');
        ValueWidth = firstSizeArray[0];
        ValueHeight = firstSizeArray[1];
      } else {
        var ArLen = paramValueWidths_Heights.length;
        if (ArLen > 1) HardSize = 0;

        ValueSizes = '&msizes=' + paramValueWidths_Heights.join(",");
      }
    } else {
      //if no size info is passed in, the size list from host site record or network is used
      //so we can't predict the size
      HardSize = 0;
    }
    
    if (paramValueBannerSizeOrder) ValueFullOptions += '&bso=' + paramValueBannerSizeOrder;

    //Do not show text for non-standard banners. ValueNoText must come after this test.
    if (ValueWidth == 468 && ValueHeight == 60) {
      ValueTextTest = 0;
    }else {
      if(! paramValueNoText) ValueTextTest = 1; 
      paramValueNoText = true;
    }

    if (! paramValueNoText) ValueOptions += '&text=1';
    if (paramValueTargetCurrent) ValueOptions += '&target=self';
  } else {
    ValueSizes = '&size=' + self.ValuePopSize;
  }

  ValueRandom   = Math.round(Math.random()*1000) + 1;
  ValueTempDisableNoCache = 0;

  if (ValueNetworkDisableNoCache) {
    ValueTempDisableNoCache = 1;
  }

  //Publisher setting overrides the network setting
  if (paramValueCacheBanners && paramValueCacheBanners == 'yes') {
    ValueTempDisableNoCache = 1;
  } else if (paramValueCacheBanners && paramValueCacheBanners == 'no') {
    ValueTempDisableNoCache = 2;
  }

  if (ValueTempDisableNoCache == 1) {
    //don't send no-cache headers 
    ValueRandom = 1;
    ValueOptions += '&disable_no_cache=1';
  } else if (ValueTempDisableNoCache == 2) {
    //send no-cache headers 
    ValueOptions += '&disable_no_cache=0';
  }

  ValueHostInfo = "host=" + paramValueHost + "&b=" + paramValueID + "." + ValueRandom;

  if (paramValueServer == null) ValueServer = "ads";

  ValueFullServer   = ValueProtocol + ValueServer + ".csi.valueclick.net/";

  ValueBanner   = ValueFullServer + 'cycle?' + ValueHostInfo + ValueOptions + ValueFullOptions + ValueSizes;

  if (ValueBannerType == 'js' && HardSize) ValueDimensions(paramValueNoText,paramValueBorder);

  // blank then out so they will only apply for this request. 
  // When there are multiple tags on the same page, we don't want an old
  // tag with these variables to 'infect' a newer tag that doesn't
  // use these variables
  ValueWidth = '';
  ValueHeight = '';

  if (ValueTextTest == 1) paramValueNoText = false;

  var urltogoto = "";
  if (navigator.userAgent.indexOf("MSIE") >= 0) {
    // don't try to set the bgcolor etc in the IFRAME for MSIE 3 
    if (navigator.appVersion.indexOf('MSIE 3') < 0) {
      if (paramValueBgColor)    ValueBanner += '&bgcolor='    + escape(paramValueBgColor);
      if (paramValueLinkColor)  ValueBanner += '&linkcolor='  + escape(paramValueLinkColor);
      if (paramValueAlinkColor) ValueBanner += '&alinkcolor=' + escape(paramValueAlinkColor);
      if (paramValueVlinkColor) ValueBanner += '&vlinkcolor=' + escape(paramValueVlinkColor);
    }
    if (ValueIFrame == 1 && ValueBannerType == 'js') {
      if (HardSize) {
        urltogoto += '<IFRAME ID="VC" NAME="VC" WIDTH="' + IWidth + '" HEIGHT="' + IHeight + '" ';
      } else {
        urltogoto += '<IFRAME ID="VC" NAME="VC" ';
      }
      urltogoto += 'SCROLLING="no" FRAMEBORDER="0" FRAMESPACING="0" MARGINHEIGHT="0" ';
      urltogoto += 'MARGINWIDTH="0" BORDER="0" HSPACE="0" VSPACE="0" ';
      urltogoto += 'ALIGN="center" SRC="' + ValueBanner + '&t=html">';
      urltogoto += '</IFRAME>';
    } else {
      urltogoto += '<SCRIPT SRC="' + ValueBanner + '&t=' + ValueBannerType + '"';
      urltogoto += ' LANGUAGE="JavaScript"></SCR' + 'IPT>';
    }
  } else {
    // should be all Netscapes that are reading this file 
    if (paramValueVersion == 1.0 && parseInt(navigator.appVersion) < 5 ) {
      urltogoto += '<table border=0 cellpadding=0 cellspacing=0><tr><td>';
      if (HardSize) {
        urltogoto += '<ILAYER ID="VC" VISIBILITY="hide" BGCOLOR="" WIDTH="' + IWidth;
        urltogoto += '" HEIGHT="' + IHeight + '"></ILAYER>';
      } else {
        urltogoto += '<ILAYER ID="VC" VISIBILITY="hide" BGCOLOR="" ';
        urltogoto += '></ILAYER>';
      }
      urltogoto += '</td></tr></table>';
    } else {
      urltogoto += '<SCRIPT SRC="' + ValueBanner + '&t=' + ValueBannerType + '"';
      urltogoto += ' LANGUAGE="JavaScript"></SCR' + 'IPT>';
    }
  }
  return urltogoto;
}

function ValueDimensions(paramValueNoText,paramValueBorder) {
  if (paramValueNoText) {
    if (paramValueBorder) {
      IWidth  = ValueWidth + 4;  
      IHeight = ValueHeight + 4;
    } else {
      IWidth  = ValueWidth;  
      IHeight = ValueHeight;
    }       
  } else {
    if (paramValueBorder) {
      IWidth  = ValueWidth + 4;
      IHeight = ValueHeight + 24;
    } else {
      IWidth  = ValueWidth;
      IHeight = ValueHeight + 24;
    }       
  }
}/*! Copyright (c) 2008 Brandon Aaron (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.
 *
 * Version: 1.0.3
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {
	
$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});
		
		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);
		
		// Make sure it is running
		q.stopped = false;
		
		// Run it immediately for the first time
		q.run();
		
		// Contnue the chain
		return this;
	},
	
	expire: function(type, fn, fn2) {
		var self = this;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context && 
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});
		
		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context || document;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;
	
	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;
	
	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;
	
	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;
		
		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});
			
		// Clear out matched elements
		this.elements = [];
		
		// Stop the Live Query from running until restarted
		this.stopped = true;
	},
	
	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;
		
		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);
		
		// Set elements to the latest set of matched elements
		this.elements = els;
		
		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);
			
			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});
			
			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,
	
	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},
	
	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},
	
	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},
	
	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;
			
			// Save a reference to the original method
			var old = $.fn[n];
			
			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);
				
				// Request a run of the Live Queries
				$.livequery.run();
				
				// Return the original methods result
				return r;
			}
		});
	},
	
	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});
		
		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},
	
	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });


// Save a reference to the original init method
var init = $.prototype.init;

// Create a new init method that exposes two new properties: selector and context
$.prototype.init = function(a,c) {
	// Call the original init and save the result
	var r = init.apply(this, arguments);
	
	// Copy over properties if they exist already
	if (a && a.selector)
		r.context = a.context, r.selector = a.selector;
		
	// Set properties
	if ( typeof a == 'string' )
		r.context = c || document, r.selector = a;
	
	// Return the result
	return r;
};

// Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
$.prototype.init.prototype = $.prototype;
	
})(jQuery);/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "/images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


/*
 *
 * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Version 2.2.1
 * Demo: http://www.texotela.co.uk/code/jquery/select/
 *
 * $LastChangedDate: 2007-12-14 17:07:30 +0000 (Fri, 14 Dec 2007) $
 * $Rev: 4156 $
 *
 */
 
(function($) {
 
/**
 * Adds (single/multiple) options to a select box (or series of select boxes)
 *
 * @name     addOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @example  $("#myselect").addOption("Value", "Text"); // add single value (will be selected)
 * @example  $("#myselect").addOption("Value 2", "Text 2", false); // add single value (won't be selected)
 * @example  $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add multiple values, but don't select
 *
 */
$.fn.addOption = function()
{
	var add = function(el, v, t, sO)
	{
		var option = document.createElement("option");
		option.value = v, option.text = t;
		// get options
		var o = el.options;
		// get number of options
		var oL = o.length;
		if(!el.cache)
		{
			el.cache = {};
			// loop through existing options, adding to cache
			for(var i = 0; i < oL; i++)
			{
				el.cache[o[i].value] = i;
			}
		}
		// add to cache if it isn't already
		if(typeof el.cache[v] == "undefined") el.cache[v] = oL;
		el.options[el.cache[v]] = option;
		if(sO)
		{
			option.selected = true;
		}
	};
	
	var a = arguments;
	if(a.length == 0) return this;
	// select option when added? default is true
	var sO = true;
	// multiple items
	var m = false;
	// other variables
	var items, v, t;
	if(typeof(a[0]) == "object")
	{
		m = true;
		items = a[0];
	}
	if(a.length >= 2)
	{
		if(typeof(a[1]) == "boolean") sO = a[1];
		else if(typeof(a[2]) == "boolean") sO = a[2];
		if(!m)
		{
			v = a[0];
			t = a[1];
		}
	}
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			if(m)
			{
				for(var item in items)
				{
					add(this, item, items[item], sO);
				}
			}
			else
			{
				add(this, v, t, sO);
			}
		}
	);
	return this;
};

/**
 * Add options via ajax
 *
 * @name     ajaxAddOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String url      Page to get options from (must be valid JSON)
 * @param    Object params   (optional) Any parameters to send with the request
 * @param    Boolean select  (optional) Select the added options, default true
 * @param    Function fn     (optional) Call this function with the select object as param after completion
 * @param    Array args      (optional) Array with params to pass to the function afterwards
 * @example  $("#myselect").ajaxAddOption("myoptions.php");
 * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"});
 * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"}, false, sortoptions, {"dir": "desc"});
 *
 */
$.fn.ajaxAddOption = function(url, params, select, fn, args)
{
	if(typeof(url) != "string") return this;
	if(typeof(params) != "object") params = {};
	if(typeof(select) != "boolean") select = true;
	this.each(
		function()
		{
			var el = this;
			$.getJSON(url,
				params,
				function(r)
				{
					$(el).addOption(r, select);
					if(typeof fn == "function")
					{
						if(typeof args == "object")
						{
							fn.apply(el, args);
						} 
						else
						{
							fn.call(el);
						}
					}
				}
			);
		}
	);
	return this;
};

/**
 * Removes an option (by value or index) from a select box (or series of select boxes)
 *
 * @name     removeOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String|RegExp|Number what  Option to remove
 * @param    Boolean selectedOnly       (optional) Remove only if it has been selected (default false)   
 * @example  $("#myselect").removeOption("Value"); // remove by value
 * @example  $("#myselect").removeOption(/^val/i); // remove options with a value starting with 'val'
 * @example  $("#myselect").removeOption(/./); // remove all options
 * @example  $("#myselect").removeOption(/./, true); // remove all options that have been selected
 * @example  $("#myselect").removeOption(0); // remove by index
 *
 */
$.fn.removeOption = function()
{
	var a = arguments;
	if(a.length == 0) return this;
	var ta = typeof(a[0]);
	var v, index;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(ta == "string" || ta == "object" || ta == "function" ) v = a[0];
	else if(ta == "number") index = a[0];
	else return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			// clear cache
			if(this.cache) this.cache = null;
			// does the option need to be removed?
			var remove = false;
			// get options
			var o = this.options;
			if(!!v)
			{
				// get number of options
				var oL = o.length;
				for(var i=oL-1; i>=0; i--)
				{
					if(v.constructor == RegExp)
					{
						if(o[i].value.match(v))
						{
							remove = true;
						}
					}
					else if(o[i].value == v)
					{
						remove = true;
					}
					// if the option is only to be removed if selected
					if(remove && a[1] === true) remove = o[i].selected;
					if(remove)
					{
						o[i] = null;
					}
					remove = false;
				}
			}
			else
			{
				// only remove if selected?
				if(a[1] === true)
				{
					remove = o[index].selected;
				}
				else
				{
					remove = true;
				}
				if(remove)
				{
					this.remove(index);
				}
			}
		}
	);
	return this;
};

/**
 * Sort options (ascending or descending) in a select box (or series of select boxes)
 *
 * @name     sortOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    Boolean ascending   (optional) Sort ascending (true/undefined), or descending (false)
 * @example  // ascending
 * $("#myselect").sortOptions(); // or $("#myselect").sortOptions(true);
 * @example  // descending
 * $("#myselect").sortOptions(false);
 *
 */
$.fn.sortOptions = function(ascending)
{
	var a = typeof(ascending) == "undefined" ? true : !!ascending;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			// create an array for sorting
			var sA = [];
			// loop through options, adding to sort array
			for(var i = 0; i<oL; i++)
			{
				sA[i] = {
					v: o[i].value,
					t: o[i].text
				}
			}
			// sort items in array
			sA.sort(
				function(o1, o2)
				{
					// option text is made lowercase for case insensitive sorting
					o1t = o1.t.toLowerCase(), o2t = o2.t.toLowerCase();
					// if options are the same, no sorting is needed
					if(o1t == o2t) return 0;
					if(a)
					{
						return o1t < o2t ? -1 : 1;
					}
					else
					{
						return o1t > o2t ? -1 : 1;
					}
				}
			);
			// change the options to match the sort array
			for(var i = 0; i<oL; i++)
			{
				o[i].text = sA[i].t;
				o[i].value = sA[i].v;
			}
		}
	);
	return this;
};
/**
 * Selects an option by value
 *
 * @name     selectOptions
 * @author   Mathias Bank (http://www.mathias-bank.de), original function
 * @author   Sam Collett (http://www.texotela.co.uk), addition of regular expression matching
 * @type     jQuery
 * @param    String|RegExp value  Which options should be selected
 * can be a string or regular expression
 * @param    Boolean clear  Clear existing selected options, default false
 * @example  $("#myselect").selectOptions("val1"); // with the value 'val1'
 * @example  $("#myselect").selectOptions(/^val/i); // with the value starting with 'val', case insensitive
 *
 */
$.fn.selectOptions = function(value, clear)
{
	var v = value;
	var vT = typeof(value);
	var c = clear || false;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(v.constructor == RegExp)
				{
					if(o[i].value.match(v))
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
				else
				{
					if(o[i].value == v)
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
			}
		}
	);
	return this;
};

/**
 * Copy options to another select
 *
 * @name     copyOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String to  Element to copy to
 * @param    String which  (optional) Specifies which options should be copied - 'all' or 'selected'. Default is 'selected'
 * @example  $("#myselect").copyOptions("#myselect2"); // copy selected options from 'myselect' to 'myselect2'
 * @example  $("#myselect").copyOptions("#myselect2","selected"); // same as above
 * @example  $("#myselect").copyOptions("#myselect2","all"); // copy all options from 'myselect' to 'myselect2'
 *
 */
$.fn.copyOptions = function(to, which)
{
	var w = which || "selected";
	if($(to).size() == 0) return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(w == "all" ||	(w == "selected" && o[i].selected))
				{
					$(to).addOption(o[i].value, o[i].text);
				}
			}
		}
	);
	return this;
};

/**
 * Checks if a select box has an option with the supplied value
 *
 * @name     containsOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     Boolean|jQuery
 * @param    String|RegExp value  Which value to check for. Can be a string or regular expression
 * @param    Function fn          (optional) Function to apply if an option with the given value is found.
 * Use this if you don't want to break the chaining
 * @example  if($("#myselect").containsOption("val1")) alert("Has an option with the value 'val1'");
 * @example  if($("#myselect").containsOption(/^val/i)) alert("Has an option with the value starting with 'val'");
 * @example  $("#myselect").containsOption("val1", copyoption).doSomethingElseWithSelect(); // calls copyoption (user defined function) for any options found, chain is continued
 *
 */
$.fn.containsOption = function(value, fn)
{
	var found = false;
	var v = value;
	var vT = typeof(v);
	var fT = typeof(fn);
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return fT == "function" ? this: found;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// option already found
			if(found && fT != "function") return false;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(v.constructor == RegExp)
				{
					if (o[i].value.match(v))
					{
						found = true;
						if(fT == "function") fn.call(o[i]);
					}
				}
				else
				{
					if (o[i].value == v)
					{
						found = true;
						if(fT == "function") fn.call(o[i]);
					}
				}
			}
		}
	);
	return fT == "function" ? this : found;
};

/**
 * Returns values which have been selected
 *
 * @name     selectedValues
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     Array
 * @example  $("#myselect").selectedValues();
 *
 */
$.fn.selectedValues = function()
{
	var v = [];
	this.find("option:selected").each(
		function()
		{
			v[v.length] = this.value;
		}
	);
	return v;
};

})(jQuery);//FUNCTION: isNumberKey(event evt)
//
//Attach to keypress event to allow only numeric entries
// <TAG onkeypress="return isNumberKey(event)"></TAG>
function isNumberKey(evt)
{
 var charCode = (evt.which) ? evt.which : event.keyCode
 if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;

 return true;
}

/*
 * **********************************************************
 * jQValidation
 * **********************************************************
*/
var	RULE_REQUIRED 	        = 1;
var RULE_REGEX		        = 2;
var RULE_COMPARE	        = 3;
var RULE_NUMERIC_MIN        = 4;
var RULE_CUSTOM_FN          = 5;

var REGEX_ZIPCODE           = /^\d{5}([\-]\d{4})?$/;
var REGEX_EMAIL             = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i ;
var REGEX_PHONE             = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
var REGEX_PHONE_DASH_ONLY   = /^\d{3}\-\d{3}\-\d{4}$/;
var REGEX_DATE	            = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

var REGEX_CC_ALL            = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/;
var REGEX_CC_VISA           = /^4[0-9]{12}(?:[0-9]{3})?$/;
var REGEX_CC_MC             = /^5[1-5][0-9]{14}$/;
var REGEX_CC_AMEX           = /^3[47][0-9]{13}$/;
var REGEX_CC_DINERS         = /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/;
var REGEX_CC_DISCOVER       = /^6(?:011|5[0-9]{2})[0-9]{12}$/;
var REGEX_CC_JCB            = /^(?:2131|1800|35\d{3})\d{11}$/;


getFaceBoxObject = function(cssClass) {
    if (cssClass) return ($('.'+cssClass).length >= 0 ? $($('.'+cssClass)[$('.'+cssClass).length-1]) : null);
    else return null;
};

getFaceBoxElement = function(cssClass) {
    if (cssClass) return ($('.'+cssClass).length > 0 ? $($('.'+cssClass)[$('.'+cssClass).length-1])[0] : null);
    else return null;
};
/*	
	***************************************************
	*jQValidationRule
	***************************************************
*/
jQValidationRule.prototype 				= new Object();
jQValidationRule.prototype.elementId 		= null;
jQValidationRule.prototype.type			= null;
jQValidationRule.prototype.errorMessage 	= null;
jQValidationRule.prototype.data			= null;
jQValidationRule.prototype.errorMessageElementId = null;
jQValidationRule.prototype.jQValidationMethod = null;
jQValidationRule.prototype.getElement 	= function()
	{
		return getFaceBoxElement( this.elementId );
	};
jQValidationRule.prototype.getErrorMessageElement = function()
    {
        return getFaceBoxElement( this.errorMessageElementId );
    };
jQValidationRule.prototype.isValid 		= function()
	{
		var ele = this.getElement();
		var valid = false;
		
		if( ele )
		{
			switch( ele.tagName )
			{
				case 'INPUT':
					
					switch( ele.type.toLowerCase() )
					{
						case 'text':
						case 'password':
						case 'hidden':
						case 'checkbox':
							valid = true;
							break;
					}
					break;
					
				case 'TEXTAREA':
					valid = true;
					break;
			}
		}
		
		return valid;
	};
	
jQValidationRule.prototype.getValue       = function()
    {
        if( !this.isValid() )
            return;
            
        var ele     = this.getElement();
        var value;
        
        switch( ele.tagName )
        {
            case 'INPUT':
				switch( ele.type.toLowerCase() )
				{
					case 'text':
					case 'password':
					case 'hidden':
					    value = ele.value;
					    break;
					    
					case 'checkbox':
                        value = ele.checked ? 'true' : '';
                        break;
				}
				break;
				
            case 'TEXTAREA':
                value = ele.value;
                break;
        }
        
        return value;
    };
	
function jQValidationRule( eleId, ruleType, errMsg, data, errMsgEleId )
	{
		this.elementId = eleId;
		this.type = ruleType;
		this.errorMessage = errMsg;
		this.data = data;
		this.errorMessageElementId = errMsgEleId;
	}
	
/*	
	***************************************************
	*jQValidator
	***************************************************
*/
jQValidator.prototype						= new Object();
jQValidator.prototype.rules 				= null;
jQValidator.prototype.errors              = null;
jQValidator.prototype.containerId			= null;
jQValidator.prototype.listId				= null;
jQValidator.prototype.cssError			= null;
jQValidator.prototype.cssErrorElement		= null;
jQValidator.prototype.validateRule		= function(rule)
	{

		if( !rule )
			return true;
			
		var isValid = true;	
		var evaluated = true;
		
		if( rule.isValid() )
		{
			var ele = rule.getElement();
			var eleErrMsg = rule.getErrorMessageElement();
			var value = rule.getValue();
			
			
			switch( rule.type )
			{
				case RULE_REQUIRED:
					isValid = ( value.length > 0 );
					break;
					
				case RULE_REGEX:
				    if( ele.value.length > 0 )
				    {
					    isValid = ( value.match( rule.data ) );
					}
					else
					{
					    evaluated = false;
					}   
					break;
					
				case RULE_COMPARE:
					var otherControl = getFaceBoxElement( rule.data );
					isValid = ( otherControl.value.toLowerCase() == value.toLowerCase() );
					break;
				
				case RULE_NUMERIC_MIN:
				    var number  = parseInt( value );
				    var min     = parseInt( rule.data );
				    
				    isValid = ( number > min );
				    break;
				case RULE_CUSTOM_FN:
				    isValid = ( rule.jQValidationMethod(value) == true);
				    break;
			}
		
			if( evaluated )
			{
			    if (isValid) 
			        $(ele).removeClass('form-errors');
			    else 
			        $(ele).addClass('form-errors');
			    
			    if( eleErrMsg )
			        eleErrMsg.innerHTML = isValid ? '' : rule.errorMessage;
			}
		}
		
		return isValid;
	};
jQValidator.prototype.validate	= function()
	{
		if( !this.rules )
			return true;
			
		var errors = new Array();
		
		var divContainer	= getFaceBoxElement( this.containerId );
		var ul				= getFaceBoxElement( this.listId );
		var hasErrors		= false;
		
			
		//hide error container
		
		if( divContainer)
		{
		    divContainer.style.display 	= 'none';
		    divContainer.className 		= '';
		}
		
		//clear children		
		if( ul )
		    ul.innerHTML = '';

		
		
		for( i = 0; i < this.rules.length; i++)
		{
			var rule = this.rules[i];
			if( !this.validateRule( rule ) )
			{
			    //save rule that errored out
			    errors.push( rule );
			    
			    if( ul )
			    {
				    var li = document.createElement('li');
				    li.innerHTML = rule.errorMessage;				
				    ul.appendChild( li );
                }
                
				hasErrors = true;
			}
		}
		
		//show error container
		if( divContainer &&  hasErrors )
		{
			divContainer.className		= this.cssError;		
			divContainer.style.display 	= 'block';
		}
		
		//save errors to class
		this.errors = errors;
		
		return !hasErrors;
	};
function jQValidator( container, list , cssContainer, cssElement )
	{
		this.rules 				= new Array();
		this.cssError 			= cssContainer;
		this.cssErrorElement	= cssElement;
		this.containerId		= container;
		this.listId				= list;
		
	}
	

/*
 * The following class returns information about errors back to the server
 */
jQValidationReporting.prototype = new Object();
jQValidationReporting.prototype.destinationUrl = null;
jQValidationReporting.prototype.sourceName     = null;
jQValidationReporting.prototype.additionalParameters = null;
jQValidationReporting.prototype.elementId = null;
jQValidationReporting.prototype.parentId  = null;
jQValidationReporting.prototype.errors    = null;
jQValidationReporting.prototype.element = function()
    {
        return getFaceBoxElement( this.elementId );
    };
    
jQValidationReporting.prototype.parent    = function()
    {
        return getFaceBoxElement( this.parentId );
    };
jQValidationReporting.prototype.elementExists = function()
    {
        if( this.element() && this.parent() )
        {   
            return true;
        }
        else
        {
            return false;
        }
    };
jQValidationReporting.prototype.url = function()
    {
        var baseUrl = this.destinationUrl;
         
        return baseUrl + '?' + this.getParameters();
    };

jQValidationReporting.prototype.getParameters = function()  
    {
        var params = 'Source=' + this.sourceName;
        
        for( i = 0; i < this.errors.length; i++ )
        {
            var rule = this.errors[i];
            
            params = params + '&' + rule.elementId + '=' + escape(rule.errorMessage);
        }
        
        //add any custom additional parameters
        if( this.additionalParameters )
            params+= '&' + this.additionalParameters;
            
        return params;
    };
    
jQValidationReporting.prototype.reportError = function ()
    {
        var image = this.element();
        
        if( image  )
        {
            if( this.parent() )
            {
                this.parent().removeChild( image );
            }
        }
        
        image = document.createElement('img');
        image.id = this.elementId;
        
        if( this.parent() )
        {
            this.parent().appendChild( image );
        }

        
        var url = this.url();
        image.src = this.url();
    };
    
function jQValidationReporting( parentId, elementId, destinationUrl, sourceName )
{
    this.parentId = parentId;
    this.elementId = elementId;
    this.destinationUrl = destinationUrl;
    this.sourceName = sourceName;
}


/*	SWFObject v2.0 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){
var Z="undefined",
P="object",
B="Shockwave Flash",
h="ShockwaveFlash.ShockwaveFlash",
W="application/x-shockwave-flash",
K="SWFObjectExprInst",
G=window,
g=document,
N=navigator,
f=[],
H=[],
Q=null,
L=null,
T=null,
S=false,
C=false;
var a=function()
    {
        var l=typeof g.getElementById!=Z&&typeof g.getElementsByTagName!=Z&&typeof g.createElement!=Z&&typeof g.appendChild!=Z&&typeof g.replaceChild!=Z&&typeof g.removeChild!=Z&&typeof g.cloneNode!=Z,
        t=[0,0,0],n=null;if(typeof N.plugins!=Z&&typeof N.plugins[B]==P){n=N.plugins[B].description;if(n){n=n.replace(/^.*\s+(\S+\s+\S+$)/,"$1");t[0]=parseInt(n.replace(/^(.*)\..*$/,"$1"),10);t[1]=parseInt(n.replace(/^.*\.(.*)\s.*$/,"$1"),10);t[2]=/r/.test(n)?parseInt(n.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof G.ActiveXObject!=Z){var o=null,s=false;try{o=new ActiveXObject(h+".7")}catch(k){try{o=new ActiveXObject(h+".6");t=[6,0,21];o.AllowScriptAccess="always"}catch(k){if(t[0]==6){s=true}}if(!s){try{o=new ActiveXObject(h)}catch(k){}}}if(!s&&o){try{n=o.GetVariable("$version");if(n){n=n.split(" ")[1].split(",");t=[parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10)]}}catch(k){}}}}var v=N.userAgent.toLowerCase(),j=N.platform.toLowerCase(),r=/webkit/.test(v)?parseFloat(v.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,i=false,q=j?/win/.test(j):/win/.test(v),m=j?/mac/.test(j):/mac/.test(v);/*@cc_on i=true;@if(@_win32)q=true;@elif(@_mac)m=true;@end@*/return{w3cdom:l,pv:t,webkit:r,ie:i,win:q,mac:m}}();var e=function(){if(!a.w3cdom){return }J(I);if(a.ie&&a.win){try{g.write("<script id=__ie_ondomload defer=true src=//:><\/script>");var i=c("__ie_ondomload");if(i){i.onreadystatechange=function(){if(this.readyState=="complete"){this.parentNode.removeChild(this);V()}}}}catch(j){}}if(a.webkit&&typeof g.readyState!=Z){Q=setInterval(function(){if(/loaded|complete/.test(g.readyState)){V()}},10)}if(typeof g.addEventListener!=Z){g.addEventListener("DOMContentLoaded",V,null)}M(V)}();function V(){if(S){return }if(a.ie&&a.win){var m=Y("span");try{var l=g.getElementsByTagName("body")[0].appendChild(m);l.parentNode.removeChild(l)}catch(n){return }}S=true;if(Q){clearInterval(Q);Q=null}var j=f.length;for(var k=0;k<j;k++){f[k]()}}function J(i){if(S){i()}else{f[f.length]=i}}function M(j){if(typeof G.addEventListener!=Z){G.addEventListener("load",j,false)}else{if(typeof g.addEventListener!=Z){g.addEventListener("load",j,false)}else{if(typeof G.attachEvent!=Z){G.attachEvent("onload",j)}else{if(typeof G.onload=="function"){var i=G.onload;G.onload=function(){i();j()}}else{G.onload=j}}}}}function I(){var l=H.length;for(var j=0;j<l;j++){var m=H[j].id;if(a.pv[0]>0){var k=c(m);if(k){H[j].width=k.getAttribute("width")?k.getAttribute("width"):"0";H[j].height=k.getAttribute("height")?k.getAttribute("height"):"0";if(O(H[j].swfVersion)){if(a.webkit&&a.webkit<312){U(k)}X(m,true)}else{if(H[j].expressInstall&&!C&&O("6.0.65")&&(a.win||a.mac)){D(H[j])}else{d(k)}}}}else{X(m,true)}}}function U(m){var k=m.getElementsByTagName(P)[0];if(k){var p=Y("embed"),r=k.attributes;if(r){var o=r.length;for(var n=0;n<o;n++){if(r[n].nodeName.toLowerCase()=="data"){p.setAttribute("src",r[n].nodeValue)}else{p.setAttribute(r[n].nodeName,r[n].nodeValue)}}}var q=k.childNodes;if(q){var s=q.length;for(var l=0;l<s;l++){if(q[l].nodeType==1&&q[l].nodeName.toLowerCase()=="param"){p.setAttribute(q[l].getAttribute("name"),q[l].getAttribute("value"))}}}m.parentNode.replaceChild(p,m)}}function F(i){if(a.ie&&a.win&&O("8.0.0")){G.attachEvent("onunload",function(){var k=c(i);if(k){for(var j in k){if(typeof k[j]=="function"){k[j]=function(){}}}k.parentNode.removeChild(k)}})}}function D(j){C=true;var o=c(j.id);if(o){if(j.altContentId){var l=c(j.altContentId);if(l){L=l;T=j.altContentId}}else{L=b(o)}if(!(/%$/.test(j.width))&&parseInt(j.width,10)<310){j.width="310"}if(!(/%$/.test(j.height))&&parseInt(j.height,10)<137){j.height="137"}g.title=g.title.slice(0,47)+" - Flash Player Installation";var n=a.ie&&a.win?"ActiveX":"PlugIn",k=g.title,m="MMredirectURL="+G.location+"&MMplayerType="+n+"&MMdoctitle="+k,p=j.id;if(a.ie&&a.win&&o.readyState!=4){var i=Y("div");p+="SWFObjectNew";i.setAttribute("id",p);o.parentNode.insertBefore(i,o);o.style.display="none";G.attachEvent("onload",function(){o.parentNode.removeChild(o)})}R({data:j.expressInstall,id:K,width:j.width,height:j.height},{flashvars:m},p)}}function d(j){if(a.ie&&a.win&&j.readyState!=4){var i=Y("div");j.parentNode.insertBefore(i,j);i.parentNode.replaceChild(b(j),i);j.style.display="none";G.attachEvent("onload",function(){j.parentNode.removeChild(j)})}else{j.parentNode.replaceChild(b(j),j)}}function b(n){var m=Y("div");if(a.win&&a.ie){m.innerHTML=n.innerHTML}else{var k=n.getElementsByTagName(P)[0];if(k){var o=k.childNodes;if(o){var j=o.length;for(var l=0;l<j;l++){if(!(o[l].nodeType==1&&o[l].nodeName.toLowerCase()=="param")&&!(o[l].nodeType==8)){m.appendChild(o[l].cloneNode(true))}}}}}return m}function R(AE,AC,q){var p,t=c(q);if(typeof AE.id==Z){AE.id=q}if(a.ie&&a.win){var AD="";for(var z in AE){if(AE[z]!=Object.prototype[z]){if(z=="data"){AC.movie=AE[z]}else{if(z.toLowerCase()=="styleclass"){AD+=' class="'+AE[z]+'"'}else{if(z!="classid"){AD+=" "+z+'="'+AE[z]+'"'}}}}}var AB="";for(var y in AC){if(AC[y]!=Object.prototype[y]){AB+='<param name="'+y+'" value="'+AC[y]+'" />'}}t.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AD+">"+AB+"</object>";F(AE.id);p=c(AE.id)}else{if(a.webkit&&a.webkit<312){var AA=Y("embed");AA.setAttribute("type",W);for(var x in AE){if(AE[x]!=Object.prototype[x]){if(x=="data"){AA.setAttribute("src",AE[x])}else{if(x.toLowerCase()=="styleclass"){AA.setAttribute("class",AE[x])}else{if(x!="classid"){AA.setAttribute(x,AE[x])}}}}}for(var w in AC){if(AC[w]!=Object.prototype[w]){if(w!="movie"){AA.setAttribute(w,AC[w])}}}t.parentNode.replaceChild(AA,t);p=AA}else{var s=Y(P);s.setAttribute("type",W);for(var v in AE){if(AE[v]!=Object.prototype[v]){if(v.toLowerCase()=="styleclass"){s.setAttribute("class",AE[v])}else{if(v!="classid"){s.setAttribute(v,AE[v])}}}}for(var u in AC){if(AC[u]!=Object.prototype[u]&&u!="movie"){E(s,u,AC[u])}}t.parentNode.replaceChild(s,t);p=s}}return p}function E(k,i,j){var l=Y("param");l.setAttribute("name",i);l.setAttribute("value",j);k.appendChild(l)}function c(i){return g.getElementById(i)}function Y(i){return g.createElement(i)}function O(k){var j=a.pv,i=k.split(".");i[0]=parseInt(i[0],10);i[1]=parseInt(i[1],10);i[2]=parseInt(i[2],10);return(j[0]>i[0]||(j[0]==i[0]&&j[1]>i[1])||(j[0]==i[0]&&j[1]==i[1]&&j[2]>=i[2]))?true:false}function A(m,j){if(a.ie&&a.mac){return }var l=g.getElementsByTagName("head")[0],k=Y("style");k.setAttribute("type","text/css");k.setAttribute("media","screen");if(!(a.ie&&a.win)&&typeof g.createTextNode!=Z){k.appendChild(g.createTextNode(m+" {"+j+"}"))}l.appendChild(k);if(a.ie&&a.win&&typeof g.styleSheets!=Z&&g.styleSheets.length>0){var i=g.styleSheets[g.styleSheets.length-1];if(typeof i.addRule==P){i.addRule(m,j)}}}function X(k,i){var j=i?"visible":"hidden";if(S){c(k).style.visibility=j}else{A("#"+k,"visibility:"+j)}}return{registerObject:function(l,i,k){if(!a.w3cdom||!l||!i){return }var j={};j.id=l;j.swfVersion=i;j.expressInstall=k?k:false;H[H.length]=j;X(l,false)},getObjectById:function(l){var i=null;if(a.w3cdom&&S){var j=c(l);if(j){var k=j.getElementsByTagName(P)[0];if(!k||(k&&typeof j.SetVariable!=Z)){i=j}else{if(typeof k.SetVariable!=Z){i=k}}}}return i},embedSWF:function(n,u,r,t,j,m,k,p,s){if(!a.w3cdom||!n||!u||!r||!t||!j){return }r+="";t+="";if(O(j)){X(u,false);var q=(typeof s==P)?s:{};q.data=n;q.width=r;q.height=t;var o=(typeof p==P)?p:{};if(typeof k==P){for(var l in k){if(k[l]!=Object.prototype[l]){if(typeof o.flashvars!=Z){o.flashvars+="&"+l+"="+k[l]}else{o.flashvars=l+"="+k[l]}}}}J(function(){R(q,o,u);if(q.id==u){X(u,true)}})}else{if(m&&!C&&O("6.0.65")&&(a.win||a.mac)){X(u,false);J(function(){var i={};i.id=i.altContentId=u;i.width=r;i.height=t;i.expressInstall=m;D(i)})}}},getFlashPlayerVersion:function(){return{major:a.pv[0],minor:a.pv[1],release:a.pv[2]}},hasFlashPlayerVersion:O,createSWF:function(k,j,i){if(a.w3cdom&&S){return R(k,j,i)}else{return undefined}},createCSS:function(j,i){if(a.w3cdom){A(j,i)}},addDomLoadEvent:J,addLoadEvent:M,getQueryParamValue:function(m){var l=g.location.search||g.location.hash;if(m==null){return l}if(l){var k=l.substring(1).split("&");for(var j=0;j<k.length;j++){if(k[j].substring(0,k[j].indexOf("="))==m){return k[j].substring((k[j].indexOf("=")+1))}}}return""},expressInstallCallback:function(){if(C&&L){var i=c(K);if(i){i.parentNode.replaceChild(L,i);if(T){X(T,true);if(a.ie&&a.win){L.style.display="block"}}L=null;T=null;C=false}}}}}();/*
 * FancyBox - simple and fancy jQuery plugin
 * Examples and documentation at: http://fancy.klade.lv/
 * Version: 1.2.1 (13/03/2009)
 * Copyright (c) 2009 Janis Skarnelis
 * Licensed under the MIT License: http://en.wikipedia.org/wiki/MIT_License
 * Requires: jQuery v1.3+
*/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}(';(7($){$.b.2Q=7(){u B.2t(7(){9 1J=$(B).n(\'2Z\');5(1J.1c(/^3w\\(["\']?(.*\\.2p)["\']?\\)$/i)){1J=3t.$1;$(B).n({\'2Z\':\'45\',\'2o\':"3W:3R.4m.4d(3h=F, 3T="+($(B).n(\'41\')==\'2J-3Z\'?\'4c\':\'3N\')+", Q=\'"+1J+"\')"}).2t(7(){9 1b=$(B).n(\'1b\');5(1b!=\'2e\'&&1b!=\'2n\')$(B).n(\'1b\',\'2n\')})}})};9 A,4,16=D,s=1t 1o,1w,1v=1,1y=/\\.(3A|3Y|2p|3c|3d)(.*)?$/i;9 P=($.2q.3K&&2f($.2q.3z.2k(0,1))<8);$.b.c=7(Y){Y=$.3x({},$.b.c.2R,Y);9 2s=B;7 2h(){A=B;4=Y;2r();u D};7 2r(){5(16)u;5($.1O(4.2c)){4.2c()}4.j=[];4.h=0;5(Y.j.N>0){4.j=Y.j}t{9 O={};5(!A.1H||A.1H==\'\'){9 O={d:A.d,X:A.X};5($(A).1G("1m:1D").N){O.1a=$(A).1G("1m:1D")}4.j.2j(O)}t{9 Z=$(2s).2o("a[1H="+A.1H+"]");9 O={};3C(9 i=0;i<Z.N;i++){O={d:Z[i].d,X:Z[i].X};5($(Z[i]).1G("1m:1D").N){O.1a=$(Z[i]).1G("1m:1D")}4.j.2j(O)}3F(4.j[4.h].d!=A.d){4.h++}}}5(4.23){5(P){$(\'1U, 1Q, 1P\').n(\'1S\',\'3s\')}$("#1i").n(\'25\',4.2U).J()}1d()};7 1d(){$("#1f, #1e, #V, #G").S();9 d=4.j[4.h].d;5(d.1c(/#/)){9 U=11.3r.d.3f(\'#\')[0];U=d.3g(U,\'\');U=U.2k(U.2l(\'#\'));1k(\'<6 l="3e">\'+$(U).o()+\'</6>\',4.1I,4.1x)}t 5(d.1c(1y)){s=1t 1o;s.Q=d;5(s.3a){1K()}t{$.b.c.34();$(s).x().14(\'3b\',7(){$(".I").S();1K()})}}t 5(d.1c("17")||A.3j.2l("17")>=0){1k(\'<17 l="35" 3q="$.b.c.38()" 3o="3n\'+C.T(C.3l()*3m)+\'" 2K="0" 3E="0" Q="\'+d+\'"></17>\',4.1I,4.1x)}t{$.4p(d,7(2m){1k(\'<6 l="3L">\'+2m+\'</6>\',4.1I,4.1x)})}};7 1K(){5(4.30){9 w=$.b.c.1n();9 r=C.1M(C.1M(w[0]-36,s.g)/s.g,C.1M(w[1]-4b,s.f)/s.f);9 g=C.T(r*s.g);9 f=C.T(r*s.f)}t{9 g=s.g;9 f=s.f}1k(\'<1m 48="" l="49" Q="\'+s.Q+\'" />\',g,f)};7 2F(){5((4.j.N-1)>4.h){9 d=4.j[4.h+1].d;5(d.1c(1y)){1A=1t 1o();1A.Q=d}}5(4.h>0){9 d=4.j[4.h-1].d;5(d.1c(1y)){1A=1t 1o();1A.Q=d}}};7 1k(1j,g,f){16=F;9 L=4.2Y;5(P){$("#q")[0].1E.2u("f");$("#q")[0].1E.2u("g")}5(L>0){g+=L*2;f+=L*2;$("#q").n({\'v\':L+\'z\',\'2E\':L+\'z\',\'2i\':L+\'z\',\'y\':L+\'z\',\'g\':\'2B\',\'f\':\'2B\'});5(P){$("#q")[0].1E.2C(\'f\',\'(B.2D.4j - 20)\');$("#q")[0].1E.2C(\'g\',\'(B.2D.3S - 20)\')}}t{$("#q").n({\'v\':0,\'2E\':0,\'2i\':0,\'y\':0,\'g\':\'2z%\',\'f\':\'2z%\'})}5($("#k").1u(":19")&&g==$("#k").g()&&f==$("#k").f()){$("#q").1Z("2N",7(){$("#q").1C().1F($(1j)).21("1s",7(){1g()})});u}9 w=$.b.c.1n();9 2v=(g+36)>w[0]?w[2]:(w[2]+C.T((w[0]-g-36)/2));9 2w=(f+1z)>w[1]?w[3]:(w[3]+C.T((w[1]-f-1z)/2));9 K={\'y\':2v,\'v\':2w,\'g\':g+\'z\',\'f\':f+\'z\'};5($("#k").1u(":19")){$("#q").1Z("1s",7(){$("#q").1C();$("#k").24(K,4.2X,4.2T,7(){$("#q").1F($(1j)).21("1s",7(){1g()})})})}t{5(4.1W>0&&4.j[4.h].1a!==1L){$("#q").1C().1F($(1j));9 M=4.j[4.h].1a;9 15=$.b.c.1R(M);$("#k").n({\'y\':(15.y-18)+\'z\',\'v\':(15.v-18)+\'z\',\'g\':$(M).g(),\'f\':$(M).f()});5(4.1X){K.25=\'J\'}$("#k").24(K,4.1W,4.2W,7(){1g()})}t{$("#q").S().1C().1F($(1j)).J();$("#k").n(K).21("1s",7(){1g()})}}};7 2y(){5(4.h!=0){$("#1e, #2O").x().14("R",7(e){e.2x();4.h--;1d();u D});$("#1e").J()}5(4.h!=(4.j.N-1)){$("#1f, #2M").x().14("R",7(e){e.2x();4.h++;1d();u D});$("#1f").J()}};7 1g(){2y();2F();$(W).1B(7(e){5(e.29==27){$.b.c.1l();$(W).x("1B")}t 5(e.29==37&&4.h!=0){4.h--;1d();$(W).x("1B")}t 5(e.29==39&&4.h!=(4.j.N-1)){4.h++;1d();$(W).x("1B")}});5(4.1r){$(11).14("1N 1T",$.b.c.2g)}t{$("6#k").n("1b","2e")}5(4.2b){$("#22").R($.b.c.1l)}$("#1i, #V").14("R",$.b.c.1l);$("#V").J();5(4.j[4.h].X!==1L&&4.j[4.h].X.N>0){$(\'#G 6\').o(4.j[4.h].X);$(\'#G\').J()}5(4.23&&P){$(\'1U, 1Q, 1P\',$(\'#q\')).n(\'1S\',\'19\')}5($.1O(4.2a)){4.2a()}16=D};u B.x(\'R\').R(2h)};$.b.c.2g=7(){9 m=$.b.c.1n();$("#k").n(\'y\',(($("#k").g()+36)>m[0]?m[2]:m[2]+C.T((m[0]-$("#k").g()-36)/2)));$("#k").n(\'v\',(($("#k").f()+1z)>m[1]?m[3]:m[3]+C.T((m[1]-$("#k").f()-1z)/2)))};$.b.c.1h=7(H,2A){u 2f($.3I(H.3u?H[0]:H,2A,F))||0};$.b.c.1R=7(H){9 m=H.4g();m.v+=$.b.c.1h(H,\'3k\');m.v+=$.b.c.1h(H,\'3J\');m.y+=$.b.c.1h(H,\'3H\');m.y+=$.b.c.1h(H,\'3D\');u m};$.b.c.38=7(){$(".I").S();$("#35").J()};$.b.c.1n=7(){u[$(11).g(),$(11).f(),$(W).3i(),$(W).3p()]};$.b.c.2G=7(){5(!$("#I").1u(\':19\')){33(1w);u}$("#I > 6").n(\'v\',(1v*-40)+\'z\');1v=(1v+1)%12};$.b.c.34=7(){33(1w);9 m=$.b.c.1n();$("#I").n({\'y\':((m[0]-40)/2+m[2]),\'v\':((m[1]-40)/2+m[3])}).J();$("#I").14(\'R\',$.b.c.1l);1w=3Q($.b.c.2G,3X)};$.b.c.1l=7(){16=F;$(s).x();$("#1i, #V").x();5(4.2b){$("#22").x()}$("#V, .I, #1e, #1f, #G").S();5(4.1r){$(11).x("1N 1T")}1q=7(){$("#1i, #k").S();5(4.1r){$(11).x("1N 1T")}5(P){$(\'1U, 1Q, 1P\').n(\'1S\',\'19\')}5($.1O(4.1V)){4.1V()}16=D};5($("#k").1u(":19")!==D){5(4.26>0&&4.j[4.h].1a!==1L){9 M=4.j[4.h].1a;9 15=$.b.c.1R(M);9 K={\'y\':(15.y-18)+\'z\',\'v\':(15.v-18)+\'z\',\'g\':$(M).g(),\'f\':$(M).f()};5(4.1X){K.25=\'S\'}$("#k").31(D,F).24(K,4.26,4.2S,1q)}t{$("#k").31(D,F).1Z("2N",1q)}}t{1q()}u D};$.b.c.2V=7(){9 o=\'\';o+=\'<6 l="1i"></6>\';o+=\'<6 l="22">\';o+=\'<6 p="I" l="I"><6></6></6>\';o+=\'<6 l="k">\';o+=\'<6 l="2I">\';o+=\'<6 l="V"></6>\';o+=\'<6 l="E"><6 p="E 44"></6><6 p="E 43"></6><6 p="E 42"></6><6 p="E 3V"></6><6 p="E 3U"></6><6 p="E 3O"></6><6 p="E 3M"></6><6 p="E 3P"></6></6>\';o+=\'<a d="2P:;" l="1e"><1p p="1Y" l="2O"></1p></a><a d="2P:;" l="1f"><1p p="1Y" l="2M"></1p></a>\';o+=\'<6 l="q"></6>\';o+=\'<6 l="G"></6>\';o+=\'</6>\';o+=\'</6>\';o+=\'</6>\';$(o).2H("46");$(\'<32 4i="0" 4h="0" 4k="0"><2L><13 p="G" l="4l"></13><13 p="G" l="4o"><6></6></13><13 p="G" l="4n"></13></2L></32>\').2H(\'#G\');5(P){$("#2I").47(\'<17 p="4a" 4e="2J" 2K="0"></17>\');$("#V, .E, .G, .1Y").2Q()}};$.b.c.2R={2Y:10,30:F,1X:D,1W:0,26:0,2X:3G,2W:\'28\',2S:\'28\',2T:\'28\',1I:3B,1x:3v,23:F,2U:0.3,2b:F,1r:F,j:[],2c:2d,2a:2d,1V:2d};$(W).3y(7(){$.b.c.2V()})})(4f);',62,274,'||||opts|if|div|function||var||fn|fancybox|href||height|width|itemCurrent||itemArray|fancy_outer|id|pos|css|html|class|fancy_content||imagePreloader|else|return|top||unbind|left|px|elem|this|Math|false|fancy_bg|true|fancy_title|el|fancy_loading|show|itemOpts|pad|orig_item|length|item|isIE|src|click|hide|round|target|fancy_close|document|title|settings|subGroup||window||td|bind|orig_pos|busy|iframe||visible|orig|position|match|_change_item|fancy_left|fancy_right|_finish|getNumeric|fancy_overlay|value|_set_content|close|img|getViewport|Image|span|__cleanup|centerOnScroll|normal|new|is|loadingFrame|loadingTimer|frameHeight|imageRegExp|50|objNext|keydown|empty|first|style|append|children|rel|frameWidth|image|_proceed_image|undefined|min|resize|isFunction|select|object|getPosition|visibility|scroll|embed|callbackOnClose|zoomSpeedIn|zoomOpacity|fancy_ico|fadeOut||fadeIn|fancy_wrap|overlayShow|animate|opacity|zoomSpeedOut||swing|keyCode|callbackOnShow|hideOnContentClick|callbackOnStart|null|absolute|parseInt|scrollBox|_initialize|bottom|push|substr|indexOf|data|relative|filter|png|browser|_start|matchedGroup|each|removeExpression|itemLeft|itemTop|stopPropagation|_set_navigation|100|prop|auto|setExpression|parentNode|right|_preload_neighbor_images|animateLoading|appendTo|fancy_inner|no|frameborder|tr|fancy_right_ico|fast|fancy_left_ico|javascript|fixPNG|defaults|easingOut|easingChange|overlayOpacity|build|easingIn|zoomSpeedChange|padding|backgroundImage|imageScale|stop|table|clearInterval|showLoading|fancy_frame|||showIframe||complete|load|bmp|jpeg|fancy_div|split|replace|enabled|scrollLeft|className|paddingTop|random|1000|fancy_iframe|name|scrollTop|onload|location|hidden|RegExp|jquery|355|url|extend|ready|version|jpg|425|for|borderLeftWidth|hspace|while|300|paddingLeft|curCSS|borderTopWidth|msie|fancy_ajax|fancy_bg_w|scale|fancy_bg_sw|fancy_bg_nw|setInterval|DXImageTransform|clientWidth|sizingMethod|fancy_bg_s|fancy_bg_se|progid|66|gif|repeat||backgroundRepeat|fancy_bg_e|fancy_bg_ne|fancy_bg_n|none|body|prepend|alt|fancy_img|fancy_bigIframe|60|crop|AlphaImageLoader|scrolling|jQuery|offset|cellpadding|cellspacing|clientHeight|border|fancy_title_left|Microsoft|fancy_title_right|fancy_title_main|get'.split('|'),0,{}))
//script for quick view popup
g_listing_key = null;
g_listing_id = null;
g_listing_multiunit = null;
g_request = null;
g_title = null;
g_cookie_value = null;
g_header = null;    
g_qv_thank_you_shown = true;
g_qv_Address = null;
g_qv_phone = null;
g_qv_contact_name = null;
g_onSubmitClickType='LeadSubmitted';

function populateLeadForm(listingKey, listingId, listingMultiUnit, request, title, header)
{
    g_listing_key = listingKey;
    g_listing_id = listingId;
    g_listing_multiunit = listingMultiUnit;
    g_request = request;
    g_title = title;
    g_header = (header && header != "" ? header : "Check Availability");
}      

 
function populateQuickView(address, phone, contact_name, display_lead_form) {
    g_qv_Address = address;
    g_qv_phone = phone;
    g_qv_contact_name = contact_name;
    g_qv_display_lead_form = display_lead_form;
}

populateQuickViewForm = function () {
    loadCookieInfo(g_qv_display_lead_form);
    getFaceBoxObject('qv_contact-form').css('display', g_qv_display_lead_form);
    getFaceBoxObject('qv_slideshow_address').css('display', 'block');
    getFaceBoxObject('qv_slideshow_view').attr('src', gSlideShowfile+'?listingkey='+(g_listing_key)+'&listingid='+(g_listing_id));
    getFaceBoxObject('qv_address').html(g_qv_Address);    
    getFaceBoxObject('qv_phone').html(g_qv_phone);
    getFaceBoxObject('qv_contact_name').html(g_qv_contact_name);
    getFaceBoxObject('qv_new_btn_submit').click(QuickViewValidate);    
    getFaceBoxObject('qv_thank_you_message').html(getFaceBoxObject('qv_thank_you_message').html().replace('#replaceme',g_title));
    getFaceBoxObject('qv_lead_title_txt').html(g_title);
    if (g_listing_id == "" || g_listing_id == "00000000-0000-0000-0000-000000000000") {
        getFaceBoxObject('qv_lead_title').addClass("apartment");
        getFaceBoxObject('qv_lead_title').removeClass("house");
    }
    else {
        getFaceBoxObject('qv_lead_title').removeClass("apartment");
        getFaceBoxObject('qv_lead_title').addClass("house");
    }
}


showThickBoxLeadForm = function() {
    if (g_qv_thank_you_shown) 
    {   
        getFaceBoxObject('qv_thank_you_show_hide').hide();
        getFaceBoxObject('qv_modal_lead').show();
        getFaceBoxObject('qv_lead_title').show();
    }
    else
    {   
        getFaceBoxObject('qv_modal_lead').hide();
        getFaceBoxObject('qv_thank_you_show_hide').show();
    }
}

loadCookieInfo = function() {
    if (g_cookie_value == null || g_cookie_value == "")
        g_cookie_value = readCookie('_LeadReply');
    if (g_cookie_value && g_cookie_value != "") {
        cookieArray = g_cookie_value.split('&');
        getFaceBoxObject('qv_lead_txt_name').val(cookieArray[0].split('=')[1]);
        getFaceBoxObject('qv_lead_txt_telephone').val(cookieArray[1].split('=')[1]);
        getFaceBoxObject('qv_lead_txt_email').val(cookieArray[3].split('=')[1]);
        getFaceBoxObject('qv_lead_txt_message').text(cookieArray[4].split('=')[1]);
        getFaceBoxObject('qv_lead_ddlMovingTimeFrame').selectOptions(cookieArray[5].split('=')[1])
    }
}

saveCookieInfo = function() {     
    var name = getFaceBoxObject('qv_lead_txt_name').val();
    var email = getFaceBoxObject('qv_lead_txt_email').val();
    var telephone = getFaceBoxObject('qv_lead_txt_telephone').val();
    var message = getFaceBoxObject('qv_lead_txt_message').val()
    var moving = getFaceBoxObject('qv_lead_ddlMovingTimeFrame').selectedValues()
    var strValue = 'Name='+name+'&Phone='+telephone+'&AlternatePhone=&Email='+email+'&Message='+message+'&TimeFrame='+moving;
    createCookie('_LeadReply',strValue,180);
    g_cookie_value = strValue;
}

showThankyou = function(){
    saveCookieInfo();
    getFaceBoxObject('qv_lead_title').hide();
    getFaceBoxObject('qv_modal_lead').hide();
    getFaceBoxObject('qv_thank_you_show_hide').show();
    dcsMultiTrackClick('DCS.dcsuri','Multitrack','DCSext.r_l_popls', g_listing_key,'DCSext.clicktype','LeadSubmitted','DCSext.LeadType','EmailLead','DCSext.LeadSubType', (g_listing_multiunit == 'True'?'MUL':'SUL'),'DCSext.LeadCount','1','DCSext.Site', gSiteSubdomain);
    getFaceBoxObject('leadTrackingTags').attr('src', gLeadTrackingTagsFile);
    g_qv_thank_you_shown = true;
}

showFailure = function(){
    saveCookieInfo();
    getFaceBoxObject('qv_lead_title').hide();
    getFaceBoxObject('qv_modal_lead').hide();
    getFaceBoxObject('qv_failure_show_hide').show();
    g_qv_thank_you_shown = true;
}

quickViewSubmitLead = function(){ 
    showThankyou();
    $.ajax({
            type: "POST",
            url: '/LeadForm.asmx/SubmitLead',
            data: 'listingKey=' + g_listing_key+'&listingId=' + g_listing_id + '&name=' + getFaceBoxObject('qv_lead_txt_name').val() + '&email=' + getFaceBoxObject('qv_lead_txt_email').val() + '&phone=' + getFaceBoxObject('qv_lead_txt_telephone').val() + '&message=' + getFaceBoxObject('qv_lead_txt_message').val()+ '&moving=' + getFaceBoxObject('qv_lead_ddlMovingTimeFrame').selectedValues()+ '&request=' + g_request,
            error: function(xhr, ajaxOptions, thrownError) {
                showFailure();
            }
    });    
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else {
        var expires = "";
    }
    var val = escape(value);
    document.cookie = name+"="+val+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = unescape(ca[i]);
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) { 
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function QuickViewValidate()
{
    //hide error message box from post back
    getFaceBoxElement('errorWrapper').style.display='none';
    
    var isValid = true;
    
    //Validator( divErrorWrapper, ulErrorList, divErrorWrapperCSS, elementErrorCSS)
    var valMgr = new jQValidator('', '', '', 'form-error');
	
    //Name
    valMgr.rules.push( new jQValidationRule('qv_lead_txt_name',  RULE_REQUIRED,  'Name is required.', '', 'qv_lead_txt_name_error'));

    //Email
    valMgr.rules.push( new jQValidationRule('qv_lead_txt_email', RULE_REQUIRED,  'Email is required.','', 'qv_lead_txt_email_error') );
    valMgr.rules.push( new jQValidationRule('qv_lead_txt_email', RULE_REGEX,     'Email address is not in an accepted format.', REGEX_EMAIL, 'qv_lead_txt_email_error'));

    //Telephone
    valMgr.rules.push( new jQValidationRule('qv_lead_txt_telephone', RULE_REGEX, 'Please enter as ###-###-####', REGEX_PHONE_DASH_ONLY , 'qv_lead_txt_telephone_error'));	
    
    //message
    valMgr.rules.push( new jQValidationRule('qv_lead_txt_message', RULE_REQUIRED,'Message is required.', '', 'qv_lead_txt_message_error'));
	
    isValid = valMgr.validate();	
	
    if(!isValid )
    {
        var reporting = new jQValidationReporting( 'errorWrapper', 'errorGif', '/Images/1x1.gif', 'SearchResultsListingReply' );
        reporting.additionalParameters = 'ListingNumber= ' + g_listing_key+ '&Language=en';
        reporting.errors = valMgr.errors;
        reporting.reportError();
    }
    else
    {
        quickViewSubmitLead();
    }
    
    return isValid;		
}


    

populateLeadFormData = function () {
    loadLeadFormCookieInfo();
    getFaceBoxObject('lf_new_btn_submit').click(LeadFormValidate);    
    getFaceBoxObject('lf_thank_you_message').html(getFaceBoxObject('lf_thank_you_message').html().replace('#replaceme',g_title));
    getFaceBoxObject('lf_lead_title_txt').html(g_title);
    getFaceBoxObject('lf_header').html(getFaceBoxObject('lf_header').html().replace('#replaceHeader',g_header));
}

showThickBoxLeadForm = function() {
    if (g_lf_thank_you_shown) 
    {   
        getFaceBoxObject('lf_thank_you_show_hide').hide();
        getFaceBoxObject('lf_modal_lead').show();
        getFaceBoxObject('lf_lead_title').show();
    }
    else
    {   
        getFaceBoxObject('lf_modal_lead').hide();
        getFaceBoxObject('lf_thank_you_show_hide').show();
    }
}

loadLeadFormCookieInfo = function() {
    if (g_cookie_value == null || g_cookie_value == "")
        g_cookie_value = readCookie('_LeadReply');
    if (g_cookie_value && g_cookie_value != "") {
        cookieArray = g_cookie_value.split('&');
        getFaceBoxObject('lf_lead_txt_name').val(cookieArray[0].split('=')[1]);
        getFaceBoxObject('lf_lead_txt_telephone').val(cookieArray[1].split('=')[1]);
        getFaceBoxObject('lf_lead_txt_email').val(cookieArray[3].split('=')[1]);
        getFaceBoxObject('lf_lead_txt_message').text(cookieArray[4].split('=')[1]);
        getFaceBoxObject('lf_lead_ddlMovingTimeFrame').selectOptions(cookieArray[5].split('=')[1])
    }
}

saveLeadFormCookieInfo = function() {     
    var name = getFaceBoxObject('lf_lead_txt_name').val();
    var email = getFaceBoxObject('lf_lead_txt_email').val();
    var telephone = getFaceBoxObject('lf_lead_txt_telephone').val();
    var message = getFaceBoxObject('lf_lead_txt_message').val()
    var moving = getFaceBoxObject('lf_lead_ddlMovingTimeFrame').selectedValues()
    var strValue = 'Name='+name+'&Phone='+telephone+'&AlternatePhone=&Email='+email+'&Message='+message+'&TimeFrame='+moving;
    createCookie('_LeadReply',strValue,180);
    g_cookie_value = strValue;
}

showLeadFormThankyou = function(){
    saveLeadFormCookieInfo();
    getFaceBoxObject('lf_lead_title').hide();
    getFaceBoxObject('lf_modal_lead').hide();
    getFaceBoxObject('lf_thank_you_show_hide').show();
    dcsMultiTrackClick('DCS.dcsuri','Multitrack','DCSext.r_l_popls', g_listing_key,'DCSext.clicktype',g_onSubmitClickType,'DCSext.LeadType','EmailLead','DCSext.LeadSubType',(g_listing_multiunit == 'True'?'MUL':'SUL'),'DCSext.LeadCount','1','DCSext.Site', gSiteSubdomain);
    getFaceBoxObject('leadTrackingTags').attr('src', gLeadTrackingTagsFile);
    g_lf_thank_you_shown = true;
}

showLeadFormFailure = function(){
    saveLeadFormCookieInfo();
    getFaceBoxObject('lf_lead_title').hide();
    getFaceBoxObject('lf_modal_lead').hide();
    getFaceBoxObject('lf_thank_you_show_hide').hide();
    getFaceBoxObject('lf_failure_show_hide').show();
    g_lf_thank_you_shown = true;
}

submitLeadForm = function(){ 

    showLeadFormThankyou();
    $.ajax({
            type: "POST",
            url: '/LeadForm.asmx/SubmitLead',
            data: 'listingKey=' + g_listing_key+'&listingId=' + g_listing_id + '&name=' + getFaceBoxObject('lf_lead_txt_name').val() + '&email=' + getFaceBoxObject('lf_lead_txt_email').val() + '&phone=' + getFaceBoxObject('lf_lead_txt_telephone').val() + '&message=' + getFaceBoxObject('lf_lead_txt_message').val()+ '&moving=' + getFaceBoxObject('lf_lead_ddlMovingTimeFrame').selectedValues()+ '&request=' + g_request,
            error: function(xhr, ajaxOptions, thrownError) {
                showLeadFormFailure();
            }
    });    
}


function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else {
        var expires = "";
    }
    var val = escape(value);
    document.cookie = name+"="+val+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = unescape(ca[i]);
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) { 
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function LeadFormValidate()
{
    //hide error message box from post back
    getFaceBoxElement('errorWrapper').style.display='none';
    
    var isValid = true;
    
    //Validator( divErrorWrapper, ulErrorList, divErrorWrapperCSS, elementErrorCSS)
    var valMgr = new jQValidator('', '', '', 'form-error');
	
    //Name
    valMgr.rules.push( new jQValidationRule('lf_lead_txt_name',  RULE_REQUIRED,  'Name is required.', '', 'lf_lead_txt_name_error'));

    //Email
    valMgr.rules.push( new jQValidationRule('lf_lead_txt_email', RULE_REQUIRED,  'Email is required.','', 'lf_lead_txt_email_error') );
    valMgr.rules.push( new jQValidationRule('lf_lead_txt_email', RULE_REGEX,     'Email address is not in an accepted format.', REGEX_EMAIL, 'lf_lead_txt_email_error'));

    //Telephone
    valMgr.rules.push( new jQValidationRule('lf_lead_txt_telephone', RULE_REGEX, 'Please enter as ###-###-####', REGEX_PHONE_DASH_ONLY , 'lf_lead_txt_telephone_error'));	
    
    //message
    valMgr.rules.push( new jQValidationRule('lf_lead_txt_message', RULE_REQUIRED,'Message is required.', '', 'lf_lead_txt_message_error'));
	
    isValid = valMgr.validate();	
	
    if(!isValid )
    {
        var reporting = new jQValidationReporting( 'errorWrapper', 'errorGif', '/Images/1x1.gif', 'SearchResultsListingReply' );
        reporting.additionalParameters = 'ListingNumber= ' + g_listing_key+ '&Language=en';
        reporting.errors = valMgr.errors;
        reporting.reportError();
    }
    else
    {
        submitLeadForm();
        
    }
    
    return isValid;		
}


ONESEARCH_URL = "http://onesearch.svc.primedia.com";  //prod
//ONESEARCH_URL = "http://10.130.87.12";  //QA
APARTMENT_GUIDE = "AG";
NEW_HOME_GUIDE = "NHG";
RENTALS = "R";
RENTAL_HOUSES = "RH";
 
APPLICATION = RENTALS;
channel = "apartments"
/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */

; (function($) {

    $.fn.extend({
        autocomplete: function(urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({},
            $.Autocompleter.defaults, {
                url: isUrl ? urlOrData: null,
                data: isUrl ? null: urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay: 10,
                max: options && !options.scroll ? 10: 150
            },
            options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight ||
            function(value) {
                return value;
            };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            // TJ - Custom property added onSelect is called when Enter/Return is pressed
            options.onSelect = options.onSelect ||
            function(value) {
                return value;
            };

            return this.each(function() {
                new $.Autocompleter(this, options);
            });
        },
        result: function(handler) {
            return this.bind("result", handler);
        },
        search: function(handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function() {
            return this.trigger("flushCache");
        },
        setOptions: function(options) {
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function() {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function(input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete",
        function() {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress": "keydown") + ".autocomplete",
        function(event) {
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch (event.keyCode) {
            case KEY.UP:
                event.preventDefault();
                if (select.visible()) {
                    select.prev();
                } else {
                    onChange(0, true);
                }
                break;

            case KEY.DOWN:
                event.preventDefault();
                if (select.visible()) {
                    select.next();
                } else {
                    onChange(0, true);
                }
                break;

            case KEY.PAGEUP:
                event.preventDefault();
                if (select.visible()) {
                    select.pageUp();
                } else {
                    onChange(0, true);
                }
                break;

            case KEY.PAGEDOWN:
                event.preventDefault();
                if (select.visible()) {
                    select.pageDown();
                } else {
                    onChange(0, true);
                }
                break;

                // matches also semicolon
            case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
            case KEY.TAB:
                if (selectCurrent()) {
                    event.preventDefault();
                    blockSubmit = true;
                    return false;
                }
                break;
            case KEY.RETURN:
                if (selectCurrent()) {
                    // custom property to call a method when item selected and user hits Enter/Return
                    options.onSelect();
                    // stop default to prevent a form submit, Opera needs special handling
                    event.preventDefault();
                    blockSubmit = true;
                    return false;
                }
                break;

            case KEY.ESC:
                select.hide();
                break;

            default:
                clearTimeout(timeout);
                timeout = setTimeout(onChange, options.delay);
                break;
            }
        }).focus(function() {
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
        }).blur(function() {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function() {
            // show select when clicking in a focused field
            if (hasFocus++>1 && !select.visible()) {
                onChange(0, true);
            }
        }).bind("search",
        function() {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()),
            function(i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache",
        function() {
            cache.flush();
        }).bind("setOptions",
        function() {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
            cache.populate();
        }).bind("unautocomplete",
        function() {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
            return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }
            //Modified by Fadi & Bill, saving actual typed in value
            if ($("input#typed")) $("input#typed").val($input.val());
            $input.val(v);
            hideResultsNow();
            $input.trigger("result", [selected.data, selected.value]);
            return true;
        }

        function onChange(crap, skipPrevCheck) {
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }

            var currentValue = $input.val();

            if (!skipPrevCheck && currentValue == previousValue)
            return;

            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            if (currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value) {
                return [""];
            }
            var words = value.split(options.multipleSeparator);
            var result = [];
            $.each(words,
            function(i, value) {
                if ($.trim(value))
                result[i] = $.trim(value);
            });
            return result;
        }

        function lastWord(value) {
            if (!options.multiple)
            return value;
            var words = trimWords(value);
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
                function(result) {
                    // if no value found, clear the input box
                    if (!result) {
                        if (options.multiple) {
                            var words = trimWords($input.val()).slice(0, -1);
                            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator: ""));
                        }
                        else
                        $input.val("");
                    }
                }
                );
            }
            // CSI: Commented out to prevent resetting of focus back to user search
            // if (wasVisible)
            //  // position cursor at end of input field
            //  $.Autocompleter.Selection(input, input.value.length, input.value.length);
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase){
              term = term.toLowerCase();
              term = term.replace(/=/g, '');
            }            
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams,
                function(key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        channel: channel,
						application: APPLICATION,
                        limit: options.max
                    },
                    extraParams),
                    success: function(data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            return JSONDataParser.parse(data, options);
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: false,
        cacheLength: 10,
        max: 100,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function(row) {
            return row[0];
        },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([^$()[]{}*.+?|\])/gi, "\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 180
    };

    $.Autocompleter.Cache = function(options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
            s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
            nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++<options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets,
            function(i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function(q) {
                if (!options.cacheLength || !length)
                return null;
                /* 
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c,
                            function(i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                if (data[q]) {
                    return data[q];
                } else
                if (options.matchSubset) {
                    for (var i = q.length - 1; i >= options.minChars; i--) {
                        var c = data[q.substr(0, i)];
                        if (c) {
                            var csub = [];
                            $.each(c,
                            function(i, x) {
                                if (matchSubset(x.value, q)) {
                                    csub[csub.length] = x;
                                }
                            });
                            return csub;
                        }
                    }
                }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function(options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
        active = -1,
        data,
        term = "",
        needsInit = true,
        element,
        list;

        // Create results
        function init() {
            if (!needsInit)
            return;
            element = $("<div/>")
            .hide()
            .addClass(options.resultsClass)
            .css("position", "absolute")
            .appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover(function(event) {
                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function(event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                input.focus();
                return false;
            }).mousedown(function() {
                config.mouseDownOnSelect = true;
            }).mouseup(function() {
                config.mouseDownOnSelect = false;
            });

            if (options.width > 0)
            element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
            element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
            return [];
            return element;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function() {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
            ? options.max
            : available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            for (var i = 0; i < max; i++) {
                if (!data[i])
                continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even": "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");
            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }
            // apply bgiframe if available
            if ($.fn.bgiframe)
            list.bgiframe();
        }

        return {
            display: function(d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function() {
                moveSelect(1);
            },
            prev: function() {
                moveSelect( - 1);
            },
            pageUp: function() {
                if (active != 0 && active - 8 < 0) {
                    moveSelect( - active);
                } else {
                    moveSelect( - 8);
                }
            },
            pageDown: function() {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function() {
                //needed to hide drop down boxes, IE6 only
                hideDropdowns(false);
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function() {
                return element && element.is(":visible");
            },
            current: function() {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function() {
                //needed to hide drop down boxes, IE6 only
                hideDropdowns(true);
                var offset = $(input).offset();
                element.css({
                    width: typeof options.width == "string" || options.width > 0 ? options.width: $(input).width(),
                    top: offset.top + input.offsetHeight + 8,
                    left: offset.left - 1
                }).show();
                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        overflow: 'auto'
                    });

                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function() {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight: listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
            },
            selected: function() {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function() {
                list && list.empty();
            },
            unbind: function() {
                element && element.remove();
            }
        };
    };

    $.Autocompleter.Selection = function(field, start, end) {
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else {
            if (field.selectionStart) {
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

})(jQuery);

// ################## BEGIN JAVASCRIPT REFACTORING ##################
JSONDataParser = {
  parse: function(data, options) {
    var parsed = [];
    if (data) {
   $(data).each(function(index, jsonData) {
        var row = $.trim(jsonData.name + "|" + jsonData.seopath + "|" + jsonData.geocode + "|" + jsonData.radius + "|" + jsonData.sortfield + "|" + jsonData.count);
        if (row) {
       row = row.split("|");
       parsed[parsed.length] = {
     data: row,
     value: row[0],
     result: options.formatResult && options.formatResult(row, row[0]) || row[0]
       };
        }
   });
    }
    return parsed;
  }
}

function hideAllSelects() {
  $("select").hide();
}

function showAllSelects() {
  $("select").show();
}

function isIESixOrLower() {
  return $.browser.msie && parseInt($.browser.version) <= 6;
}

function hideDropdowns(hide){
  if (isIESixOrLower()) {
    if (hide) {
      hideAllSelects();
    }
    else{
      showAllSelects();
    }
  }
 
}var ONESEARCH_OPTIONS;
var INVALID_QUERIES = [""];
var PROCESSING = false;

/*
 * jQuery plugin for implementing OneSearch on the specified form.
 *
 * Usage: jQuery(selector).onesearch(options);
 * selector is the jQuery selector to the form submit button.
 * options are key/value pairs of options to the plugin.
 *
 * This plugin has a dependency on the jquery.autocomplete plugin.
 * 
 * options.highlight: The function that gets called when an item is highlighted.
 *
 */
jQuery.fn.onesearch = function(options) {
	setupOptions(options);
	jQuery(this).bind("submit", getSeoPath);
	jQuery('#btnSearch').bind("click", getSeoPath);
    jQuery('#user_search').keypress(function (event) {
        if (event.keyCode == 13) {
            getSeoPath();
            return false;
        }
    });

};


/*
 * jQuery plugin for adding autocomplete functionality on the
 * specified input field.
 *
 * Usage: jQuery(selector).onesearch(options);
 * selector is the jQuery selector to the form submit button.
 * options are key/value pairs of options to the plugin.
 *
 * This plugin has a dependency on the jquery.autocomplete plugin.
 *
 * options.highlight: The function that gets called when an item is highlighted.
 * 
 */
jQuery.fn.oneautocomplete = function(options) {
    //console.log('here');
	setupOptions(options);
        jQuery("body").append("<input type='hidden' id='seopath'/>");
        jQuery("body").append("<input type='hidden' id='geocode'/>");
        jQuery("body").append("<input type='hidden' id='radius'/>");
        jQuery("body").append("<input type='hidden' id='sortfield'/>");
        jQuery(this).autocomplete(ONESEARCH_URL + "/autocomplete?callback=?", {
		dataType: "json",
    highlight: options.highlight, 
    minChars: 3, 
    delay: 200, 
    cacheLength: 1000,
    maxItemsToShow: 10,
		matchSubset: 1,
		matchContains: 0,
    onSelect: selectLocation }).result(function(event, item) {
        jQuery(this).attr("value", item[0]);
        jQuery("#seopath").attr("value", item[1]);
        jQuery("#geocode").attr("value", item[2]);
        jQuery("#radius").attr("value", item[3]);
        jQuery("#sortfield").attr("value", item[4]);
		PROCESSING = true;
	});
};

/*
 * This object represents a search via OneSearch.
 * 
 * controller: The LocationsController that encapsulates the ajax call 
 *             to the controller on the server side.
 */
Search = function(controller) {
	this.controller = controller;
};

/*
 * Executes a search for a seo path based on the supplied query or dimension id.
 * 
 * query: The user entered search query
 * dimensionId: The N= value of the dimension, known if this was autocompleted.
 *
 */
Search.prototype.execute = function(query) {
	var newQuery = query.replace(/=/g, '');
  if (this.invalid(query)) {
    jQuery("body").trigger({ type: "onesearch-error-invalid", query: query });
    return false;
  }
	this.controller.seoPath(newQuery);
};

/*
 * Will return true if the query is suggestion text or empty.
 *
 * query: The search query to examine.
 * 
 */
Search.prototype.invalid = function(query) {
  if (jQuery.inArray(query, INVALID_QUERIES) >= 0) {
    return true;
  }
  return false;
};

/*
 * This object provides the interface to the OnesearchService 
 * on the server and all communication between the client and 
 * server via AJAX.
 *
 * channel: The channel to search in.
 *
 */
OnesearchService = function(channel) {
	this.channel = channel;
};

/*
 * Retrieves the seo_path for the provided query or dimension id.
 *
 * query: The user entered search query
 * dimensionId: The N= value of the dimension, known if this was autocompleted.
 * 
 */
OnesearchService.prototype.seoPath = function(query) {
	var self = this;
	jQuery.getJSON(ONESEARCH_URL + "/seopath?callback=?", { q: query, channel: this.channel, application: APPLICATION }, function(response) {
		if (response.seopath) {
			self.handleSuccess(response);
		} 
		else {
			self.handleError(response);
		}
	});
};

/*
 * This function gets fired when the search returns a seo path
 * successfully. It will in turn fire the success event for the 
 * application to handle accordingly.
 *
 * seoPath: The seo path returned from the service.
 *
 */
OnesearchService.prototype.handleSuccess = function(response) {
  var seoPath = response.seopath;
	// TODO: Need to change the name of the form.
	jQuery("#search_form").unbind("submit", getSeoPath);
	jQuery("body").trigger({ type: "onesearch-success", seoPath: seoPath, query: response.query, geocode: response.geocode, radius: response.radius, sortfield: response.sortfield });
	PROCESSING = false;
};

/*
 * This function gets fired when the search returns an error, 
 * currently this will happen if there are no results from the search.
 *
 * response: The error response from the server.
 *
 */
OnesearchService.prototype.handleError = function(response) {
	jQuery("body").trigger({ type: "onesearch-error-noresults", message: response.message, query: response.query });
	PROCESSING = false;
};

/*
 * This function sets up the global options "hash" for OneSearch.
 * If the options have already been set, it will ignore them.
 *
 * options.highlight: The function that gets called when an item is highlighted.
 *
 */
setupOptions = function(options) {
	if (!ONESEARCH_OPTIONS) {
		ONESEARCH_OPTIONS = options;
	}
};

/*
 * This function is called when the user selects an item from 
 * the autocomplete list - will trigger the success event with the seo path.
 *
 */
selectLocation = function() {
    var seoPath = jQuery("#seopath").attr("value");
    var geoCode = jQuery("#geocode").attr("value");
    var radius = jQuery("#radius").attr("value");
    var sortField = jQuery("#sortfield").attr("value");
    var query = jQuery("#user_search").attr("value");
    jQuery("#search_form").unbind("submit", getSeoPath);
    jQuery("body").trigger({ type: "onesearch-success", seoPath: seoPath, query: query, geocode: geoCode, radius: radius, sortfield: sortField });
    PROCESSING = false;
};


/*
 * Creates a new Search and retrieves the seo path for the users
 * selection in the autocomplete or value in the search box.
 *
 */
getSeoPath = function() {
  if (!PROCESSING) { 
  	PROCESSING = true;
  	var query = jQuery("#user_search").attr("value");
  	new Search(new OnesearchService(channel)).execute(query);
  }
  else {
    selectLocation();
  }
  return false;
};var channel = "apartments";
var valid_key = false;
var default_records_per_page = 20;
var dummy_search_options = ['Price-Range','Bedrooms','Bathrooms'];

$(document).ready(function(){
    do_eraseCookies();
    $("form#aspnetForm").unbind('submit');
    $("#aspnetForm").attr("action", "/");
	$("input#user_search").oneautocomplete({ highlight: highlightItem });
    $("#search_form").onesearch();

    $("body").bind("onesearch-success", onesearchSuccess);
    $("body").bind("onesearch-error-noresults", onesearchNoResults);
    $("body").bind("onesearch-error-invalid", onesearchInvalid);
    
    $("#osClear").bind("click", InitControl);
    
	INVALID_QUERIES = ["City, State or Zip", "College, State", "Military Base, State", ""];

    var savedVal = "";
    if ($('#overrideInit').val()) {
        savedVal = $('#hdn_init').val();
    }
    else {
        savedVal = readCookie("user.search");
    }
	if (!savedVal) {
	    savedVal = $('#hdn_init').val();
        if ((savedVal==="undefined")||(!savedVal)) {
            savedVal = "";
        } 
	}
    var vals = savedVal.match(/.*(\d{5,5})/);
    if(vals != null && vals[1] != null) {
	    savedVal = vals[1];
	}
    if ($('#blankOneSearch').val()) {
        savedVal = "";
    }
	$("input#user_search").val(savedVal);

});

function highlightItem(value, term) {
  return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
}

function exists(value) {
  return ((value != null) && (value.length > 0) && ($.inArray(value, dummy_search_options) == -1) );
}

function GetRefinements() {
    if (!$("[id$='_searchRefinement']").length) {
        return "";
    }

    var seoText = "";
    var endecaIds = "";
    var vals = [];
    
    if ($("[id$='_propertyTypes']").length) {
        if ($(".property_types input[type=checkbox][checked]").length != $(".property_types input[type=checkbox]").length) {
            $(".property_types input[type=checkbox][checked]").each(function(){
                vals.push([this.value, this.id.replace("_CheckBox","") + "-", ""]);
            }); 
        }
    }
    
    var ctrl = $("#pricerange");
    if (ctrl.val() != "-1") {
        vals.push([ctrl.val(), ctrl.find('option').filter(':selected').text().replace(new RegExp("\\$", "g" ), ""), "Price-Range-"]);
    }

    ctrl = $("#bedrooms");
    if (ctrl.val() != "-1") {
        vals.push([ctrl.val(), ctrl.find('option').filter(':selected').text(), "Beds-"]);
    }

    ctrl = $("#fullbaths");
    if (ctrl.val() != "-1") {
        vals.push([ctrl.val(), ctrl.find('option').filter(':selected').text(), "Baths-"]);
    }
    
    var sep = "";
    $(vals).each(function(index, value){
	    endecaIds += sep + value[0];
	    seoText += value[1] + ((value[2] != "") ? "-" + value[2] : "");
        sep = "+";
    }); 
    if (sep != "") {
        endecaIds += "/";
    }
    return seoText + endecaIds;
}
 
function InitControl() {
    $("input#user_search").val("");
} 
      
function onesearchSuccess(event) {
   var search_val = $("#user_search").val();
    createCookie("user.search", search_val);
   //if the search_val contains 5 digits (a possible zip code), replace the field value with just the 5 digits
	var vals = search_val.match(/.*(\d{5,5})/);
	if(vals != null && vals[1] != null) {
		search_val = vals[1];
		$("#user_search").val(search_val);
	}
    var post_url = (event.seoPath.substring(0, 1) == "/") ? event.seoPath : "/" + event.seoPath;
    CalldcsMultiTrack();
    do_redirect(post_url + GetRefinements());
    //do_submitForm(post_url + GetRefinements());
}
function do_redirect(url){
    do_setCookies();
    if ($('#isaptdomain').val().toLowerCase() == 'true') {
        url = url.replace('/Rental-Listings', '');
    }
    window.location.href = url;
}
function do_submitForm(url){
    var submitForm = getNewSubmitForm();
    createNewFormElement(submitForm, "geocode", jQuery("#geocode").val());
    createNewFormElement(submitForm, "radius", jQuery("#radius").val());
    createNewFormElement(submitForm, "sortfield", jQuery("#sortfield").val());
    submitForm.action= url;
    submitForm.submit();
}
function do_setCookies() {
    createCookie("geocode", jQuery("#geocode").val());
    createCookie("radius", jQuery("#radius").val());
    createCookie("sortfield", jQuery("#sortfield").val());
}
function do_eraseCookies() {
    eraseCookie("geocode");
    eraseCookie("radius");
    eraseCookie("sortfield");
}
function onesearchNoResults(event) {
	searchErrorMessage(event.message);
}

function onesearchInvalid(event) {
	searchErrorMessage("You must enter a city, state or a zip code before this search can be performed.");
}

function searchErrorMessage(message){
    $("#searchErrors").text(message).show();
    $("body").bind('click.searchErrors', function(){
        $("#searchErrors").hide();
        $("body").unbind('click.searchErrors');
    });
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else {
	    var expires = "";
	}
	var val = escape(value);
	if(name=="user.search")
	    document.cookie = name+"="+val+expires+";domain=.rentals.com;";
	else
	    document.cookie = name+"="+val+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = unescape(ca[i]);
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) { 
		    return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function CalldcsMultiTrack(){
    var clickValue = $("input#typed").val();
    var selSearch = $("#user_search").val();
    dcsMultiTrackClick('DCS.dcsuri', 'Multitrack', 'DCSext.clicktype', 'search', 'DCSext.clickvalue', clickValue, 'DCSext.search', clickValue, 'DCSext.selsearch', selSearch);
}

//helper function to create the form
function getNewSubmitForm(){
    var submitForm = document.createElement("FORM");
    document.body.appendChild(submitForm);
    submitForm.method = "POST";
    return submitForm;
}

//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
    var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>");
    inputForm.appendChild(newElement);
    newElement.value = elementValue;
    return newElement;
}