/*jslint browser: true */
/*global window, jQuery, cleanPopup, hidePopup */
(function($) {

	if (typeof (Array.prototype.indexOf) === 'undefined') {
		Array.prototype.indexOf = function(item) {
			for (var i = 0; i < this.length; i++) {
				if (this[i] === item) {
					return i;
				}
			}
			return -1;
		};
	}
	String.prototype.splitUrls = function() {
		var urls = this.split(',http');
		for (var i = 0; i < urls.length; i++) {
			if (i > 0) {
				urls[i] = 'http' + urls[i];
			}
		}
		return urls;
	};
	var debug = false;
	jQuery.fn.log = function(msg) {
		if (debug && console) {
			console.log("%s: %o", msg, this);
		}
		return this;
	};

	jQuery.fn.extend({
		executeOnce : function(label, delay, fn, option) {
			return this.each(function() {
				jQuery.timer.delayExecute(this, delay, label, fn, option);
			});
		},
		stopExecution : function(label) {
			return this.each(function() {
				jQuery.timer.remove(this, label);
			});
		}
	});

	jQuery.extend({
		timer : {
			delayExecute : function(element, delay, label, fn, option) {
				var timer = jQuery.data(element, label);
				if (timer) {
					if (timer.timerId) {
						if (option === 'block') {
							return;
						}
						window.clearTimeout(timer.timerId);
						timer.timerId = null;
					}
				} else {
					timer = {};
					jQuery.data(element, label, timer);
				}
				var timerId;
				var handler = function() {
					if (timer.timerId === timerId) {
						timer.timerId = null;
						fn.call(element);
					} else {
					}
				};
				timerId = timer.timerId = window.setTimeout(handler, delay);

			},
			remove : function(element, label) {
				var timer = jQuery.data(element, label);
				if (timer) {
					if (timer.timerId) {
						window.clearTimeout(timer.timerId);
						timer.timerId = null;
					}
				}
			}
		}
	});

	$.fn.document = function() {
		var element = this[0];
		if (element.nodeName.toLowerCase() === 'iframe') {
			return element.contentWindow.document;
		} else {
			return $(this);
		}
	};
	
  	var getTransparent = function(el) {
  		for(var n=0;n<el.parents().length;n++) {
			var parent = el.parents().get(n);
			var pBg = $.browser.safari ? $(parent).css("background") : $(parent).css("background-color");
			if (pBg !== '' && pBg !== 'transparent') {
				return pBg;
			}
		}
		return '#FFF';
  	};

	$.fn.hoverClass = function(clsName) {
		this.bind('mouseover',function(e) {$(this).addClass(clsName);}).bind('mouseout',function(e) {$(this).removeClass(clsName);});
        return this;
	};
	var fadeFx = function(opts) {
		opts.showAnim	   = { opacity: 1 };
		opts.hideAnim   = { opacity: 0 };
		opts.cssBeforeShow = { opacity: 0,display:''};
		opts.cssAfterShow = { opacity:''};

        if (opts.hideSpeed === 0) {
        	opts.hideSpeed = 50;
        }
	    if (opts.showSpeed === 0) {
	    	opts.showSpeed = 50;
	    }
		opts.sync=false;
		opts.beforeHide.push(function(toHide) {
		    var offset = toHide.position();
			this.cssBeforeHide = {top:offset.top + 'px',left:offset.left + 'px',opacity:1,zIndex:100000,position:'absolute'}; 
			this.cssAfterHide = {position:'',top:'',left:'',opacity:'',zIndex : '',display:'none'};
		});
		opts.beforeShow.push(function(toShow) {
		    var h = toShow.outerHeight();
		    var w = toShow.outerWidth();
		    var ph = toShow.parent().outerHeight();
		    var pw = toShow.parent().outerWidth();
		    var y = (ph-h)/2;
			var x = (pw-w)/2;
 			var offset = this.jqContentContainer.position();
            toShow.css({position:'absolute',top: (offset.top + y) + 'px',left: (offset.left + x) + 'px'});
		});
		opts.cssAfterShow = {zIndex:'',position : '',left:'',top:'',textAlign:'center',verticalAlign:'middle'};
		opts.cssAfterShow = {zIndex:''};

	};

	var vScrollFx = function(opts) {
		opts.hideAnim   = { height: 'hide' };
		opts.showAnim = { height: 'show' };
		opts.cssAfterShow = { display: '',top:'0px'};
		opts.hideSpeed = 1300;
	    opts.showSpeed = 1300;
	};

	var tossFx = function(opts) {
		if (opts.xOffset === 0) {
			opts.xOffset = 100;
		}
		if (opts.yOffset === 0) {
			opts.yOffset = 50;
		}
		opts.beforeHide.push(function(toHide) {
		    var offset = toHide.position();
			var color = getTransparent(toHide);
			this.cssBeforeHide = {top:offset.top + 'px',left:offset.left + 'px',opacity:1,zIndex:100000,backgroundColor:color,position:'absolute'};
			
			this.cssAfterHide = {position:'',top:0,left:0,opacity:'',zIndex : '',display:'none'};
			this.cssBeforeShow = {opacity:0,zInex:990000,display:''};//,verticalAlign: 'middle'};//top:'',left:'',position:'static'};
			this.cssAfterShow = {opacity:'',zIndex:''};
			this.hideAnim = {left: (offset.left + this.xOffset) + 'px', top: (offset.top - this.yOffset) + 'px',opacity:0};

		});
		if (this.removeAfterHide) {
			opts.afterHide.push(function(toHide) {toHide.remove();});
		}
		if ($.browser.msie) { 
			opts.beforeShow.push(function(toShow) {
		    	if (this.dynamicLoad && toShow[0].tagName === 'IMG' && this.center) {
		        	var h = toShow.outerHeight();
		        	var ph = toShow.parent().outerHeight();
					var m = (ph-h)/2;
					if (m > 0) {
						toShow.css('marginTop', m + 'px');
					}
		    	}
			});
        }
		opts.showAnim = { opacity:1 };
		opts.sync = true;
		opts.hideSpeed = 1200;
		opts.showSpeed = 500;
	};

	var zoomFx = function(opts) {
		opts.beforeHide.push(function(toHide) {
			var pw = toHide.parent().outerWidth();
			var ph = toHide.parent().outerHeight();
			var w = toHide.outerWidth();
			var h = toHide.outerHeight();
			var x = (pw-w)/2;
			var y = (ph-h)/2;
		    var offset = toHide.position();
			var color = getTransparent(toHide);
			this.cssBeforeHide = {top:offset.top + 'px',left:offset.left + 'px',width:w + 'px',height: h + 'px',opacity:1,zIndex:100000,backgroundColor:color,position:'absolute'};
			this.jqContentContainer.css('display','block');
			offset = this.jqHideTarget.position();

			this.hideAnim={width:this.jqHideTarget.outerWidth() + 'px',height:this.jqHideTarget.outerHeight() + 'px',top:offset.top + 'px',left: offset.left + 'px'};

		});
		if (this.removeAfterHide) {
			opts.afterHide.push(function(toHide) {toHide.remove();});
		}
		opts.beforeShow.push(function(toShow) {
		    var offset = this.jqShowSrc.position();
			var ws = this.jqShowSrc.outerWidth();
			var hs = this.jqShowSrc.outerHeight();
			var pw = this.jqContentContainer.outerWidth();
			var ph = this.jqContentContainer.outerHeight();
			var w = toShow.outerWidth();
			var h = toShow.outerHeight();
			var x = (pw-w)/2;
			var y = (ph-h)/2;
			var color = getTransparent(toShow);
			this.cssBeforeShow = {top:offset.top + 'px',left:offset.left + 'px',width:ws + 'px',height: hs + 'px',opacity:1,zIndex:100000,backgroundColor:color,position:'absolute'};
			var parent = this.jqContentContainer;
			offset = this.jqContentContainer.position();
			this.showAnim = { width: w + 'px',height: h + 'px',left: (offset.left + x)+ 'px',top: (offset.top + y)+ 'px'};

		});

		opts.cssAfterShow = {zIndex:'',position : '',left:'',top:'',textAlign:'center'};
		opts.cssAfterShow = {zIndex:''};
		opts.sync = true;
		if (opts.hideSpeed === 0) {
			opts.hideSpeed = 200;
		}
		if (opts.showSpeed === 0) {
			opts.showSpeed = 200;
		}
	};

	var zoomxFx = function(opts) {
		opts.beforeHide.push(function(toHide) {
			var pw = toHide.parent().outerWidth();
			var ph = toHide.parent().outerHeight();
			var w = toHide.outerWidth();
			var h = toHide.outerHeight();
			var x = (pw-w)/2;
			var y = (ph-h)/2;
			this.cssBeforeHide = {};
			this.hideAnim={width:'hide'};
			//if ($.browser.msie) { 
		    	//if (this.dynamicLoad && toHide[0].tagName == 'IMG' && this.center) {
		    	if (this.center) {
		        	var h2 = toHide.outerHeight();
		        	var ph2 = toHide.parent().outerHeight();
					var m = (ph2 - h2) / 2;
					if (m > 0) {
						toHide.css('marginTop', m + 'px');
					}
		    	}
        	//}

		});
		if (this.removeAfterHide) {
			opts.afterHide.push(function(toHide) {toHide.remove();});
		}
		opts.beforeShow.push(function(toShow) {
			var pw = toShow.parent().outerWidth();
			var ph = toShow.parent().outerHeight();
			var w = toShow.outerWidth();
			var h = toShow.outerHeight();
			var x = (pw-w)/2;
			var y = (ph-h)/2;
			this.cssBeforeShow = {};
			this.showAnim = { width:'show'};
			//if ($.browser.msie) { 
		    	//if (this.dynamicLoad && toShow[0].tagName == 'IMG' && this.center) {
		    	if (this.center) {
		        	var h2 = toShow.outerHeight();
		        	var ph2 = toShow.parent().outerHeight();
					var m = (ph2 - h2) / 2;
					if (m > 0) {
                		toShow.css('marginTop', m + 'px');
					}
		    	}
        	//}

		});

		//opts.sync = true;
		opts.hideSpeed = 800;
		opts.showSpeed = 1200;
	};
	
	var shuffleFx = function(opts) {
		opts.beforeHide.push(function(toHide) {
			var w = toHide.parent().outerWidth();
			var offset = toHide.position();
			var offset2 = toHide.parent().position();
			var color = getTransparent(toHide);
			//toHide.css('background-color', color);
			this.cssBeforeHide = {top:offset.top + 'px',left:offset.left + 'px',zIndex:800000,position:'absolute',backgroundColor:color};
			this.cssAfterHide = {top:'',left:''};//,zIndex :'',position:''};//,opacity:''};
			this.hideAnim = {left: '-=' + (w+this.xOffset) + 'px',top:'-=' + this.yOffset + 'px'};//,opacity:.4};
			this.hideAnim2 = {left: '+=' + (w+this.xOffset) + 'px',top:'+=' + this.yOffset + 'px'};//,opacity:0};

			this.cssBeforeShow = {zIndex:990000,opacity:0,position:'absolute',backgroundColor:color};
			this.cssAfterShow = {zIndex: ''};
			this.showAnim = {opacity:1};

		});
		opts.doHideAnimate = function(jqToHide,jqToShow) {
			var mgr = this;
			jqToHide.animate(this.hideAnim, this.hideSpeed).animate(mgr.hideAnim2, mgr.hideSpeed, function() { //
					jqToHide.hide();
					mgr.doAfterHide(jqToHide);
            });
			this.doShow(jqToShow);
		};

		opts.beforeShow.push(function(toShow) {
			
			var pw = toShow.parent().outerWidth();
			var ph = toShow.parent().outerHeight();
			var w = toShow.outerWidth();
			var h = toShow.outerHeight();
			var x = (pw-w)/2;
			var y = (ph-h)/2;
			this.cssBeforeShow = {};
			if ($.browser.msie) { 
		    	if (this.center) {
		        	var h2 = toShow.outerHeight();
		        	var ph2 = toShow.parent().outerHeight();
					var m = (ph2 - h2) / 2;
					if (m > 0) {
                		toShow.css('marginTop', m + 'px');
					}
		    	}
        	}

		});

		opts.sync = true;
		opts.hideSpeed = 500;
		opts.showSpeed = 100;

	};
	var replaceImage = function (jqToHide, jqToShow) {
		this.doBeforeHide(jqToHide);
		this.doAfterHide(jqToHide);
		jqToHide.attr('src',jqToShow.attr('src'));
		this.doAfterShow(jqToHide);
	};
	var replaceContent = function (jqToHide, jqToShow) {
		this.doBeforeHide(jqToHide);
		jqToHide.hide();
		this.doAfterHide(jqToHide);
		jqToShow.show();			  
		this.doAfterShow(jqToShow);
	};
		
	var defaultDisplayMgr = {
	    fx:'',
		hideAnim: null,
	    hideSpeed: 0,
		cssBeforeHide : {},
		cssAfterHide : {},
		beforeHide : [],
		afterHide : [],
	    showAnim : null,
	    showSpeed:0,
		cssBeforeShow : {},
		cssAfterShow : {},
		beforeShow : [],
		afterShow : [],
		sync: false,
		removeAfterHide : false,
		xOffset :0,
		yOffset :0,
		doBeforeHide : function(jqToHide) {
			var param = [jqToHide];
			for (i=0; i < this.beforeHide.length; i++) {
				this.beforeHide[i].apply(this,param);
			}
			jqToHide.css(this.cssBeforeHide);
		},
		doAfterHide : function(jqToHide) {
			var param = [jqToHide];
			for (i=0; i < this.afterHide.length; i++) {
				this.afterHide[i].apply(this,param);
			}
			jqToHide.css(this.cssAfterHide);
			jqToHide.hide();
            if (typeof this.onHide === 'function') {
            	this.onHide();
			}
		},
		doBeforeShow : function(jqToShow) {
			var param = [jqToShow];
			for (i=0; i < this.beforeShow.length; i++) {
				this.beforeShow[i].apply(this,param);
			}
			jqToShow.css(this.cssBeforeShow);
		},
		doAfterShow : function(jqToShow) {

			var param = [jqToShow];
			for (i=0; i < this.afterShow.length; i++) {
				this.afterShow[i].apply(this,param);
			}
            jqToShow.css(this.cssAfterShow);
			jqToShow.css('opacity',1).show(); // opacity bit needed to handle reinit case
			if ($.browser.msie) {
				jqToShow[0].style.removeAttribute('filter');
			}
            if (typeof this.onShow === 'function') {
            	this.onShow();
            }
		},
		doHideAnimate : function(jqToHide,jqToShow) {
			var mgr = this;
			jqToShow.hide();
			jqToHide.animate(this.hideAnim, this.hideSpeed, function() { //
				jqToHide.hide();
				mgr.doAfterHide(jqToHide);
				if (!mgr.sync) {
					mgr.doShow(jqToShow);
				}
            });
			if (mgr.sync) {
				this.doShow(jqToShow);
			}
		},
		doShowAnimate : function(jqToShow) {
			var mgr = this;
            jqToShow.animate(this.showAnim, this.showSpeed, function() {
				jqToShow.show();
				mgr.doAfterShow(jqToShow);
             });
		},
		doShow : function (jqToShow) {
			this.doBeforeShow(jqToShow);
 			if (this.showAnim && this.showSpeed) {
				this.doShowAnimate(jqToShow);
			} else {
				jqToShow.show();
				this.doAfterShow(jqToShow);
            }
		},
		doHide : function(jqToHide,jqToShow) {
			this.doBeforeHide(jqToHide);
 			if (this.hideAnim && this.hideSpeed) {
				this.doHideAnimate(jqToHide,jqToShow);
 			} else {
				jqToHide.hide();
				this.doAfterHide();
			    this.doShow(jqToShow);
	        }
		},
		toggleDisplay : function(jqToHide,jqToShow) {
			this.doHide(jqToHide,jqToShow);
		},
		init : function () {
			switch(this.fx) {
				case 'toss':
					tossFx(this);
					break;
				case 'zoom':
					zoomFx(this);
					break;
				case 'vScroll':
					vScrollFx(this);
					break;
				case 'fade':
					fadeFx(this);
					break;
				case 'shuffle':
					shuffleFx(this);
					break;
				case 'replaceContent':
					this.toggleDisplay = replaceContent;
					break;
				case 'replaceImage':
					this.toggleDisplay = replaceImage;
					break;
			}

		}
	};
	
	var defaultContentMgr = {
		id : "contentMgr",
		display:$.extend({},defaultDisplayMgr),
		alternateDisplay: null,
		contents:null,
		urlSelect:null,
		activeIndex: 0,
		maxIndex:0,
		wrapIndex : true,
		dynamicLoad : false,
		removeAfter : false,
		isImage : false,
		urlList : null,
		jqContainer: null,
		jqContents : null,
		jqCacheContents : null,
		cache : false,
		slideShowDelay : 500,
		slideShowCycle : 2000,
		slideShowEnabled : false,
		beforeDynamicLoad : function () {
		},
		afterDynamicLoad : function () {
		},
		//initList : [],
		onShow : function () {
//it is possible that hide have not finish
			//this.resetActiveContent();
//do on certian condition only
			this.jqContents = this.jqContainer.find(this.contents);
			this.jqActiveContent = this.jqContents.filter(':visible');

			if (this.slideShowEnabled) {
				this.delayNext();
			}
		},
		onHide : function () {
		},
		delayNext : function (delay) {
			if (this.slideShowEnabled) {
				var mgr = this;
				var handler = function () {
					mgr.next();
				};
				this.jqContainer.executeOnce(this.id+'sstimer',delay || this.slideShowCycle, handler, 'block');
			}
		},
		startSlideShow : function() {
			this.slideShowEnabled = true;
			this.delayNext(this.slideShowDelay);
		},
		stopSlideShow : function () {
			this.slideShowEnabled = false;
			this.jqContainer.stopExecution(this.id+'sstimer');
		},
		resetActiveContent : function () {
			var previous = this.jqActiveContent;
			this.jqActiveContent = this.jqContents.filter(':visible');
			if (this.jqActiveContent.length > 1) {
				var idx = this.jqActiveContent.index(previous[0]);
				this.jqActiveContent = $(this.jqActiveContent[idx === 0 ? 1 :0 ]);
			}
		},
		switchToIndex : function(idx) {
			if (idx !== this.activeIndex) {
				if (this.cache) {
					var url = this.urlList[idx];
					if (this.urlList[url]) {
						this.switchToContent(this.urlList[url]); 
						this.activeIndex = idx;
					} else {
						this.loadContent(url);
					}
				} else if (this.dynamicLoad) {
					this.loadContent(this.urlList[idx]);
				} else {
					this.switchToContent($(this.jqContents[idx]));
					this.activeIndex = idx;
				}
			}
		},
		switchToContent : function(jqTarget) {
			if (this.jqContents.length > 1) {
				this.jqActiveContent = this.jqContents.filter(':visible');
			} else {
				this.jqActiveContent = this.jqContents;
			}
			this.display.jqShowSrc = this.jqShowSrc;
			this.display.jqHideTarget = this.jqCurrent;
			this.display.toggleDisplay(this.jqActiveContent,jqTarget);
		},
		previous : function() {
			if (this.activeIndex > 1) {
				this.switchToIndex(this.activeIndex-1);
			} else if (this.wrapIndex) {
				this.switchToIndex(this.maxIndex);
			}
		},
		next : function() {
			if (this.activeIndex < this.maxIndex) {
				this.switchToIndex(this.activeIndex + 1);
			} else {
				if (this.wrapIndex || this.slideShowEnabled) {
				this.switchToIndex(0);
				}
			}
		},
		loadContent : function (url,idx) {
			this.beforeDynamicLoad();
			if (this.isImage) {
				this.dynamicLoadImage(url);
			} else {
				//call  before dynamic load
				//opts.jqSelected.addClass('loading');
				var mgr = this;
				this.jqActiveContent.parent().loadContent(url,null,function(html) {mgr.afterLoad(url,$(html),false);},null);
			}
		},
		dynamicLoadImage : function (url) {
			var imgPreloader = new Image();
			var mgr = this;
			imgPreloader.onload = function() {
				mgr.afterLoad(url,$(imgPreloader),mgr.display.fx !== 'replaceImage');
			};
			imgPreloader.src = url;
		},
		afterLoad : function (url, elem, append) {
			this.afterDynamicLoad();
			var index = this.urlList.indexOf(url);
			if (append) {
				elem.hide().appendTo(this.jqActiveContent.parent());
			}
			//elem.find('input:text').inputFields();

			if (this.cache) {
				this.urlList[url] = elem;
				this.switchToIndex(index);
			} else {
				this.activeIndex = index;
				this.switchToContent(elem); 
			}
		},
		initContext : function () {
			this.resetActiveContent();
			if (this.urlSelect || this.getUrls) {
				this.dynamicLoad = this.display.dynamicLoad = true;
				if (this.alternateDisplay) {
				    this.alternateDisplay.dynamicLoad = true;
				}
				var urls;
				//for backward compatibility - should be remove
				if (this.getUrls) {
				    urls = this.getUrls();
					this.maxIndex = this.urlList.length -1;
				} else {
				    if (this.urlSelect.charAt(0) === '[' && this.urlSelect.charAt(this.urlSelect.length - 1) === ']') {
				    	//if (this.urlSelect == '[img]') {
					    urls = this.urlSelect.substring(1,this.urlSelect.length-1);
				    } else {
				        urls = this.jqContainer.find(this.urlSelect);
				        if (urls.length > 0) {
					        urls = urls.attr('urls');
				        }
				    }
				    if (urls.length > 0) {
					    this.urlList = urls.splitUrls();
					    this.maxIndex = this.urlList.length -1;
				    }
				}
				
				if (this.isImage) {
					this.activeIndex = urls.indexOf(this.jqContents[0].src);
				//else {
					//this.activeIndex = this.jqContents.index(this.jqActiveContent[0]);
				}
			} else {
				this.maxIndex = this.jqContents.length - 1;
				this.activeIndex = this.jqContents.index(this.jqActiveContent[0]);
			}
		},
		init : function () {
			var mgr = this;
			if (this.jqContainer) {
        		this.jqContents = this.jqContainer.find(this.contents);
			}
			if (this.jqContents) {
				this.display.jqContentContainer = this.jqContents.parent();
				if (this.alternateDisplay) {
					this.alternateDisplay.jqContentContainer = this.jqContents.parent();
				}
				this.initContext();
			}
			//replcae image only if dynamic and isImage
			if (this.display.fx === '') {
				if (this.dynamicLoad && this.isImage) {
					this.display.fx = 'replaceImage';
				} else {
					this.display.fx = 'replaceContent';
				}
			}
			if (this.dynamicLoad && this.fx === 'toss') {
				this.display.removeAfterHide = true;
			}
			this.display.init();
			this.display.onShow = function () {
				mgr.onShow();
			};
			this.display.onHide = function () {
				mgr.onHide();
			};
			if (this.alternateDisplay) {
			    if (this.alternateDisplay.fx === '') {
				    if (this.dynamicLoad && this.isImage) {
					    this.alternateDisplay.fx = 'replaceImage';
				    } else {
					    this.alternateDisplay.fx = 'replaceContent';
				    }
			    }
			    this.alternateDisplay.init();
			    this.alternateDisplay.onShow = function () {
				    mgr.onShow();
			    };
			    this.alternateDisplay.onHide = function () {
				    mgr.onHide();
			    };
			}
			//(this.initList.length);
			if (this.initList)
			for (i=0; i < this.initList.length; i++) {
				this.initList[i].apply(this);
			}

		}
	};
	
	function extendDisplay(displayOptions) {
	    var display=$.extend({},defaultDisplayMgr,displayOptions);
		display.beforeHide = [].concat(defaultDisplayMgr.beforeHide);
		if (displayOptions && displayOptions.beforeHide) {
			display.beforeHide.concat(displayOptions.beforeHide);
		}
		display.afterHide = [].concat(defaultDisplayMgr.afterHide);
		if (displayOptions && displayOptions.afterHide) {
			display.afterHide.concat(displayOptions.afterHide);
		}
		display.beforeShow = [].concat(defaultDisplayMgr.beforeShow);
		if (displayOptions && displayOptions.beforeShow) {
			display.beforeShow.concat(displayOptions.beforeShow);
		}
		display.afterShow = [].concat(defaultDisplayMgr.afterShow);
		if (displayOptions && displayOptions.afterShow) {
			display.afterShow.concat(displayOptions.afterShow);
		}
		return display;
	}

	$.fn.configureContentManager = function(options) {
		if (options.contents === undefined) {
        	options.contents = '>';
		}

	    var settings = $.extend({},defaultContentMgr,options);
	    settings.display = extendDisplay(options.display);
	    if (options.alternateDisplay) {
	        settings.alternateDisplay = extendDisplay(options.alternateDisplay);
	    }

		var doClone = this.length > 1;
		this.each(function() {
			var config = doClone ? $.extend({},settings) : settings;
			config.jqContainer = $(this);
			if (doClone) {
				config.display = $.extend({},settings.display);
				if (config.alternateDisplay) {
				    config.alternateDisplay = $.extend({},settings.alternateDisplay);
				}
			}
			config.init();
		    jQuery.data(this, config.id, config);
		});
		return this;

	};
	
	jQuery.fn.extend({
		startSlideShow: function() {
			this.each(function() {
		    	var contentMgr = jQuery.data(this, defaultContentMgr.id);
				if (contentMgr)
					contentMgr.startSlideShow();
			});
			return this;
		},
		stopSlideShow: function() {
			return this.each(function() {
		    	var contentMgr = jQuery.data(this, defaultContentMgr.id);
				if (contentMgr)
					contentMgr.stopSlideShow();
			});
		}
	});


	/*
	 * $('conatiner').hoverSlideShow(options)
	 */
	$.fn.hoverSlideShow = function(options) {
		this.configureContentManager(options);
		return this.each(function() {
			$(this).bind('mouseleave',function(e) {
				$(this).stopSlideShow();
			}).bind('mouseenter',function(e) {
				$(this).startSlideShow();
			});
		});
	};

	var navMgr = {
	    navId : null,
		locked:false,
		navs : 'li',
		selectedClass:'selected',
		disabledClass:'disabled',
		hoverClass: 'hover',
		nextButton: null,
		previousButton : null,
        previousButtonHoverClass : null,
        nextButtonHoverClass : null,
		activeClass : 'active',
		contentContainer:null,
		initList : [],
		activeNavIndex : 0,
		getActiveIndex : function () {
		    return this.activeNavIndex;
		},
		beforeDynamicLoad : function () {
			if (this.onloadClass) {
				this.jqSelected.addClass(this.onloadClass);
			}
		},
		afterDynamicLoad : function () {
			if (this.onloadClass) {
				this.jqSelected.removeClass(this.onloadClass);
			}
		},
		navSelection : function () {
			this.jqShowSrc = this.jqSelected;
			this.activeNavIndex = this.jqNavs.index(this.jqSelected);
			this.switchToIndex(this.activeNavIndex);
		},
		nextTab : function () {
		    var mgr = this;
			if (!mgr.locked) {
			    mgr.locked = true;
			    mgr.jqCurrent = mgr.jqNavs.filter('.' + mgr.selectedClass);
			    mgr.activeNavIndex = mgr.jqNavs.index(mgr.jqCurrent);
			    mgr.nextTabIndex();
			    mgr.jqSelected = $(mgr.jqNavs[mgr.activeNavIndex]);
			    mgr.navSelection();
	        }
		},
		nextTabIndex : function() {
		    if (this.activeNavIndex == this.maxIndex)
		        this.activeNavIndex =0;
	        else
				this.activeNavIndex++;
        },
        previousTabIndex : function () {	
        	if (this.activeNavIndex == 0)
				this.activeNavIndex =this.maxIndex;
			else
				this.activeNavIndex--;
	    },
		addToInitList : function () {
		    this.initList.push(function() {
				var mgr = this;
				if (mgr.navId) {
                    jQuery.data(mgr.jqNavContainer[0], mgr.navId,mgr);
                }
                this.jqNavs = this.jqNavContainer.find(this.navs);
				if (this.jqNavs.length == 0)
					$.log("can't find " + this.navs);
		        this.locked =false;
		        if (this.nextButton) {
		            this.jqNext = this.jqNavContainer.find(this.nextButton);
					if (this.activeClass && this.wrapIndex)
						this.jqNext.addClass(this.activeClass);
					if (this.nextButtonHoverClass)
					    this.jqNext.hoverClass(this.nextButtonHoverClass);
		            this.jqNext.click(function() {
						if ($(this).hasClass(mgr.activeClass) && !mgr.locked) {
            	            if (mgr.alternateDisplay) mgr.display = mgr.alternateDisplay;
						    mgr.nextTab();
						}
					});
		        }
		        if (this.previousButton) {
		            this.jqPrevious = this.jqNavContainer.find(this.previousButton);
					if (this.activeClass && this.wrapIndex)
						this.jqPrevious.addClass(this.activeClass);
					if (this.previousButtonHoverClass) 
					    this.jqPrevious.hoverClass(this.previousButtonHoverClass);
		            this.jqPrevious.click(function() {
						if ($(this).hasClass(mgr.activeClass) && !mgr.locked) {
							mgr.jqCurrent = mgr.jqNavs.filter('.' + mgr.selectedClass);
				    		mgr.activeNavIndex = mgr.jqNavs.index(mgr.jqCurrent);
				    		mgr.previousTabIndex();
							mgr.jqSelected = $(mgr.jqNavs[mgr.activeNavIndex]);
							mgr.locked = true;
            	            if (mgr.alternateDisplay) mgr.display = mgr.alternateDisplay;
							mgr.navSelection();
						}
					});
		        }
		        if (this.hoverClass) {
		            this.jqNavs.hoverClass(this.hoverClass);
		            if (this.jqNext)
		                this.jqNext.hoverClass(this.hoverClass);
		            if (this.jqPrevious)
		                this.jqPrevious.hoverClass(this.hoverClass);
		        }
		        var mgr = this;
		        this.display.afterHide.push(function() {
			        mgr.jqCurrent.removeClass(mgr.selectedClass);
		        });
		        this.display.afterShow.push(function() {
			        if (mgr.jqSelected) {
				        mgr.jqSelected.addClass(mgr.selectedClass);
				        mgr.jqSelected = null;
			        }
			        //update the next/previous if exist
			        mgr.locked = false;
		        });
		        this.mainDisplay = this.display;
		        if (this.alternateDisplay) {
		            this.alternateDisplay.afterHide.push(function() {
			            mgr.jqCurrent.removeClass(mgr.selectedClass);
		            });
		            this.alternateDisplay.afterShow.push(function() {
			            if (mgr.jqSelected) {
				            mgr.jqSelected.addClass(mgr.selectedClass);
				            mgr.jqSelected = null;
			            }
			            //update the next/previous if exist
			            mgr.locked = false;
		            });
		        }
			    this.jqNavs.bind('click', function(e) {
				    e.preventDefault();
                    if (mgr.locked) {
	 				    this.blur();
            		    return false;
            	    }           	    
				//selected
				    mgr.jqCurrent = mgr.jqNavs.filter('.' + mgr.selectedClass);
				    mgr.activeNavIndex = mgr.jqNavs.index(mgr.jqCurrent);
					mgr.jqSelected = $(this);

				// if animation is still running, tab is selected or disabled or onClick callback returns false stop here
            	// check if onClick returns false last so that it is not executed for a disabled tab
            	    if (mgr.locked || mgr.jqSelected.is('.' + mgr.selectedClass) || mgr.jqSelected.is('.' + mgr.disabledClass)) {
	 				    this.blur();
            		    return false;
            	    }
            	    mgr.locked = true;
            	    mgr.display = mgr.mainDisplay;
				    mgr.navSelection();
			    });
				
            });
	    }
	};
	
	/*
	 * $('conatiner of tabs').navs(options)
	 */
	$.fn.navs = function(options) {
	    var settings = $.extend({},navMgr,options);
	    settings.initList = [];
	    settings.jqNavContainer = this;
		settings.addToInitList();
		var contents = $(settings.contentsContainer);
		if (contents.length == 0)
			$.log('unable to find nav content' + settings.contentsContainer);
		else
			contents.configureContentManager(settings);
		return this;
	};
	$.fn.applyToNavMgr = function(id, fn) {
        var mgr = jQuery.data(this[0],id);
        if (mgr !== null) {
			fn.apply(this, [mgr]);
        }
		return this;
	};

	$.fn.allowDrag = function(src,options) {
		var dragMgr = null;
		var _drag = function(e) {
			e.preventDefault();
			if (dragMgr)
				dragMgr.drag(e);
		};
		var _dragStop = function(e) {
			e.preventDefault();
			if (dragMgr)
				dragMgr.dragStop(e);
		};
		var mleave = function(e) {
			e.preventDefault();
			if (! e.relatedTarget) {
				if (dragMgr)
					dragMgr.dragStop(e);
			}
		};

		var defaultDragMgr = {
			sensitivity:0,
			trackMouseMove : function(e) {
			},
			drag : function(e) {
				//if (e.which == 1) {
				if (this.dragMode == 'start') {
					var xDelta = e.pageX - this.mX;
					var yDelta = e.pageY - this.mY;
					if ((Math.abs(xDelta) > dragMgr.sensitivity) || (Math.abs(yDelta)  > dragMgr.sensitivity)) {
						this.dragMode = 'dragging';
					}
				}
				if (this.dragMode == 'dragging') {
					this.trackMouseMove(e);
				}
				/*} else {
					this.dragStop(e);
				}*/
			},
			dragStop : function (e) {
				if (this.dragMode) {
					$(document).unbind('mousemove',_drag).unbind('mouseup',_dragStop).unbind('mouseout',mleave);
					dragMgr = null;
					this.dragMode = null;
				}
			}
		};
		var content = this;
		$(src,this).bind('mousedown',function (e) { 
			if (dragMgr == null || !dragMgr.dragMode) {
			    e.preventDefault();
				dragMgr =$.extend({},defaultDragMgr, options);
				dragMgr.mX = dragMgr.oX = e.pageX;
				dragMgr.mY = dragMgr.oY = e.pageY;
				dragMgr.offset = content.position();

				dragMgr.dragMode='start';
				$(document).bind('mouseout',mleave).bind('mouseup',_dragStop).bind('mousemove',_drag);
			}
		}).css({cursor:'move'});
		
		return this;
		
	};

	
	/*
 	 * Layer object for popup menu, tooltip, dialog (modal/none modal)
 	 * shimlayer is needed only for <= IE6
	 * shimlayer sizes modal dialog: full window size; none-modal, tooltip, popup: size of container
 	 * zIndex 1000 *n reserve for shim layer
 	 * zIndex 1000 * n + 1 reserver for modal overlay
 	 * zIndex 1000 * n  + 2 reserve for each container 
 	 */	
	var _needShimLayer = ($.browser.msie && ($.browser.version < 7));
	$.layerMgr = {
			_layers : [],
			newLayer : function(content, options) {
				var defaultLayer = {
					cloneData : false,
					onOpen : null,
					onClose : null,
					onOpenEvents : [],
					onCloseEvents : [],
					onInit : function() {},
					addOnOpenEvent : function (f) {
						this.onOpenEvents.push(f);
					},
					open: function (external) {
						if (!external && $.isFunction(this.onOpen)) {
							// execute the onOpen callback 
					        this.onOpen.apply(this);
						}
						else {
							if (this.cloneData) {
					            this.jqClonedContent = this.jqContent.clone().appendTo('body');
							}
							if (this.jqShim) {
								this.jqShim.show();
							}
							if (this.jqOverlay) {
								this.jqOverlay.show();
								//this.jqOverlay.fadeIn('slow');
							}
							this.jqContent.show();
							//this.container.slideDown('slow');
						}
						// bind default events
						this.bindEvents();
					},
					close: function (external) {
						//call close on all layers with higher index than the current index
						$.layerMgr._layers.pop();
						if ($.isFunction(this.onClose) && !external) {
							// execute the onClose callback
							this.onClose.apply(this);
						}
						else {
						    for(var i=0; i < this.onCloseEvents.length; i++) {
							    this.onCloseEvents[i].apply(this);
						    }
							this.jqContent.hide();
							if (this.cloneData) {
							    this.jqContent.remove();
								this.jqContent = this.jqClonedContent;
							}
							if (this.jqOverlay)
								this.jqOverlay.hide();
								//this.jqOverlay.fadeOut('slow');
							if (this.jqShim) {
								//if (this.jqShim == this._modalShimLayer)
								//	this.jqShim.hide();
								//else
									this.jqShim.remove();
							}
						    this.unbindEvents();
						    if (this.src) {
							    this.src._layer = null;
							    this.src = null;
						    }
						}
					},
					trackMouseMove :function(e) {
						var xDelta = e.pageX - this.mX;
						var yDelta = e.pageY - this.mY;
						if ((Math.abs(xDelta) > this.sensitivity) || (Math.abs(yDelta)  > this.sensitivity)) {
							var offset = this.jqContent.position();
							this._moveTo((offset.left + xDelta),(offset.top + yDelta));
							this.mX = e.pageX;
							this.mY = e.pageY;
						}

					},
					bindEvents: function () {
						for(var i=this.onOpenEvents.length-1; i >= 0; i--)
							this.onOpenEvents[i].apply(this);
					},
					unbindEvents: function () {
					},
					createShimLayer : function() {
						if (_needShimLayer)
							return $('<iframe src="javascript:false;" frameBorder=0 class="shim">')
								.css({position: 'absolute',height: '100%',width: '100%',top: '0px',left: '0px'})
								.appendTo('body');
						return null;
					},
					_moveTo : function (left, top) {
						var css = {position:'absolute', top:top+'px', left:left+'px'};
						if (this.jqShim) {
							this.jqShim.css(css);
						}
						this.jqContent.css(css);
						//alert(this.jqContent.html());
					},
					createOverlay : function () { return null; }

				};
		
				function setZindex(layer, index) {
					index = (index + 1) * 1000;
					if (layer.jqShim)
						layer.jqShim.css({zIndex : index});
					++index;
					if (layer.jqOverlay)
						//layer.jqOverlay.css({zIndex : index, opacity : .5});
						layer.jqOverlay.css({zIndex : index});
					++index;
					layer.jqContent.css({zIndex : index});
				}
				function initLayer (layer,content) {
					layer.layers = $.layerMgr._layers;
					layer.layers.push(layer);
					var index = layer.layers.length;
					layer.index = index;
					layer.jqShim = layer.createShimLayer();
					layer.jqOverlay = layer.createOverlay();
					layer.jqContent = $(content);
					layer.onInit();
					setZindex(layer,index);
				}
				var layer = $.extend({}, defaultLayer, options);
				initLayer(layer,content);
				return layer;
			}
		};
		
	jQuery.extendLayer = function(defaultOpts,options) {
		var opts =$.extend({}, defaultOpts, options);
        opts.onOpenEvents = defaultOpts.onOpenEvents ? [].concat(defaultOpts.onOpenEvents): [];
		if (options && options.onOpenEvents)
			opts.onOpenEvents = opts.onOpenEvents.concat(options.onOpenEvents);
        opts.onCloseEvents = defaultOpts.onCloseEvents ? [].concat(defaultOpts.onCloseEvents): [];
		if (options && options.onCloseEvents)
			opts.onCloseEvents = opts.onCloseEvents.concat(options.onCloseEvents);
		return opts;
	};
	function fitHorizontal(x,w) {
	    x -= $(document).scrollLeft(); 
	    return x >= 0  && $(window).width()>= (x + w); 
    }
	function fitVertical(y,h) {
	    y -= $(document).scrollTop(); 
	    return y >= 0 && $(window).height()>= (y + h); 
    }
	/*
	 * $(content).popupLayer(eventSrc,options)
	 */
	$.fn.popupLayer = function(src,options) {
		var defaultPopuLayer = {
			positionBy : 'source',
			//source ref - left is same as bottomLeft
			positionRef : 'bottomLeft',
			targetRef : 'topLeft',
			pointerLength : 0,
			sourceMovable : false,
			xOffset : 0,
			yOffset : 0,
			beforeOpenPopup : function () {},
			targetLeftSrcLeftX : function(srcX,srcW,popupW) {
				this.srcHorPos = 'left';
			    var x = srcX + this.xOffset;
			    if (fitHorizontal(x,popupW)) return x;
                var x2 = srcX + srcW - popupW - this.xOffset;
			    if (fitHorizontal(x2,popupW)) {this.srcHorPos = 'right';return x2;}
	            return x; 
			},			
			targetLeftSrcRightX : function(srcX,srcW,popupW) {
				this.srcHorPos = 'left';
			    var x = srcX + srcW + this.xOffset;
			    if (fitHorizontal(x,popupW)) return x;
			    //try aligning right
			    var x2 = srcX + srcW - popupW - this.xOffset;
			    if (fitHorizontal(x2,popupW)) {this.srcHorPos = 'right';return x2;}
	            return x; 
			},			
			targetRightSrcLeftX : function(srcX,srcW,popupW) {
				this.srcHorPos = 'right';
			    var x = srcX - popupW + this.xOffset;
			    if (fitHorizontal(x,popupW)) return x;
			    //try aligning right
			    var x2 = srcX - this.xOffset;
			    if (fitHorizontal(x2,popupW)) {this.srcHorPos = 'left';return x2;}
			    //align to the edge of the window
	            return x; 
			},			
			targetRightSrcRightX : function(srcX,srcW,popupW) {
				this.srcHorPos = 'right';
			    var x = srcX + srcW - popupW + this.xOffset;
			    if (fitHorizontal(x,popupW)) return x;
			    //try aligning left
			    var x2 = srcX - this.xOffset;
			    if (fitHorizontal(x2,popupW)) {this.srcHorPos = 'left';return x2;}
	            return x; 
			},			
			targetTopSrcTopY : function(srcY,srcH,popupH) {
				this.srcVerPos = 'top';
			    var y = srcY + this.pointerLength + this.yOffset;
			    if (fitVertical(y,popupH)) {
			    	return y;
			    }
			    //try aligning top
			    var y2 = srcY - popupH - this.pointerLength - this.yOffset;
			    if (fitVertical(y2,popupH)) {
			    	this.srcVerPos = 'bottom';
			    	return y2;
			    }
	            return y; 
			},			
			targetTopSrcBottomY : function(srcY,srcH,popupH) {
				this.srcVerPos = 'top';
			    var y = srcY + srcH + this.pointerLength + this.yOffset;
			    if (fitVertical(y,popupH)) return y;
			    var y2 = srcY - popupH - this.pointerLength - this.yOffset;
			    if (fitVertical(y2,popupH)) {this.srcVerPos = 'bottom';return y2;}
	            return y; 
			},			
			targetBottomSrcTopY : function(srcY,srcH,popupH) {
				this.srcVerPos = 'bottom';
			    var y = srcY -popupH - this.pointerLength + this.yOffset;
			    if (fitVertical(y,popupH)) return y;
			    //try aligning bottom
			    var y2= srcY + srcH + this.pointerLength - this.yOffset;
			    if (fitVertical(y2,popupH)) {this.srcVerPos = 'top';return y2;}
				return y;
			},			
			targetBottomSrcBottomY : function(srcY,srcH,popupH) {
				this.srcVerPos = 'bottom';
			    var y = srcY + srcH -popupH - this.pointerLength + this.yOffset;
			    if (fitVertical(y,popupH))return y;
			    var y2 = srcY + srcH + this.pointerLength - this.yOffset;
			    if (fitVertical(y2,popupH)) {this.srcVerPos = 'top';return y2;}
	            return y; 
			},			
			calculateX : function(srcX,srcW,popupW,srcAlign,targetAlign) {
			    if (targetAlign == 'left') {
			        if (srcAlign == 'left') {
			            return this.targetLeftSrcLeftX(srcX,srcW,popupW);
			        } else {
			            return this.targetLeftSrcRightX(srcX,srcW,popupW);
			        }
			    } else {
			        if (srcAlign == 'left') {
			            return this.targetRightSrcLeftX(srcX,srcW,popupW);
			        } else {
			            return this.targetRightSrcRightX(srcX,srcW,popupW);
			        }
			    }
			},
			calculateY : function(srcY,srcH,popupH,srcAlign,targetAlign) {
				//alert(srcAlign + ":" + targetAlign);
			    if (targetAlign == 'top') {
			        if (srcAlign == 'top') {
			            return this.targetTopSrcTopY(srcY,srcH,popupH);
			        } else {
			            return this.targetTopSrcBottomY(srcY,srcH,popupH);
			        }
			    } else {
			        if (srcAlign == 'top') {
			            return this.targetBottomSrcTopY(srcY,srcH,popupH);
			        } else {
			            return this.targetBottomSrcBottomY(srcY,srcH,popupH);
			        }
			    }
			},
			openPopup : function (src) {
				this.src = src;
				this.beforeOpenPopup();
				if (this.sourceMovable) {
				    this.jqSrcContainer = $(this.src).parent();
				    this.jqSrcContainer.css({position:'relative'});
				    this.jqContent.remove().css({position:'absolute'});
				    this.jqSrcContainer.append(this.jqContent);
				    if (this.jqShim) {
				        this.jqShim.remove().appendTo(this.jqSrcContainer);
				    }
			    } 
			    
			    //if (this.jqContent.parent().length == 0)
			    //    this.jqContent.appendTo('body');
				src._layer = this;
				//quickly show the container and its content so that browser can 
				// calculate actual width and height
				this.jqContent.show();
				var w = this.jqContent.outerWidth();
				var h = this.jqContent.outerHeight();
				this.left=0;
				this.top = 0;
				this.offset(src,w,h);
				this.jqContent.hide();
				this._sizeTo(w,h);
				this._moveTo(this.left,this.top);
				this.open();
			},
			offset : function(src,w,h) {
					var jqSrc = $(src);
					if (this.positionBy == 'source') {
						if (this.positionRef == 'left') this.positionRef = 'topLeft';
						this.verPos =this.positionRef == 'topRight' ||this.positionRef == 'topLeft' ? 'top' : 'bottom'; 
						this.horPos = this.positionRef == 'bottomLeft' ||this.positionRef == 'topLeft' ? 'left' : 'right';
						//alert(this.positionRef + "===" + this.targetRef);
						var offset = jqSrc.offset();
						this.left = this.calculateX(offset.left,jqSrc.outerWidth(),w,this.horPos,this.targetRef == 'bottomLeft' || this.targetRef == 'topLeft' ? 'left' : 'right');
						this.top = this.calculateY(offset.top,jqSrc.outerHeight(),h,this.verPos,this.targetRef == 'topRight' ||this.targetRef == 'topLeft' ? 'top' : 'bottom');
						if (this.pointerLength > 0) {
							this.positionClass = '.' + this.srcVerPos + '-' + this.srcHorPos + '-arrow';
							$(this.positionClass,this.jqContent).show();
						}
						if (this.sourceMovable) {
							offset = this.jqContent.parent().offset();
							this.left -= offset.left;
							this.top -= offset.top;
						}
					} else {
						this.left = this.mX + this.xOffset;
						this.top = this.mY + this.yOffset;
					}
				},
			_sizeTo : function (w, h) {
				if (this.jqShim) {
					var css = {width:w+'px', height:h+'px'};
					this.jqShim.css(css);
				}
			}
		};
		var opts = $.extend({}, defaultPopuLayer, options);
		var popup = $.layerMgr.newLayer(this,opts);
		popup.openPopup(src);
		return this;
	};
	/*
	 * $(content).popup(eventSrc,options)
	 */
	var _singlePopupop = null;
	$.fn.popup = function (eventSrc, options) {
		var closePopup = function () {
		    if (_singlePopupop) {
		        _singlePopupop.close();
                _singlePopupop = null;
		    }
		};
		closePopup();
	    var defaultPopup = {
			hooverPopup : false,
		    closeOnClick : true,
			onOpenEvents : [
				function () {
		            _singlePopupop = this;
		            if (this.closeOnClick)
		                $(document).bind('click',closePopup);
					if (this.hooverPopup) {
						//set delay on mouseleave
						this.jqContent.bind("mouseleave", closePopup);
					}

			}],
			onCloseEvents : [
				function () {
		        if (this.closeOnClick)
		            $(document).unbind('click',closePopup);
				if (this.hooverPopup) {
				    this.jqContent.unbind("mouseleave", closePopup);
				}
		         _singlePopupop = null;
			}]

		};
		var opts = $.extendLayer(defaultPopup,options);
		$(this).popupLayer(eventSrc,opts);
		return this;
	};

	/*
	 * $(eventSrcs).attachHoverPopup(content,options)
	 */
	$.fn.attachPopup = function(content,startevent,options) {
		// default configuration options
		var defaultPopup = {
			delay: 150,
			sensitivity: 5,
			hooverPopup : true,
			onCloseEvents : [
				function () {
				cleanPopup(this.src);
			}],
			onOpenEvents : [
				function () {
					var popup = this;
					var src = this.src;
					this.jqContent.bind("click", function(e) {
						popup.close();
					})
					.bind("mouseenter", function(e) {
						cleanPopup(src);
					})
					.bind("mouseleave", function(e) {
						//close popup but delay it just in case user move back to the src that trigger
						//of this popup
						hidePopup(src,'container mouseleave');
					});
					$('.closeBtn',popup.jqContent).bind('click',function (e) {
				    	popup.close();
			        });

				}]
		};
		var options = $.extendLayer(defaultPopup,options);
		
		var showPopup = function (content,src,opts) {
			cleanPopup(src);
			$(content).popup(src,opts);
		};
		var hidePopup = function(src,tag) {
			if (src._layer)
				src._hoverPopup_t = setTimeout(function() { if (src._hoverPopup_t && src._layer)src._layer.close();cleanPopup(src);},options.delay);
		};
		var cleanPopup = function(src) {
			if (src && src._hoverPopup_t) { clearTimeout(src._hoverPopup_t); src._hoverPopup_t=null;}
		};
		var jqContent = $(content);
		var events;
		if (options.positionBy == 'mouse') {
			events = ' mousemove mouseleave';
		} else {
			events = ' mouseleave';
		}
		events = startevent + events;
		return this.each(function() {
			var src = this;
			$(src).bind(events,function(e) {
				// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
                if (e.type !== "click") {
					var p = (e.type == "mouseenter" ? e.fromElement : e.toElement) || e.relatedTarget;
					while (p && p !== this) { try { p = p.parentNode; } catch(e) { p = this; } }
					if (p == this) { return false; }
				}
				
				// copy objects to be passed into t (required for event object to be passed in IE)
				var ev = jQuery.extend({},e);

				// else e.type == "onmouseover"
				if (e.type == "mousemove") {
					if (src._layer) {
						//move to new location
						var xDelta = e.pageX - src._layer.mX;
						var yDelta = e.pageY - src._layer.mY;
						if ((Math.abs(xDelta) > options.sensitivity) || (Math.abs(yDelta)  > options.sensitivity)) {
							var offset = src._layer.jqContent.position();
							src._layer._moveTo((offset.left + xDelta),(offset.top + yDelta));
							src._layer.mX = e.pageX;
							src._layer.mY = e.pageY;
						}

					}
				} else if (e.type == "mouseenter" || e.type == "click") {
					if (src._layer) {
						//popup already opend, clear the timer of the 
						//layer so that it does not close the layer
						cleanPopup(src);
					} else {
						//delay opening of popup
						options.mX = e.pageX;
						options.mY = e.pageY;
						src._hoverPopup_t = setTimeout(function() { showPopup(content,src,options);},options.delay);
					}

				} else {
					if (src._layer) {
						hidePopup(src,'src ml');
					} else {
						cleanPopup(src);
					}
				}
				return false;
			});
		});
	};

	/*
	 * $(eventSrcs).attachHoverPopup(content,options)
	 */
	$.fn.attachHoverPopup = function(content,options) {
	    this.attachPopup(content,"mouseenter",options);
	    return this;
	};
	
	var menuOption = {
			name: 'Cat',
			container : '#ui-search-category', //this is just an example
			currentVal : null,
			list : null, // must be provided by caller
            startValue : function () {
                currentVal = $(this.container + ' input').val();
            },
            beforeOpenPopup : function() {
                $('#' + this.name + 'Dropdown li').removeClass("ui-selectmenu-item-focus");  
                $('#' + this.name + 'Dropdown li.itemid' + this.currentVal).addClass("ui-selectmenu-item-focus");  
            },
            createDropDown : function () {
                var str = '<ul id="' + this.name + 'Dropdown" class="ui-selectmenu-menu" >';
                for(var i = 0; i < this.list.length; i++) {
                    str += "<li class='itemid" + this.list[i].id + "'><a href='#'>" + this.list[i].value + "</a></li>";
                }
                str += '</ul>';
                return str;
            },
            getEntry : function(id) {
            	if (id !== null) {
            		for(var i = 0; i < this.list.length; i++) {
            			if (id == this.list[i].id)
            				return this.list[i];
            		}
            	}
                return this.list[0];
            },
            menuSelect : function (li,val) {
            	this.setSelected(val,$(li).find('a').html());
            	$(this.container +" a").focus();
                return this.menuSelected(li,val);
            },
            setSelected : function(val,display) {
            	$(this.container + ' input').val(val);
            	$(this.container + ' .ui-selectmenu').html(display);
            },
            menuSelected : function (li,val) {
                return false;
            },
            
            getCurrentIndex : function(items, currentVal ){
            	var i = 0;
            	for( i=0, size= items.length; i < size; i++){
            		if ($(items[i]).attr("class").substring(6) === currentVal){
        				return i;
        			}
            	}	
        		return i;
            },
            
            bindKeyDownForSeachBox : function(contentId, options) {
            	$(this.container).bind('keydown', {contentId: contentId, options:options}, function(e) {	
                var keyCode = e.keyCode || e.which,
                    arrow = {left: 37, up: 38, right: 39, down: 40 },
                    curElem, currentIndex, container, cls, currentVal;


					switch (keyCode) {
						case arrow.up:
						dropDownBox = $(e.data.contentId);
						currentVal = $(options.container + ' input').val();
						currentAnchor = $(options.container + ' a');
						currentIndex = options.getCurrentIndex(dropDownBox.children(), currentVal );
						currentIndex = (currentIndex === 0 || currentAnchor.css('background-color')==='rgb(221, 221, 221)' || currentAnchor.css('background-color')==='#dddddd')?currentIndex:currentIndex-1;
						curElem = dropDownBox.children().eq(currentIndex);
						$(curElem).removeClass("ui-selectmenu-item-focus");  
						cls=$(curElem).attr('class');
						cls=cls.substring(6);
						e.data.options.menuSelect(curElem,cls);
						e.preventDefault();
						$(e.data.contentId + ' a').focus();
						break;
					case arrow.down:
						dropDownBox = $(e.data.contentId);
						currentVal = $(options.container + ' input').val();
						currentAnchor = $(options.container + ' a');
						currentIndex = options.getCurrentIndex(dropDownBox.children(), currentVal );
						currentIndex = (currentIndex === (dropDownBox.children().size()-1) || (currentAnchor.css('background-color')==='rgb(221, 221, 221)' || currentAnchor.css('background-color')==='#dddddd')) ? currentIndex : currentIndex + 1;
						curElem = dropDownBox.children().eq(currentIndex);
						$(curElem).removeClass("ui-selectmenu-item-focus");  
						cls=$(curElem).attr('class');
						cls=cls.substring(6);
						e.data.options.menuSelect(curElem,cls);
						e.preventDefault();
						$(e.data.contentId + ' a').focus();
						break;
					}
                
              });
            }	
		};
	
	$.fn.popupMenu = function(options,initVal) {
		function clickFunction() {
			$(this).removeClass("ui-selectmenu-item-focus");  
			var cls=$(this).attr('class');
			cls=cls.substring(6);
			var flag = options.menuSelect(this,cls);
			$(document).click();
			return flag;
		}
		function mouseOverFunction() {
			$(contentId + ' li').removeClass("ui-selectmenu-item-focus");
			$(contentId).unbind('mouseover');      
		}
		function createContent() {
			// create content
			$(options.createDropDown()).appendTo('body');
			if (options.list.length > 18) {
				$(contentId).css({height: '435px',overflow : 'auto'});
			}
			$(contentId + ' li').hoverClass("ui-selectmenu-item-focus");
			$(contentId).bind('mouseover',mouseOverFunction);
			$(contentId + ' li').click(clickFunction);

		}

		function clickHandler(e) {
			options.startValue();
			var content = $(contentId);
			if (content.length == 0) {
				createContent();
			} else {
				if ($(contentId + ":visible").length == 1) {
					$(document).click();
					return false;
				}
			}
			$(contentId).popup(this,options);
	        return false;
		}
		var that = {
			popup : $(this),
			enabled: true,
			enable: function() {
				if (this.enabled) {
					return;
				}
				this.popup.bind("click", clickHandler);
				this.popup.css({"background-color":"#ffffff"});
				this.enabled = true;
			},
			disable: function() {
				this.popup.unbind("click", clickHandler);
				this.popup.css({"background-color":"#dddddd"});
				this.enabled = false;
			}
		};
	    var options = $.extend({},menuOption,options);
		var contentId = '#' + options.name + 'Dropdown';
		var values = options.getEntry(initVal);
		options.setSelected(values.id,values.value);
		
		options.bindKeyDownForSeachBox(contentId, options);
		
		// create content
		createContent();
		
		$(this).bind("click",clickHandler);
		return that;
	};
    var defaultBubbleHelp = {
	        width:'320px',
  			delay: 350,
  			className : 'help-tip',
			positionRef : 'topRight',
			targetRef : 'bottomLeft',
			xOffset : -20,
  			pointerLength : 14, 
			onOpenEvents : [
				function () {
 			    	var popup = this;
			    	$('.closeBtn',popup.jqContent).click(function (e) {
				    	//e.preventDefault();
				    	popup.close();
			        });
				}],
            onCloseEvents : [
                function () {
                    if (this.positionClass){
				        $(this.positionClass).hide();
                    }    
                    this.container.remove();
		        }],
		    // overwriteing targetLeftSrcRightX of supperclass since right alligned help arrow needs extra 10 pixels shift to the left
			targetLeftSrcRightX : function(srcX,srcW,popupW) {
				this.srcHorPos = 'left';
			    var x = srcX + srcW + this.xOffset;
			    if (fitHorizontal(x,popupW)) return x;
			    //try aligning right
			    var x2 = srcX + srcW - popupW - this.xOffset-10;
			    if (fitHorizontal(x2,popupW)) {this.srcHorPos = 'right';return x2;}
	            return x; 
			},			
		    xoffset : function(src,w,h) {
				var jqSrc = $(src);
				var sw = jqSrc.outerWidth();
			    var sh = jqSrc.outerHeight();

    			var offset = jqSrc.offset();
    			var horPos = 'right';
    			var verPos = 'bottom';
				var left = offset.left + (sw/2) + this.xOffset;
		        if ($(window).width()-(left -16 - $(document).scrollLeft())> w) {
		        	this.xOffset = -10;
		            horPos = 'left';
		            this.left = left - 16;
		        } else {
		            this.left = left-w+ (sw/2) + 9 + this.xOffset;
		            horPos = 'right';
		        }
    			var top = offset.top + this.yOffset;
				if ($(window).height()-(top + 32 -$(document).scrollTop()+sh)> h) {
				    this.top = top + 32;
				    verPos = 'top';
				} else {
				    this.top = top - h - 9;
				    verPost = 'bottom';
				}
				

				this.positionClass = '.' + verPos + '-' + horPos + '-arrow';
				$(this.positionClass,this.jqContent).show();
				

			},
            container : null
    };
	
	jQuery.extendBubbleHelp = function(options) {
		options = $.extendLayer(defaultBubbleHelp,options);
	    options.container =
 	        	$('<div class="' + options.className + '"><table border="0" cellpadding="0" cellspacing="0" width="100%">' +
				'<tr><td class="help-tip-rtl round-top-left">&nbsp;</td><td class="help-tip-rtm round-top-middle">&nbsp;</td><td class="help-tip-rtr round-top-right">&nbsp;</td></tr>' +
				'<tr><td class="help-tip-rml round-middle-left">&nbsp;</td><td class="help-tip-rm round-middle">' +		
				'<table style="float: left; display: inline;" border="0" cellpadding="0" cellspacing="0" width="100%">' +
				'<tr><td align="left" valign="top" width="100%"><div class="popText"></div></td>' +
				'<td style="padding-left: 3px;" valign="top" width="19px"><div class="closeBtn"></div></td></tr></table>' +
				'</td><td class="help-tip-rmr round-middle-right">&nbsp;</td></tr>' +
				'<tr><td class="help-tip-rbl round-bottom-left">&nbsp;</td><td class="help-tip-rbm round-bottom-middle" width="100%">&nbsp;</td><td class="help-tip-rbr round-bottom-right">&nbsp;</td></tr></table>' +
				'<div class="top-left-arrow">&nbsp;</div><div class="top-right-arrow">&nbsp;</div><div class="bottom-left-arrow">&nbsp;</div><div class="bottom-right-arrow">&nbsp;</div></div>').hide();
        return options;
    };
	
	$.fn.attachHoverBubbleHelp = function(content,options) {
		var opts = $.extendBubbleHelp(options);
		opts.beforeOpenPopup = function() {
			$('.popText',opts.container).html(content);
			opts.container.css({width:opts.width}).appendTo('body');
		};
		this.each(function() { $(this).attachHoverPopup(opts.container[0],opts);});
    };
 	$.fn.attachStaticBubbleHelp = function(content,options) {
		var opts = $.extendBubbleHelp(options);
		opts.closeOnClick =false;
		opts.beforeOpenPopup = function() {
			$('.popText',this.container).html(content);
			this.container.css({width:opts.width}).appendTo('body');
		};
        opts.container.popup(this,opts);
		return this;
    };
    
    var dynamicBubbleHelp=null;
	$.fn.attachDynamicHoverBubbleHelp = function(content,options) {
		if (!dynamicBubbleHelp)
			dynamicBubbleHelp = $.extendBubbleHelp(options);
		dynamicBubbleHelp.beforeOpenPopup = function() {
			$('.popText',dynamicBubbleHelp.container).html($(this.src).data("bubbleHelp"));
			dynamicBubbleHelp.container.css({width:dynamicBubbleHelp.width}).appendTo('body');
		};
 	    this.each(function() {
 	    	$(this).data("bubbleHelp", content);
 	    	$(this).attachHoverPopup(dynamicBubbleHelp.container[0],dynamicBubbleHelp);
 	    	if (this._layer) {
 	    		// if layer visible, update its content
				$('.popText', this._layer.jqContent).html(content);
 	    	}
 	    });
    };
   

    
    jQuery.handleGalleryImageClicks = function(gid) {
    	var va,vah,vac;
		$('#'+gid+' .tn img').click(function(){
			va = $(this).parent().parent().parent().find('a');
			vah = va.attr('href');
			if (va.attr('target')) {
				vac = va.clone();
				vac.attr('target','');
				window.open(vac.attr('href'));
			}
			else {
				window.location = vah;
			}
		})};
		/*
		$('#'+gid+' .gallery-ad-top-nopic, .ad-detail div.price').click(function(){
			va = $(this).parent().find('a');
			vah = va.attr('href');
			if (va.attr('target')) {
				vac = va.clone();
				vac.attr('target','');
				window.open(vac.attr('href'));
			}
			else {
				window.location = vah;
			}
		});
    };
    */

    jQuery.searchBrowseViewConfig  = function(options) {
		var defaultOptions = {
				toggle : '#galleryOption',
				galleryView : false,
				popup : '#imgRolloverPopup',
				popupSize : '_26.jpeg',
				displaySize : '_24.jpeg',
				imageLoaded : false,
				setGalleryViewOption: function(mode) {
					window.location = this.toggleViewURL;
				}
		};
		options = $.extend({},defaultOptions,options);
		if (!options.galleryView) {
			$('body').append('<div id="imgRolloverPopup"><div>e.screenY: <span id="irp-e-screeny"></span></div><div>this.offsetParent.offsetTop+75:<span id="irp-op-ot"></span></div></div>');
			var images = $('.tn img');
			
			/*
			images.click(function() {
				var va = $(this).parent().parent().find('a').attr('href');
				window.location = va;
			});
			*/
			
			images.attr('title','');
			options.popup.scrolled = false;
			var findPos = function(obj) {
				var curleft = 0;
				var curtop = 0;
				if (obj.offsetParent) {
					do {
						curleft += obj.offsetLeft;
						curtop += obj.offsetTop;
					} while (obj = obj.offsetParent);
				}
				return {l: curleft, t: curtop};
			};
			var getOffset = function(n) {
				var p = findPos($(n).siblings()[0]);
				return p.t - window.pageYOffset + 25;
			};
			var himages = $('.tn.wimg img');
			himages.parent().
				mouseover(
					function(e) {
						var src = $('img',this).attr('src');
						$(options.popup).html('<img style="margin-bottom:-5px;" src="' + src.replace(options.displaySize,options.popupSize) + '"/>').show();
						if (!$.browser.msie) {
							var left = $(this).offset().left + this.offsetWidth + 10;
							$(options.popup).css({
										'position': 'fixed',
										'left':left + 'px',
										'padding-bottom': '0',
										'background-color': '#888',
										'top': getOffset(this) + 'px',
										'-moz-box-shadow': '10px 10px 5px #bbb'
										});
						}
						else {
							if (options.popup.scrolled) {
								$(options.popup).hide();
								options.popup.scrolled = false;
							}
							else {
								$(options.popup).css({'left':e.pageX + 15 + 'px','top':e.pageY + 15 + 'px'});
							}
						}
					}).
				mouseout(
					function() {
						$(options.popup).hide();
					}).
				mousemove(
					function(e) {
						if ($.browser.msie) {
							$(options.popup).css({'left':e.pageX + 15 + 'px','top':e.pageY + 15 + 'px'});
						}
					}
				);
			if ($.browser.msie || $.browser.safari) {
				$(window).scroll(
						function(e) {
							options.popup.scrolled = true;
							$(options.popup).hide();
						}
				);
			}
    	}
		$(options.toggle).click(function(e) {
			options.setGalleryViewOption(e.target.checked);
		});
		// make sure checkbox is in sync with toggleurl
		$(options.toggle).attr("checked", (options.toggleViewURL.indexOf("gallery") < 0));
	};
	
	
	var fieldHelpPopup = null;    
	var inputFieldsOptions = {className :'tipField', charCountClass:'charCount'};
	$.fn.inputFields = function() {
		options = inputFieldsOptions;
		if (options.className) {
			$(window).unload(function() {$('.' + options.className).val('');});
		    $('form').submit(function() {$(this).find('.' + options.className).val('');});
		}
		this.each(function() {
    		var $this = $(this);
			var fieldTip = $this.attr('title');

    		var keycount = function(i) {
      			var max = $(this).attr('maxlength');
      			var val = $(this).attr('value');
      			var cur = 0;
      			if (val)
        			cur = val.length;
      			var left = max-cur;
      			var c = $(this).next("span").find(".counter");
      			c.text(left.toString());
      			if (left <= 10)
          			c.css("background","#F4F379");
      			else
          			c.css("background","none");
    		};
      		$this.focus(function() {
				var $$this = $(this);
        		if ($$this.is('.' + options.className)) {
          			$$this.val('').removeClass(options.className);
        		}
				if (fieldHelpPopup) {
					fieldHelpPopup.close();
					fieldHelpPopup = null;
				}
				var fieldHelp = $$this.attr('fieldHelp');
				if (fieldHelp) {
					fieldHelpPopup = $.extendBubbleHelp({});
					fieldHelpPopup.closeOnClick =false;
                    fieldHelpPopup.sourceMovable = true;
					fieldHelpPopup.beforeOpenPopup = function() {
						$('.popText',this.container).html(fieldHelp);
						this.container.css({width:'300px'});
					};
					fieldHelpPopup.container.popup(this,fieldHelpPopup);
					fieldHelpPopup = this._layer;
				}
				if ($$this.is('.' + options.charCountClass)) {
    				var max = $$this.attr('maxlength');
					if (max) {
    					var val = $$this.val();
    					var cur = 0;
    					if (val) // value="", or no value at all will cause an error
      						cur = val.length;
    					var left = max-cur;
    					$$this.after("<span><span class='counter'>"+ left.toString()+"</span> characters remaining</span>");
    					// Style as desired
    					var c = $$this.next("span").find(".counter");
    					c.css("margin-left","10px");
    					c.css("padding", "0 3px 0 3px");
    					c.css("border", "1px solid #ccc");
    					if (left <= 10) {
        					c.css("background","#F4F379");
    					} else {
        					c.css("background","none");
    					}
						$$this.keyup(keycount);

					}

				}
      		});
    
      		$this.blur(function() {
				if (fieldHelpPopup) {
					fieldHelpPopup.close();
					fieldHelpPopup = null;
				}
				var $$this = $(this);
        		if ($$this.val() == '') {
          			$$this.addClass(options.className);
          			$$this.val(fieldTip);
				}
				if ($$this.is('.' + options.charCountClass)) {
					$$this.next('span').remove();
				}
 			});
			if (fieldTip) {
      			if ($.browser.msie && $this.val() == fieldTip) {
        			$this.val('');
      			}
				if ($this.val() === '' && document.activeElement !== this) {
        			$this.addClass(options.className);
					$this.val(fieldTip);
				}
			}
 			
			//return this;
  		});
  		return this;

	};
	$.fn.resetInputFields = function() {
 	    this.find('.' + inputFieldsOptions.className).val('').removeClass(inputFieldsOptions.className);
   };
   
   jQuery.cookie = function(name, value, options) {
	    if (typeof value !== 'undefined') { // name and value given, set cookie
	        options = options || {};
	        if (value === null) {
	            value = '';
	            options.expires = -1;
	        }
	        var expires = '';
	        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
	            var date;
	            if (typeof options.expires == 'number') {
	                date = new Date();
	                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
	            } else {
	                date = options.expires;
	            }
	            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
	        }
	        // CAUTION: Needed to parenthesize options.path and options.domain
	        // in the following expressions, otherwise they evaluate to undefined
	        // in the packed version for some reason...
	        var path = options.path ? '; path=' + (options.path) : '';
	        var domain = options.domain ? '; domain=' + (options.domain) : '';
	        var secure = options.secure ? '; secure' : '';
	        document.cookie = [name, '=', value, expires, path, domain, secure].join('');
	    } 
	    else { // only name given, get cookie
	        var cookieValue = null;
	        if (document.cookie && document.cookie !== '') {
	            var cookies = document.cookie.split(';');
	            for (var i = 0; i < cookies.length; i++) {
	                var cookie = jQuery.trim(cookies[i]);
	                // Does this cookie string begin with the name we want?
	                if (cookie.substring(0, name.length + 1) == (name + '=')) {
	                    cookieValue = cookie.substring(name.length + 1);
	                    break;
	                }
	            }
	        }
	        return cookieValue;
	    }
	};
	
	jQuery.cookielet = function(cookieName, cookieletName, cookiletValue, options) {
		var wholeCookieValue = jQuery.cookie(cookieName);
		if (cookiletValue) { // name and value given, set cookielet
			options = options || {};
			if (wholeCookieValue) {
				var cookiletRegEx = new RegExp('(^|\\^){1}' + cookieletName + '\\^[^^]*');
				if (wholeCookieValue.search(cookiletRegEx) !== -1) {
					wholeCookieValue = wholeCookieValue.replace(cookiletRegEx, '$1'+cookieletName+'^'+cookiletValue);
				} else {
					wholeCookieValue = wholeCookieValue +'^' + cookieletName + '^' + cookiletValue;
				}
				jQuery.cookie(cookieName, wholeCookieValue, options);
			}
			else if (cookiletValue) {
				jQuery.cookie(cookieName, (cookieletName+'^'+cookiletValue+'^'), options);
			}
		} else { // only name given, get cookielet value
			if (wholeCookieValue && wholeCookieValue.length > 0) {
				var ca = wholeCookieValue.charAt(0) !== '^' ? wholeCookieValue.split('^') : wholeCookieValue.slice(1).split('^');
				for(var i=0; i < ca.length - 1; i+=2) {
					if (ca[i] === cookieletName) {
						return ca[i+1];
					}
				}
			}
			return null;
		}
	};
	
	(function($) {
		// modified base 64, padding is set as '!', '/' is '_', '+' is '-'
		var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_!";
		
		var uTF8Encode = function(string) {
			string = string.replace(/\x0d\x0a/g, "\x0a");
			var output = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					output += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					output += String.fromCharCode((c >> 6) | 192);
					output += String.fromCharCode((c & 63) | 128);
				} else {
					output += String.fromCharCode((c >> 12) | 224);
					output += String.fromCharCode(((c >> 6) & 63) | 128);
					output += String.fromCharCode((c & 63) | 128);
				}
			}
			return output;
		};
		
		var uTF8Decode = function(input) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
			while (i < input.length) {
				c = input.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				} else if ((c > 191) && (c < 224)) {
					c2 = input.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				} else {
					c2 = input.charCodeAt(i+1);
					c3 = input.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		}
		
		$.extend({
			base64Encode: function(input) {
				var output = "";
				var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
				var i = 0;
				input = uTF8Encode(input);
				while (i < input.length) {
					chr1 = input.charCodeAt(i++);
					chr2 = input.charCodeAt(i++);
					chr3 = input.charCodeAt(i++);
					enc1 = chr1 >> 2;
					enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;
					if (isNaN(chr2)) {
						enc3 = enc4 = 64;
					} else if (isNaN(chr3)) {
						enc4 = 64;
					}
					output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
				}
				return output;
			},
			base64Decode: function(input) {
				var output = "";
				var chr1, chr2, chr3;
				var enc1, enc2, enc3, enc4;
				var i = 0;
				input = input.replace(/[^A-Za-z0-9\-\_\!]/g, "");
				while (i < input.length) {
					enc1 = keyString.indexOf(input.charAt(i++));
					enc2 = keyString.indexOf(input.charAt(i++));
					enc3 = keyString.indexOf(input.charAt(i++));
					enc4 = keyString.indexOf(input.charAt(i++));
					chr1 = (enc1 << 2) | (enc2 >> 4);
					chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
					chr3 = ((enc3 & 3) << 6) | enc4;
					output = output + String.fromCharCode(chr1);
					if (enc3 != 64) {
						output = output + String.fromCharCode(chr2);
					}
					if (enc4 != 64) {
						output = output + String.fromCharCode(chr3);
					}
				}
				output = uTF8Decode(output);
				return output;
			}
		});
	})(jQuery);
	
	/*
	var initAddThis = function(e) {
	    var url = 'http://s7.addthis.com/js/250/addthis_widget.js#username=polaris2209';
	    $.getScript(url);
	    $('.addthis_button').unbind('mouseenter',initAddThis);
	    return true;		
	};
	*/
	//$('.addthis_button').bind('mouseenter',initAddThis);
	
	 function collectRoverData() {
	        var roverData = {},
	        $metaData = $("meta[name^='track']");
	        $metaData.each(function() {
	            roverData[$(this).attr('name').substr(6)]=$(this).attr('content');
	        });
	        return roverData;
	    }
	 var roverLoaded = false;
	 $.fn.roverTracker = function(pageId) {
		 var roverData = collectRoverData();
    	 var pageImpEvent;
		 var callRover = function() {
			 roverLoaded = true;
        	 _rover.setAppId(3060);
        	 var impEvt=_rover.createPageImpEvent(pageImpEvent);
             impEvt.setLVTrk(true);
             for(var name in roverData) {
            	 if (name == 'source') {
            	 } else {
            		 impEvt.getTrackData().addNvp(name,roverData[name]);
            	 }
             }
             ebayLVTr.setPageImpEvent(pageImpEvent);
             _rover.track();
		 };
		 if (!pageId) {
		     $metaData = $("meta[name^='rover.pageId']").each(function() {
		    	 pageId = parseInt($(this).attr('content'));
		     });
		 }
         if (pageId && (location.protocol == "http:")) {                
        	 pageImpEvent = [pageId];
        	 if (roverLoaded) {
        		 callRover();
        	 } else {
        		 jQuery.ajax({
        				type: "GET",
        				url: "http://include.ebaystatic.com/js/v/us/roverlv.js",
        				data: null,
        				cache : true,
        				success: callRover,
        				dataType: "script"
        			});        	 
        	 }
         }
	 }
})(jQuery);

$(document).ready(function() {
	$('input:text, textarea').inputFields();
	$(document).roverTracker();
});
var showLocationFilter = false;
var bedroomList = [
	{ id : '', value : 'Studio+'},
	//{ id : 'STUDIO', value : 'Studio+'},
	{ id : 'ONE', value :'1+ BR'},
	{ id : 'TWO' , value : '2+ BR' },
	{ id : 'THREE', value : '3+ BR'},
	{ id : 'FOUR', value : '4+ BR' },
	{ id : 'FIVE', value : '5+ BR' },
	{ id : 'MORE_THAN_SIX' , value : '6+ BR'}
];
var bedroomMenuOption = {
        name: 'Bedroom',
        container : '#ui-search-bedrooms', 
        list : bedroomList
     };
var bathroomList = [
    { id : '', value : '1+ BA'},
	//{ id : 'ONE', value : '1+ BA'},
	{ id : 'TWO', value : '2+ BA'},
	{ id : 'THREE', value : '3+ BA'},
	{ id : 'FOUR', value : '4+ BA'},
	{ id : 'FIVE', value : '5+ BA'}
];
var bathroomMenuOption = {
		name: 'Bathroom',
        container : '#ui-search-bathrooms', 
	    list : bathroomList
	};
var petOfferedByList = [
    { id : 'Shelter', value : 'Shelter'},
    { id : 'Owner', value : 'Owner'},
    { id : 'Breeder', value : 'Breeder'}
    ];
var petOfferedByMenuOption = {
		name: 'PetOfferedBy',
        container : '#ui-search-petOfferedBy', 
	    list : petOfferedByList
	};
var petGenderList = [
	{ id : '', value : 'Any Gender'},
    { id : 'Female', value : 'Female'},
    { id : 'Male', value : 'Male'}
    ];
var petGenderMenuOption = {
		name: 'PetGender',
        container : '#ui-search-petgender', 
	    list : petGenderList
	};
var carSellerList = [
	{ id : '', value : 'Any Seller'},
	{ id : 'Owner', value : 'By Owner'},
    { id : 'Dealer', value : 'By Dealer'}
    ];
var carSellerMenuOption = {
		name: 'CarSeller',
        container : '#ui-search-carseller', 
	    list : carSellerList
	};
polaris.show_CARS = function (minYear,maxYear,minMileage,maxMileage,soldBy) {
	var soldByName=carSellerMenuOption.container.substring(1);
	minYear = minYear == null ? '' : minYear;
	maxYear = maxYear == null ?  '' : maxYear;
	minMileage = minMileage == null ? '' : minMileage;
	maxMileage = maxMileage == null ? '' : maxMileage;
	$('#search-filters .attributes').remove();
	var str = '<div class="ui-search-filter attributes">' + 
		'<label>Year</label><input id="minYear" name="cars.minYear" class="search-filter-shorttext" title="min" type="text" value="' + minYear + '"/><input id="maxYear" name="cars.maxYear" class="search-filter-shorttext" title="max" type="text" value="' + maxYear + '"/>' +
		'</div><div class="ui-search-filter attributes">' +
		'<label>Mileage</label><input id="minMileage" name="cars.minMileage" class="search-filter-shorttext" title="min" type="text" value="' + minMileage + '"/><input id="maxMileage" name="cars.maxMileage" class="search-filter-shorttext" title="max" type="text" value="' + maxMileage + '"/>' +
		'</div>' + 
		'<div id="' + soldByName  + '" class="ui-search-filter attributes">' +
		'<a style="width:100px;" tabindex="0" class="ui-selectmenu xsp" href="#"></a>' +
		'<input type="hidden" name="cars.forSaleBy" value=""/>' +
		'</div>'; 
		$('#attributes2').html(str).show();
    $('#ui-search-carseller a').popupMenu(carSellerMenuOption,soldBy);
	$('.attributes input:text').inputFields();
}
polaris.show_CARSMETA =	function (minYear,maxYear,minMileage,maxMileage,soldBy) {
	polaris.show_CARS(minYear,maxYear,minMileage,maxMileage,soldBy);
}
function show_PETS_searchFilters(offered,genderOverride,cat) {
	var pathPrefix = cat.toLowerCase();
    var gender = genderOverride ?
    		genderOverride :
    		$("input[name=pets.gender]")[0] ?
    			$("input[name=pets.gender]")[0].value :
    			$("input[name=petsmeta.gender]")[0] ?
    				$("input[name=petsmeta.gender]")[0].value :
    				"";
	var offeredName=petOfferedByMenuOption.container.substring(1);
	var genderName=petGenderMenuOption.container.substring(1);
	var po = {};
	if ($('#petOfferedBy').dropdownchecklist) {
		$('#petOfferedBy').dropdownchecklist("getSelected", po);
		$('#petOfferedBy').dropdownchecklist("destroy");
	}
	$('#search-filters .attributes').remove();
	var ddcl = '<div id="' +
		offeredName +
		'" class="ui-search-filter attributes"><div class="from">From</div><select id="petOfferedBy" multiple="true" name="' +
		pathPrefix +
		'.offeredBy">';
	if (po.Shelter) {
		ddcl += '<option value="Shelter" selected="selected">Shelter</option>';
	}
	else {
		ddcl += '<option value="Shelter">Shelter</option>';
	}
	if (po.Owner) {
		ddcl += '<option value="Owner" selected="selected">Owner</option>';
	}
	else {
		ddcl += '<option value="Owner">Owner</option>';
	}
	if (po.Breeder) {
		ddcl += '<option value="Breeder" selected="selected">Breeder</option>';
	}
	else {
		ddcl += '<option value="Breeder">Breeder</option>';
	}
	ddcl += '</select></div>';
	var str = ddcl + '<div id="' + genderName  + '" class="ui-search-filter attributes">' +
    '<a style="width:100px;" tabindex="0" class="ui-selectmenu xsp" href="#"></a>' +
    '<input type="hidden" name="' +
    pathPrefix + '.gender" value="'+gender+'"/>' +
    '</div>'; 
	if (showLocationFilter)
		$('#attributes2').html(str).show();
	else
		$('#attributes1').after(str);

	$('#petOfferedBy').dropdownchecklist({width:150,emptyText:"Anyone"});
    $('#ui-search-petgender a').popupMenu(petGenderMenuOption,gender);
	$('.attributes input:text').inputFields();
}
polaris.show_PETS = function (offered,gender) {
	show_PETS_searchFilters(offered,gender,"PETS");
}
polaris.show_PETSMETA =	function show_PETSMETA(offered,gender) {
	show_PETS_searchFilters(offered,gender,"PETSMETA");
}

polaris.show_JOBS = function() {}
polaris.show_RENTAL = function (bedrooms,bathrooms,petsAllowed) {
	petsAllowed = petsAllowed ? 'checked' : '';
	$('#search-filters .attributes').remove();
	var str = '<label class="la-re" for="ui-search-bedrooms">Beds </label><span id="ui-search-bedrooms" class="ui-search-filter attributes">' +
    '<a style="width:50px;" tabindex="0" class="ui-selectmenu xsp" href="#"></a>' +
    '<input type="hidden" name="rental.noOfBedrooms" value=""/>' +
    '</span>' + 
	'<label class="la-re" for="ui-search-bedrooms">Baths </label><span id="ui-search-bathrooms" class="ui-search-filter attributes">' +
    '<a style="width:50px;" tabindex="0" class="ui-selectmenu xsp" href="#"></a>' +
    '<input type="hidden" name="rental.noOfBathrooms" value=""/>' +
    '</span>' + 
    '<span class="la-chbox">' + 
    '<input class="petsOK" id="petsAllowed" name="rental.petsAllowed" type="checkbox" value="true" ' + petsAllowed + '/><input type="hidden" name="_petsAllowed" value="on"/><label class="petsOK" for="rental.petsAllowed">Pets OK</label>' +               
    '</span>';
		$('#attributes2').html(str).show();
	$('#ui-search-bedrooms a').popupMenu(bedroomMenuOption,bedrooms);
    $('#ui-search-bathrooms a').popupMenu(bathroomMenuOption,bathrooms);
	$('.attributes input:text').inputFields();
}
polaris.show_COMMERCIAL = function (minSize,maxSize) {
	minSize = minSize == null ? '' : minSize;
	maxSize = maxSize == null ?  '' : maxSize;
	$('#search-filters .attributes').remove();
	var str = '<div class="ui-search-filter attributes">' + 
		'<label>Size (sq ft)</label><input id="minSize" name="commercial.minSize" class="search-filter-shorttext" title="Min" type="text" value="' + minSize + '"/><input id="maxSize" name="commercial.maxSize" class="search-filter-shorttext" title="Max" type="text" value="' + maxSize + '"/>' +
		'</div>';
	if (showLocationFilter)
		$('#attributes2').html(str).show();
	else
		$('#attributes1').after(str);
	$('.attributes input:text').inputFields();
}
polaris.show_HOUSE = function(bedrooms,bathrooms) {
	$('#search-filters .attributes').remove();
	var str = '<label class="la-re" for="ui-search-bedrooms">Beds </label><span id="ui-search-bedrooms" class="ui-search-filter attributes">' +
    '<a style="width:50px;" tabindex="0" class="ui-selectmenu xsp" href="#"></a>' +
    '<input type="hidden" name="house.noOfBedrooms" value=""/>' +
    '</span>' + 
	'<label class="la-re" for="ui-search-bedrooms">Baths </label><span id="ui-search-bathrooms" class="ui-search-filter attributes">' +
    '<a style="width:50px" tabindex="0" class="ui-selectmenu xsp" href="#"></a>' +
    '<input type="hidden" name="house.noOfBathrooms" value=""/>' +
    '</span>'
	if (showLocationFilter)
		$('#attributes2').html(str).show();
	else
		$('#attributes1').after(str);
    $('#ui-search-bedrooms a').popupMenu(bedroomMenuOption,bedrooms);
    $('#ui-search-bathrooms a').popupMenu(bathroomMenuOption,bathrooms);
	$('.attributes input:text').inputFields();
}
polaris.show_HOUSINGMETA = function(bedrooms,bathrooms) {
	polaris.show_HOUSE(bedrooms,bathrooms);
}

function show_PRICE() {
	if ($('#price').length == 0) {
		var str = '<div class="ui-search-filter" id="price">' +
		'<label for="search-filter-min">Price </label><input id="minPrice" name="minPrice" class="search-filter-shorttext" title="min" type="text" value=""/><input id="maxPrice" name="maxPrice" class="search-filter-shorttext" title="max" type="text" value=""/></div>';
		$(str).insertBefore('#search-filters div:first');
		$('#price input:text').inputFields();
	}
}
/*
 * Distance Search
 */
polaris.initDistanceSearch = function(p) {

	var radiusMenuOption = {
		name: 'Radius',
		container : '#ui-search-radius', 
		setSelected : function(val,display) {
			display = display.replace(/&nbsp;/g,'');
			$(this.container + ' input').val(val);
			$(this.container + ' .ui-selectmenu').html(display);
		},
		createDropDown : function () {
			var str = '<ul id="' + this.name + 'Dropdown" class="ui-selectmenu-menu" >';
			for(var i = 0; i < this.list.length; i++ ){
				str += "<li class='itemid" + this.list[i].id + "'><a href='#'>" + this.list[i].value + "</a></li>";
			}
			str += '</ul>';
			return str;
		},
		list : p.radiusMenuList
	};
	var radiusMenu = $('#ui-search-radius a').popupMenu(radiusMenuOption, p.selectedRadius);
	
	var distanceAddress = p.form.find("#distanceAddress");
	var lat = p.form.find("#lat");
	var lng = p.form.find("#lng");
	var locId = p.form.find("#locId");
	var radius = p.form.find("#radius");
	var lastPlacemark;
	var prompt = p.prompt;
	
	function distanceAddressHasContent() {
		if (distanceAddress.val().length > 0) {
			if (distanceAddress.val() != prompt) {
				return true;
			}
		}
		return false;
	}

	function keyUpInAddress(evt) {
		enableControls();
	}

	var toggleFormSubmit = p.toggleFormSubmit;
	var disableSubmitButton = p.disableSubmitButton;
	var enableSubmitButton = p.enableSubmitButton;

	function locationBlur() {
			if (distanceAddressHasContent()) {
				if (polaris.isBingEnabled) {
					bingGeocode();
				} else {
					gGeocode(disableSubmitButton, enableSubmitButton);
				}
			}
			else {
				distanceAddress.val(prompt);
			}
			enableControls();
		}

	function locationFocus() {
		if (distanceAddress.val() == prompt) {
			distanceAddress.val("");
		}
	}

	function enableControls() {
		if (distanceAddressHasContent()) {
			polaris.locationMenu.disable();
			radiusMenu.enable();
		}
		else {
			polaris.locationMenu.enable();
			radiusMenu.disable();
            lat.val(0);
            lng.val(0);
            radius.val("MILES");
		}
	}
	
	function setDistanceSearchParams(addr, ilat, ilng, ilocId) {
		distanceAddress.val(addr);
		lat.val(ilat);
		lng.val(ilng);
		locId.val(ilocId);
	}

	//var geocoder = new google.maps.ClientGeocoder();

	function parseAddress(pm) {
		if (pm.address.indexOf(", United States") > -1) {
			return pm.address.substr(0, pm.address.indexOf(", United States"));
		}
		if (pm.address.indexOf(", USA") > -1) {
			return pm.address.substr(0, pm.address.indexOf(", USA"));
		}
		return null;
	}

	function gGeocodeImpl(prefunc, postfunc, inaddr) {
		var geocoder = new google.maps.ClientGeocoder();
		var addr = inaddr||distanceAddress.val();
		// Accept US area: 17..73, -161..-66
		var re = /^\s*((1[7-9]|[2-6][0-9]|7[0-3])(\.(\d+)?)?)\s*,\s*(-(6[6-9]|[7-9][0-9]|1[0-5][0-9]|16[01])(\.(\d+)?)?)/;
		var m = re.exec(addr);
		if (m != null) {
			// Already have a US lat/lng. Just use it.
			var tlat = parseFloat(m[1]).toString();
			var tlng = parseFloat(m[5]).toString();
			setDistanceSearchParams(tlat + ", " + tlng, tlat, tlng, "")
			return;
		}
		if (prefunc) {
			prefunc();
		}
		if (postfunc) {
			this.geocodeTimeout = setTimeout(postfunc, 5000);
		}
		addr += " USA";
		geocoder.getLocations(addr,
			function(response) {
				if (postfunc) {
					clearTimeout(this.geocodeTimeout);
				}
				var sAddress, sLat, sLng;
				if (!response || !response.Status || !response.Status.code || 
						response.Status.code !== 200 || !response.Placemark || 
						response.Placemark.length === 0 ) {
					if (polaris.areaName == addr) {
						// second failure
						setDistanceSearchParams(polaris.areaName, 0, 0, "")
						if (postfunc) {
							postfunc();
						}
					}
					else {
						// first failure
						gGeocode(prefunc, postfunc, polaris.areaName); 
					}
				}
				else {
					lastPlacemark = response.Placemark[0];
					if (lastPlacemark != null && parseAddress(lastPlacemark) != null) {
						setDistanceSearchParams(parseAddress(lastPlacemark),
							escape(lastPlacemark.Point.coordinates[1]),
							escape(lastPlacemark.Point.coordinates[0]), "")
						if (postfunc) {
							postfunc();
						}
					}
					else {
						// an address was returned outside the US
						gGeocode(prefunc, postfunc, polaris.areaName); 
					}
				}
			}
		);
	}
	
	function bingGeocode(search) {
	    var result,
	    bingUrl = "http://dev.virtualearth.net/REST/v1/Locations";
	    search = (search === undefined)? distanceAddress.val() : search;
	    $.ajax({
	        url: bingUrl,
	        dataType: "jsonp",
	        data: {
	            key: polaris.bingMapsKey,
	            query: search,
	            culture: "en-US",
	            output: "json"
	        },
	        jsonp: "jsonp",
	        success: function (data) {
	            var addr;
	            result = data.resourceSets[0];
	            if (result) {
	                if (result.estimatedTotal > 0) {
	                    var usItems = [];
	                    for (var i = 0; i < result.resources.length; i++) {
	                        var place = result.resources[i];
	                        if ((place.address && place.address.countryRegion === 'United States')) {
	                            usItems.push(place);
	                        }
	                    }
	                    if (usItems.length > 0) {
	                        if (/^\d{5}$/.test(search) && usItems[0].address.postalCode !== undefined &&
	                            usItems[0].address.locality !== undefined) { // zip code
	                            addr = usItems[0].address.locality + ", " + usItems[0].address.adminDistrict + " " + usItems[0].address.postalCode;
	                        } else {
	                            addr = usItems[0].address.formattedAddress;
	                        }
	                        setDistanceSearchParams(addr, usItems[0].point.coordinates[0], usItems[0].point.coordinates[1], "");
	                    }	
	                }	   
	            }
	        },
	        complete: function () { 
	            // if bing returns 0 result or return error, call again with area name because it is the default search
	            if (result === undefined || result.estimatedTotal === 0) {
	                if (polaris.areaName === 'San Francisco Bay Area') {
	                    bingGeocode('San Francisco');   
	                } else {
	                    bingGeocode(polaris.areaName);
	                }
	            }   
	        }
	    });
	}

	function gGeocode(prefunc, postfunc, inaddr) {
		if (polaris.geoCoder === null) {
			polaris.googleMapKeyInfo[2]["callback"] = function (){polaris.geoCoder = new google.maps.ClientGeocoder();gGeocodeImpl(prefunc, postfunc, inaddr);};
				google.load(polaris.googleMapKeyInfo[0],polaris.googleMapKeyInfo[1], polaris.googleMapKeyInfo[2]);
			} else {
				gGeocodeImpl(prefunc, postfunc, inaddr);
        }
	}
	
	distanceAddress.bind("keyup", keyUpInAddress);
	distanceAddress.bind("focus", locationFocus);
	distanceAddress.bind("blur", locationBlur);
	enableControls();

	return {
			form: p.form,
			setDistanceAddress: function(da) {
				distanceAddress.val(da);
			},
			geocoded: function(pre, post) {
				var need = (lastPlacemark === undefined) ? true :
						(parseAddress(lastPlacemark) == distanceAddress.val()) ? false : true;
				if (distanceAddressHasContent() && need) {
					gGeocode(pre, post);
					return false;
				}
				else {
					return true;
				}
			}
	};
}


polaris.showShareAdForm = function(opt) {

	polaris.showModal(null,this);
}


polaris.initAlertSubscription = function(opt) {
	var widget = $("#"+opt.widget);
	var container = $("#"+opt.container);
	var contentContainer = $("#"+opt.contentContainer);
	var formOpenLink = $("."+opt.formOpenLink);
	var alertSubscriptionSubmit = $("#"+opt.alertSubscriptionSubmit);
	var closeSubscriptionFormXLink = $("#"+opt.closeSubscriptionFormXLink);
	var alertSubscriptionPrompt = $("."+opt.alertSubscriptionPrompt);
	var initialPrompt = alertSubscriptionPrompt.html();
	var alertSubscriptionHeaderText = $("#subscriptionFormHeaderText");
	var fetchUserDataURL = opt.fetchUserDataURL;
	var open = opt.open;
	var smsIsEnabled = opt.smsIsEnabled;
	var isUserAlert = opt.userAlert? opt.userAlert: false; 
	var email = null;
	var sms = null;
	var smsCheckbox = null;
	var disabledInputClass = "disabled-input";
	var lastFocus = null;
	var useSMS = $("#useSMS");
	var useEmail = $("#useEmail");
	var inputsBound = false;
	var userStatusRetrieved = false;

	var emailreg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var smsreg = /^(?:\+?1[-. ]?)?\(?([2-9][0-9]{2})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
	email = $("#subscriberEmailAddress");
	sms = $("#subscriberSMSNumber");
	
	var emailSuccessMsg = [
		"<p>We'll be sending email alerts for your subscription to <span id='successEmailAddress'>",
		"",
		"</span></p><p>(make sure to check your spam or junk folder)</p>"
		];
	var smsSuccessMsg = [
	       "<p>We'll be sending text message alerts for your subscription to <span id='successSmsNumber'>",
	       "",
	       "</span></p>"
        ];
	

	function initUserStatus(sFunc, scope) {

		polaris.setUserDataCallback(
			function(response) {
				polaris.setUserPhoneNumber(response.cellNumber);
				polaris.setUserPhoneNumberIsVerified(response.cellNumberVerified);
				sms.val(window.polaris.getUserPhoneNumber());
				email.val(window.polaris.getUserEmail());
				userStatusRetrieved = true;
				sFunc.apply(scope);
			},
			this
		);
        $.ajax({
            type: "GET",
            url: fetchUserDataURL,
            dataType: "jsonp"
        });
		
	}

	function enter(e) {
		if (e.which == 13) {
			e.preventDefault();
			$(this).blur();
			alertSubscriptionSubmit.click();
			return false;
		}
	}
	
	function bindInputs() {
		if (!inputsBound) {
			bindSms();
			bindUseEmailCheckbox();
			bindUseSMSCheckbox();
			bindSubmitButton();
			inputsBound = true;
		}
	}

	function initInputs() {

        email.val(window.polaris.getUserEmail());

	    var pn = window.polaris.getUserPhoneNumber();
	    if (pn !== null && pn.length > 0) {
	    	sms.val(pn);
	    	if (window.polaris.getUserPhoneNumberIsVerified()) {
	    		sms.attr("readonly", true);
	    		sms.parent().addClass("locked");
	    	}
	    	else {
	    		sms.focus();
	    	}
	    }
	    else {
	    	sms.val("");
    		sms.focus();
	    }

		validateSms();
		bindInputs();
	    
	}
	
	function submitByAjax() {
	    alertSubscriptionSubmit.unbind("click");
	    alertSubscriptionSubmit.unbind("mouseenter mouseleave");
		$('#alert-subscription-form .formbusy').show();

		$.post(opt.alertSubscriptionUrl, $('#alertSubscriptionForm').serialize(), createSubscriptionResponse, "json");
		return false;

	}

	function createSubscriptionResponse(resp) {
		if (polaris.alertSubscription.originalForm === undefined || polaris.alertSubscription.originalForm === null) {
			polaris.alertSubscription.originalForm = contentContainer.html(); 
		}
		polaris.alertSubscription.subscribed = resp.success;
		var st = 0;
		st = st + (resp.triedEmail ? 1 : 0);
		st = st + (resp.successEmail ? 2 : 0);
		st = st + (resp.triedSMS ? 4 : 0);
		st = st + (resp.successSMS ? 8 : 0);
		switch(st) {
			case 0: // should never happen
				showError(resp, "email");
				showError(resp, "sms");
				break;
			case 1: // should never happen;indicates a back-end error;show any email error message
				showError(resp, "email");
				break;
			case 2: // can't happen
				showError(resp, "email");
				break;
			case 3: // hide inputs and subscribe button, show email success
				setEmailSuccessMessage();
				removeInput("email", true);
				removeInput("sms", true);
				hideSubscribe(true);
				setPrompt(true);
				break;
			case 4: // show sms error message
				showError(resp, "sms");
				break;
			case 5: // should never happen;indicates a back-end error;show any error messages;
				showError(resp, "email");
				showError(resp, "sms");
				break;
			case 6: // should never happen
				showError(resp, "email");
				showError(resp, "sms");
				break;
			case 7: // show email success message;
			        // show sms error message
				setEmailSuccessMessage();
				removeInput("email", true);
				showError(resp, "sms");
				setPrompt(true);
				break;
			case 8: // should never happen
				showError(resp, "sms");
				break;
			case 9: // should never happen;indicates a back-end error;show any email error messages;
				showError(resp, "email");
				showError(resp, "sms");
				break;
			case 10: // should never happen
				showError(resp, "email");
				showError(resp, "sms");
				break;
			case 11: // should never happen
				     // hide inputs and subscribe button, show email success
				setEmailSuccessMessage();
				removeInput("email", true);
				showError(resp, "sms");
				hideSubscribe(true);
				setPrompt(true);
				break;
			case 12: // hide inputs and subscribe button, show sms success
				setSMSSuccessMessage();
				removeInput("email", true);
				removeInput("sms", true);
				hideSubscribe(true);
				setPrompt(true);
				break;
			case 13: // should never happen;indicates a back-end error;show any error message for email
			         // show sms success;hide inputs and subscribe button
				setSMSSuccessMessage();
				removeInput("sms", true);
				showError(resp, "email");
				setPrompt(true);
				break;
			case 14: // should never happen;indicates a back-end error;show any error message for email
	                 // show sms success;hide inputs and subscribe button
				setSMSSuccessMessage();
				removeInput("email", true);
				removeInput("sms", true);
				hideSubscribe(true);
				setPrompt(true);
				break;
			case 15: // hide inputs and subscribe button, show email and sms success
				setEmailSuccessMessage();
				setSMSSuccessMessage();
				removeInput("email", true);
				removeInput("sms", true);
				hideSubscribe(true);
				setPrompt(true);
				break;
		}
	}

	function hideSubscribe(inv) {
		if (inv) {
			$(".form-section-container.subscribe").addClass("invisible");
		}
		else {
			$(".form-section-container.subscribe").removeClass("invisible");
		}
	}
	function removeInput(inp) {
		$(".form-section-container."+inp).remove();
	}
	function setSMSSuccessMessage() {
		smsSuccessMsg[1] = sms.val();
		$(".smsSubscriptionSuccess").html(smsSuccessMsg.join(""));
		$(".smsSubscriptionSuccess").removeClass("hide");
		$(".smsSubscriptionSuccess").removeClass("invisible");
	}
	function setEmailSuccessMessage() {
		emailSuccessMsg[1] = email.val();
		$(".emailSubscriptionSuccess").html(emailSuccessMsg.join(""));
		$(".emailSubscriptionSuccess").removeClass("hide");
		$(".emailSubscriptionSuccess").removeClass("invisible");
	}
	function showError(resp, inp) {
		if (resp.errors && resp.errors[inp]) {
			$("."+inp+" .invalid-input-msg").html(polaris.alertSubscription.errorMessages[resp.errors[inp]]);
			$("."+inp+" .invalid-input-msg").removeClass("hide");
		}
	}

	function repaintAlertSubscriptionForm(data) {
		if (polaris.alertSubscription.originalForm === undefined || polaris.alertSubscription.originalForm === null) {
			polaris.alertSubscription.originalForm = contentContainer.html(); 
		}
		contentContainer.html(data);
		if ($(".emailSubscriptionSuccess").length || $(".smsSubscriptionSuccess").length) {
			polaris.alertSubscription.subscribed = true;
		}
		setPrompt(true);
	}

	function isDisabled(n) {
		return n.hasClass(disabledInputClass);
	}
	
	function markValidity(i1, valid) {
		if (valid) {
			i1.removeClass("invalid-input");
			$(".invalid-input-msg", i1.parent()).addClass("hide");
		}
		else {
			if (!isDisabled(i1)) {
				i1.addClass("invalid-input");
				$(".invalid-input-msg", i1.parent()).removeClass("hide");
			}
		}
	}
	
	function smsValidator() {
		var valid = smsreg.test(sms.val());
		if (valid) {
			var v = sms.val();
			var vf = v.replace(smsreg, "($1) $2-$3");
			if (v != vf) {
				sms.val(v.replace(smsreg, "($1) $2-$3"));
			}
		}
		markValidity(sms, valid);
		return valid;
	}

	function validateSms() {
		sms.parent().removeClass("validated");
		$(".sms .invalid-input-msg").html(polaris.alertSubscription.errorMessages.SMS_NUMBER_NOT_VALID);
		if (sms.val().length && smsValidator() && !isDisabled(sms)) {
			sms.parent().addClass("validated");
		}
		bindSubmitButton();
	}

	function bindUseSMSCheckbox() {
	    useSMS.attr("checked", false);
	    sms.addClass(disabledInputClass);
        sms.attr("readonly", true);
	    useSMS.bind($.browser.msie ? 'propertychange': 'change', function(e) {
			if (e.type == "change" || (e.type == "propertychange" && window.event.propertyName == "checked")) {
		    	if (useSMS.attr("checked")) {
		    		sms.removeClass(disabledInputClass);
			    	if (!window.polaris.getUserPhoneNumberIsVerified()) {
			    		sms.attr("readonly", false);
			    		sms.focus();
			    	}
		    	}
		    	else {
					$(".invalid-input-msg", sms.parent()).addClass("hide");
		    		sms.addClass(disabledInputClass);
		            sms.attr("readonly", true);
		    	}
				bindSubmitButton();
			}
		});
	}

	function bindUseEmailCheckbox() {
	    useEmail.attr("checked", true);
	    email.removeClass(disabledInputClass);
	    useEmail.bind($.browser.msie ? 'propertychange': 'change', function(e) {
			if (e.type == "change" || (e.type == "propertychange" && window.event.propertyName == "checked")) {
		    	if (useEmail.attr("checked")) {
		    		email.removeClass(disabledInputClass);
		    	}
		    	else {
					$(".invalid-input-msg", email.parent()).addClass("hide");
		    		email.addClass(disabledInputClass);
		    	}
				bindSubmitButton();
			}
		});
	}

	function bindSms() {
	    sms.keypress(enter);
		sms.keyup(validateSms);
		sms.click(validateSms);
		sms.keydown(function(e){
			var w = e.which;
			var s = e.shiftKey; 
			if (s) {
				if ((w == 9) ||					// back tab
					(w == 36) ||				// shift home
					(w == 35) ||				// shift end
					(w == 57) ||				// left paren
					(w == 48)) {				// right paren
					return true;
				}
			}
			else {
				if ((48 <= w)&&(w <=57)) {		// keyboard numbers
					return true;
				}
				if ((96 <= w)&&(w <=105)) {		// keypad numbers
					return true;
				}
				if ((w == 32)  ||						// space
					(w == 110) ||						// keypad period
					(w == 190) ||						// keyboard period
					(w == 109) ||						// minus
					($.browser.msie && w == 189) ||		// minus 
					(w == 13)  ||						// enter
					(w == 8)   ||						// backspace
					(w == 46)  ||						// delete
					(w == 37)  ||						// left arrow
					(w == 39)  ||						// right arrow
					(w == 9)   ||						// tab			
					(w == 36)  ||						// home
					(w == 35)  )  {						// end
					return true;
				}
			}
			e.preventDefault();
			return false;
		});
	    sms.bind("focus", setLastFocus);
	}

	function unbindToggleLink() {
		formOpenLink = $("."+opt.formOpenLink);
		if (formOpenLink) {
			formOpenLink.unbind("click");
		}
	}
	
	function bindToggleLink() {
		formOpenLink = $("."+opt.formOpenLink);
		if (formOpenLink) {
			formOpenLink.bind("click", toggleAlertWidget);
		}
	}
	
	function unbindCloseLink() {
		closeSubscriptionFormXLink = $("#"+opt.closeSubscriptionFormXLink);
		if (closeSubscriptionFormXLink) {
			closeSubscriptionFormXLink.unbind("click");
		}
	}

	function bindCloseLink() {
		closeSubscriptionFormXLink = $("#"+opt.closeSubscriptionFormXLink);
		if (closeSubscriptionFormXLink) {
			closeSubscriptionFormXLink.bind("click",hideAlertWidget);
		}
	}
	
	function hideAlertWidget() {
		widget.slideUp("slow", setPrompt);
	}
	
	function toggleAlertWidget() {
		unbindCloseLink();
		if (polaris.isLoggedIn()) {
			if (open) {
				widget.appendTo(formOpenLink.parent().parent());
			}
			else {
				widget.appendTo($(this).parent().parent());
			}
			if ($.browser.msie) {
				widget.css("display","block");
				setPrompt();
			}
			else {
				widget.slideDown("slow", setPrompt);
			}
			if (lastFocus) {
				$(lastFocus).focus().keyup();
			}
			else {
				email.focus().keyup();
			}
			if (!userStatusRetrieved) {
				initUserStatus(initInputs, this);
			}
		}
		else {
			polaris.showModal(toggleAlertWidget,this);
		}
		bindCloseLink();
	}
	
	function disableSubmitButton() {
		alertSubscriptionSubmit.unbind("click");
		alertSubscriptionSubmit.unbind("mouseenter mouseleave");
		alertSubscriptionSubmit.addClass("disabled");
	}
	function enableSubmitButton() {
		disableSubmitButton();
    	alertSubscriptionSubmit.removeClass("disabled");
    	alertSubscriptionSubmit.hover(
    			function(e){
    				alertSubscriptionSubmit.addClass("hand-pointer");
    			},
    			function(e){
    				alertSubscriptionSubmit.removeClass("hand-pointer");
    			}
    	);
	}

	function enableAjaxSubmit() {
		enableSubmitButton();
	    alertSubscriptionSubmit.bind("click", submitByAjax);
	}

	function promptForSmsTerms() {
		smsAgreementPrompt.removeClass("hide");
	}

	function bindSubmitButton() {
	    alertSubscriptionSubmit.unbind("click");

	    var enable = ((useEmail.attr("checked"))												?  1 : 0)
	       + ((useSMS.attr("checked"))					                                        ?  2 : 0)
	       + ((sms.parent().hasClass("validated"))					                            ?  4 : 0)
	       + ((window.polaris.getUserPhoneNumberIsVerified())                                	?  8 : 0);

	    switch (enable) {
	    //case  0: //
	    case  1: // useEmail
	    	enableAjaxSubmit();
		    break;
	    //case  2: // useSMS
	    //case  3: // useEmail useSMS
	    //case  4: // smsValid
	    case  5: // useEmail smsValid
	    	enableAjaxSubmit();
		    break;
	    case  6: // useSMS smsValid
	    	enableAjaxSubmit();
	    	break;
	    case  7: // useEmail useSMS smsValid
	    	enableAjaxSubmit();
	    	break;
	    //case  8: // smsVerified
	    case 9:  // useEmail smsVerified
	    	enableAjaxSubmit();
		    break;
	    case 10:  // useSMS smsVerified
	    	enableAjaxSubmit();
		    break;
	    case 11:  // useEmail smsVerified
	    	enableAjaxSubmit();
		    break;
	    //case 12: // smsValid smsVerified
	    case 13: // useEmail smsValid smsVerified
	    	enableAjaxSubmit();
		    break;
	    case 14: // useSMS smsValid smsVerified
	    	enableAjaxSubmit();
		    break;
	    case 15: // useEmail useSMS smsValid smsVerified
	    	enableAjaxSubmit();
		    break;
    	default:
    		disableSubmitButton();
	    }
		    
	}

	function setPrompt(showing) {
		unbindToggleLink();
		if (showing === undefined || showing === null) {
			showing = ($(widget).css("display") !== "none");
		}
		var pmt = "";
		var banner = "";
		var pndx = (showing ? 1 : 0)
		         + (window.polaris.isLoggedIn() ? 2 : 0)
		         + (polaris.alertSubscription.subscribed ? 4 : 0)
		         + (polaris.alertSubscription.pending ? 8 : 0)
		         + (open ? 16 : 0)
		         + (isUserAlert ? 29 : 0);
		
		switch (pndx) {
		case 0:			// not showing, not signed in, not subscribed, not pending, search has results
			pmt = "Be the first to get new results like these - <a class=\"subscribe-to-alert\">subscribe to alerts</a>";
			break;
		case 1:			// showing, not signed in, not subscribed, not pending, search has results
			pmt = "Subscribe to receive alerts when new ads match your search"
			break;
		case 2:			// not showing, signed in, not subscribed, not pending, search has results 
			pmt = "Be the first to get new results like these - <a class=\"subscribe-to-alert\">subscribe to alerts</a>";
			break;
		case 3:			// showing, signed in, not subscribed, not pending, search has results
			pmt = "Subscribe to receive alerts when new ads match your search";
			break;
		case 4:			// not showing, not signed in, subscribed, not pending, search has results
			pmt = "You have subscribed to an alert for this search. <a class=\"subscribe-to-alert\">See the details</a>";
			break;
		case 5:			// showing, not signed in, subscribed, not pending, search has results
			pmt = "Please confirm your alert subscription";
			break;
		case 6:			// not showing, signed in, subscribed, not pending, search has results
			pmt = "You have subscribed to an alert for this search. <a class=\"subscribe-to-alert\">See the details</a>";
			break;
		case 7:			// showing, signed in, subscribed, not pending, search has results
			pmt = "Thanks for subscribing";
			break;
		case 8:			// not showing, not signed in, not subscribed, pending, search has results
			pmt = "Your alert subscription has not been activated yet! <a class=\"subscribe-to-alert\">See important information!</a>";
			break;
		case 9:			// showing, not signed in, not subscribed, pending, search has results
			pmt = "Almost done, now activate your alert";
			break;
		case 10:		// not showing, signed in, not subscribed, pending, search has results
			pmt = "Your alert subscription has not been activated yet! <a class=\"subscribe-to-alert\">See important information!</a>";
			break;
		case 11:		// showing, signed in, not subscribed, pending, search has results
			pmt = "Almost done, now activate your alert";
			break;
		case 12:		// not showing, not signed in, subscribed, pending, search has results
			pmt = "not showing, not signed in, subscribed, pending, search has results";
			break;
		case 13:		// showing, not signed in, subscribed, pending, search has results
			pmt = "showing, not signed in, subscribed, pending, search has results";
			break;
		case 14:		// not showing, signed in, subscribed, pending, search has results
			pmt = "not showing, signed in, subscribed, pending, search has results";
			break;
		case 15:		// showing, signed in, subscribed, pending, search has results
			pmt = "showing, signed in, subscribed, pending, search has results";
			break;
		case 16:		// not showing, not signed in, not subscribed, not pending, no search result
			pmt = "Be the first to know <a class=\"subscribe-to-alert\">subscribe to alerts</a>";
			break;
		case 17:		// showing, not signed in, not subscribed, not pending, no search result
			pmt = "Subscribe to receive alerts when new ads match your search";
			break;
		case 18:		// not showing, signed in, not subscribed, not pending, no search result 
			pmt = "Be the first to know <a class=\"subscribe-to-alert\">subscribe to alerts</a>";
			break;
		case 19:		// showing, signed in, not subscribed, not pending, no search result
			pmt = "Subscribe to receive alerts when new ads match your search";
			break;
		case 20:		// not showing, not signed in, subscribed, not pending, no search result
			pmt = "You have subscribed to an alert for this search. <a class=\"subscribe-to-alert\">See the details</a>";
			break;
		case 21:		// showing, not signed in, subscribed, not pending, no search result
			pmt = "Thanks for subscribing";
			break;
		case 22:		// not showing, signed in, subscribed, not pending, no search result
			pmt = "You have subscribed to an alert for this search. <a class=\"subscribe-to-alert\">See the details</a>";
			break;
		case 23:		// showing, signed in, subscribed, not pending, no search result
			pmt = "You have subscribed to an alert for this search.";
			break;
		case 24:		// not showing, not signed in, not subscribed, pending, no search result
			pmt = "Your alert subscription has not been created yet! <a class=\"subscribe-to-alert\">See important information!</a>";
			break;
		case 25:		// showing, not signed in, not subscribed, pending, no search result
			pmt = "Your alert subscription has not been created yet!";
			break;
		case 26:		// not showing, signed in, not subscribed, pending, no search result
			pmt = "Your alert subscription has not been created yet! <a class=\"subscribe-to-alert\">See important information!</a>";
			break;
		case 27:		// showing, signed in, not subscribed, pending, no search result
			pmt = "showing, signed in, not subscribed, pending, no search result";
			break;
		case 28:		// not showing, not signed in, subscribed, pending, no search result
			pmt = "not showing, not signed in, subscribed, pending, no search result";
			break;
		case 29:		// showing, not signed in, subscribed, pending, no search result
			pmt = "showing, not signed in, subscribed, pending, no search result";
			break;
		case 30:		// not showing, signed in, subscribed, pending, no search result
			pmt = "not showing, signed in, subscribed, pending, no search result";
			break;
		case 31:		// showing, signed in, subscribed, pending, no search result
			pmt = "Be the first to get new ads from this user - <a class=\"subscribe-to-alert\">subscribe to alerts</a>";
			break;
		case 32:		// showing, signed in, subscribed, pending, no search result
			pmt = "Subscribe to receive alerts when this user posts new ads";
			break;
		case 33:		// showing, signed in, subscribed, pending, no search result
			pmt = "case 33";
			break;
		case 34:		// showing, signed in, subscribed, pending, no search result
			pmt = "case 34";
			break;
		case 35:		// showing, signed in, subscribed, pending, no search result
			pmt = "You have subscribed to an alert from this user. <a class=\"subscribe-to-alert\">See the details</a>";
			break;
		case 36:		// showing, signed in, subscribed, pending, no search result
			pmt = "Thanks for subscribing";
			break;
		default:
		}
		
		alertSubscriptionPrompt.html(pmt);
		bindToggleLink();
		
	};
	
	function setLastFocus() {
		if (($(widget).css("display") !== "none")) {
			lastFocus = this;
		}
	}
	
	if (!polaris.alertSubscription) {
		polaris.alertSubscription = {
			subscribed: false,
			pending: false,
			errorMessages: {
				SMS_VELOCITY_CHECK: "You've changed your cell number too many times today. Try again later.",
				SMS_NUMBER_NOT_VALID: "You've entered an invalid number.",
				CELLNUMBER_TAKEN: "That number is already being used.",
				SMS_ERROR: "Something went wrong. We're checking in to it..."
			}
		};
	}

	bindSubmitButton();
    bindToggleLink();

    polaris.alertSubscription.tooltip = {
	    REALTIME:"As soon as the item is posted",
	    HOURLY: "Hourly summary of posted items",
	    DAILY: "Daily summary of posted items",
	    WEEKLY: "Weekly summary of posted items"
    };
    
    if (polaris.isLoggedIn()) {
    	if (open) {
    		toggleAlertWidget(formOpenLink);
    	}
    }
	alertSubscriptionSubmit.addClass("disabled");
}



polaris.initAutoComplete = function(autoCompletePath, location) {
	polaris.autoComplete = {};
	var locIdPattern = /\[(\d+):[\w\s-]+\]/;
	var	re_token = /\/\/.*\r|\/\*(?:.|\n|\r)*?\*\/|\w+\b|[+-]?\d+(([.]\d+)*([eE][+-]?\d+))?|["][^"]*["]|['][^']*[']|./g;
	var re_ident = /[a-zA-Z0-9_][a-zA-Z0-9_]*/;
	var areaId = location.match(locIdPattern)[1];
	
	function rebuildCategoryDropdown() {
		jQuery('#search-category a').unbind("click");
		jQuery("#"+polaris.catMenuOption.name+"Dropdown").remove();
		jQuery('#search-category a').popupMenu(polaris.catMenuOption,polaris.selectedCatId);
	}
	
	function reinitCategoryList() {
		var sl = null;
		for (var z=0;z<polaris.categoryList.length;z++) {
			if (polaris.categoryList[z].level > 1) {
				sl = z;
				break;
			}
		}
		if (z !== null) {
			polaris.categoryList.splice(z,1);
			rebuildCategoryDropdown();
			return true;
		}
		return false;
	}

	$("#keyword").autocomplete({
		source: function(request, response) {
			var locId = $("#ui-search-neighborhood input").val();
			var catId = $('#search-category input').val();
			var data = {
				q: request.term,
				limit: 8,
				locId: locId ? locId : areaId ? areaId : 0
			};
			if (catId != "") {
				data.catId = catId;
			}
			$.ajax({
				url: autoCompletePath,
				dataType: "json",
				data: data,
				success: function(data) {
					if (!data) {
						response({});
					}
					else {
						polaris.autoComplete.terms = data;
						$("ul.ui-autocomplete li.ui-menu-item a").each(
							function(ndx, a) {
								$(a).unbind("click");
							}
						);
						response($.map(data, function(item) {
							var h = []
							h.push("<span class='suggested_term'>"+item.term+"</span>");
							if (item.catName) {
								h.push("<span class='cat_extension'> in <span class='suggested_category_name'>"+item.catName+"</span>");
								h.push("<span class='suggested_category_id'>"+item.catId+"</span>");
								if (item.parentCatId) {
									h.push("<span class='suggested_category_parent_id'>"+item.parentCatId+"</span>");
								}
								h.push("</span>");
							}
							return {
								label: h.join(""),
								value: item.term,
								hasExtension: (typeof item.catName !== 'undefined'),
								catName: item.catName,
								catId: item.catId,
								parentCatId: item.parentCatId
							}
						}));
						var utxt = $("#keyword").val();
						$("ul.ui-autocomplete li.ui-menu-item a").each(
							function(ndx, a) {
								var utok = utxt.match(re_token);
								if (utok) {
									var n = "";
									for (var i = 0; i < utok.length; i++) {
										if (utok[i].match(re_ident)) {
											n = n + utok[i] + " ";
										}
									}
									n = n.substr(0,n.length-1);
									var t = $(".suggested_term", a)[0];
									var atxt = (t.innerText || t.textContent).substr(n.length);
									$(t).html(n+"<b>"+atxt+"</b>");
								}
							}
						);
					}
				}
			})
		},
		minlength: 2,
		delay: 400,
		select : function(event, ui) {
			if (ui.item.hasExtension) {
				polaris.selectedCatId = ui.item.catId;
				
				// ensure not in list already
				var onlist = false;
				for (var z=0;z<polaris.categoryList.length;z++) {
					if (polaris.categoryList[z].id == ui.item.catId) {
						onlist = true;
						break;
					}
				}
				if (!onlist) {
					for (var x=0;x<polaris.categoryList.length;x++) {
						var c = polaris.categoryList[x];
						if (c.level > 0 && c.id == ui.item.parentCatId) {
							polaris.categoryList.splice(x+1,0,{id: ui.item.catId,value: ui.item.catName,level: 2});
							rebuildCategoryDropdown();
							break;
						}
					}
				}
				
				jQuery(".itemid"+ui.item.catId).click();
			}
			if (event.keyCode == 13) {
				$("#search-wrapper form").submit();
			}
		}
	});
}

polaris.initShareAdForm = function(p) {

    polaris.initModal({
        modalId: "share-ad-form-modal",
        clear: function() {
            $("#share-ad-form-modal .wrapper .background .closex").unbind("click");
        },

        init: function() {
            $("#share-ad-form-modal .wrapper .background .closex").hover(
                function(){
                    $(this).addClass("hand-pointer");
                },
                function(e){
                    $(this).removeClass("hand-pointer");
                });

            $("#share-ad-form-modal .wrapper .background .closex").bind("click",
                function(e) {
                    //polaris.clearModal();
                    $("#share-ad-form-modal").hide();
                });
        },

        show: function() {
        },
        
        hide: function() {
        }
    });
}


polaris.initSignInModal = function(p) {
    var clearErrorMessage = function(e) {
    	$("#"+e.target.id+"errormsg").addClass("invisible");
	};
    var submitOnEnter = function(e) {
		if (e.keyCode == 13) {
			$("#btn-signin").click();
		}
	};
	polaris.initModal({
	    modalId: "login-or-register-modal",
	    clear: function() {
				$("#email").val("")
		        $("#password").val("");
	            $(document).unbind("keyup.polaris");
	            $("#login-or-register-modal .wrapper .background .closex").unbind("click");
	        },
	    init: function() {
	            
	            function submitSignInForm(evt) { 
	            	
	            	$.getJSON( p.signInAjaxURL + '?' + $("#signinajax").serialize() + '&signInAjaxType=regular' + '&jsoncallback=?', 
	            			function ( data ) { 
	                       if (data) {
	                           if (data.signInSuccessfull) {
	                               polaris.updateHeaderLinks();
	                               polaris.clearModal(true);
	                           }
	                           else {
	                               if (data.errorMessages) {
	                                   for (e in data.errorMessages) {
	                                       var m = $("#"+e+"errormsg");
	                                       m.html(data.errorMessages[e]);
	                                       m.removeClass("invisible");
	                                   }
	                               }
	                               $("#btn-signin").bind("click", submitSignInForm);
	                           }
	                       }
	                     } 
	            	);
	            }

	            function submitSignInFB() {
	                $.ajax({
	                   type: "POST",
	                   url: p.signInFBAjaxURL,
	                   data: "cmd=fbloginAjax",
	                   dataType: "json",
	                   success: function(data) {
	                       if (data) {
	                           if (data.success) {
	                               polaris.updateHeaderLinks();
	                               polaris.clearModal(true);
	                           }
	                           else {
	                               if (data.errorMessages) {
	                                   for (e in data.errorMessages) {
	                                       var m = $("#"+e+"errormsg");
	                                       m.html(data.errorMessages[e]);
	                                       m.removeClass("invisible");
	                                   }
	                               }
	                               $("#fb_login_img").bind("click", loginUsingFb);
	                           }
	                       }
	                   },
	                   error: function() {
	                       $("#fb_login_img").bind("click", loginUsingFb);
	                   }
	                });
	            }

	            function loginUsingFb() {
	                $("#fb_login_img").unbind("click");
	                FB.getLoginStatus(function(response) {
	                    if (response.authResponse) {
	                        submitSignInFB();
	                    } else {
	                        FB.login(function(response) {
	                            if (response.authResponse) {
	                            	if (response.status === 'connected') {
	                                    submitSignInFB();
	                                } else {
	                                    $("#fb_login_img").bind("click", loginUsingFb);
	                                }
	                            } else {
	                                $("#fb_login_img").bind("click", loginUsingFb);
	                            }
	                          }, {scope:'email'});
	                    }
	                });
	                
	            }

	            $("#fb_login_img").bind("click", loginUsingFb);
                $("#fb_login_img").hover(
                        function(){$(this).addClass("hand-pointer");},
                        function(e){$(this).removeClass("hand-pointer");}
                );
	
	            $("#login-or-register-modal .wrapper .background .closex").hover(
	                    function(){$(this).addClass("hand-pointer");},
	                    function(e){$(this).removeClass("hand-pointer");}
	            );
	            $("#login-or-register-modal .wrapper .background .closex").bind("click",
                    function(e) {
                        $("#btn-signin").unbind("click");
                        polaris.clearModal();
                    }
                );
	            $(document).bind("keyup.polaris",
	                function(e) {
	                    if (e.keyCode == 27) {
	                       $("#btn-signin").unbind("click");
	                       polaris.clearModal();
	                    }
	                }
	            );
	            
	            $("#btn-signin").bind("click", submitSignInForm);
                $("#btn-signin").hover(
                        function(){$(this).addClass("hand-pointer");},
                        function(e){$(this).removeClass("hand-pointer");}
                );

	        },
	        show: function() {
                $("#email").focus();
                $("#email").bind("change", clearErrorMessage);
                $("#password").bind("change", clearErrorMessage);
                $("#email").bind("keyup", submitOnEnter);
                $("#password").bind("keyup", submitOnEnter);
                $("#emailerrormsg").addClass("invisible");
                $("#passworderrormsg").addClass("invisible");
	        },
	        hide: function() {
                $("#email").unbind("change");
                $("#password").unbind("change");
                $("#email").unbind("keyup");
                $("#password").unbind("keyup");
	        }
	});
	
}

function setupGoogleAfs(clientId,channel,n,q,locale,adTest,adSafe,page,qctxt,qlnk) {
    if (n < 1) return;
	google_afs_ad = 'n' + n;
	google_afs_adpage = page;
	google_afs_query = q;
	if (channel) {
		google_afs_channel = channel;
	} 
	google_afs_ie = "utf8";
	google_afs_oe = "utf8";
	if (adTest)
		google_afs_adtest = 'on';
	google_afs_adsafe = adSafe;
	google_afs_hl = locale.substring(0,2);
	google_afs_gl = locale.substring(3);
    google_afs_client = clientId;
    google_afs_qry_ctxt = qctxt;
    google_afs_qry_lnk = qlnk;
    
	document.writeln('<script language="JavaScript" src="http://www.google.com/afsonline/show_afs_ads.js"></script>');
}
function setupGoogleAfc(clientId,channel,n,hints,locale,adTest,adSafe,page) {
    google_max_num_ads = n;
	if (hints)
		google_hints = hints;
	if (channel)
		google_ad_channel = channel; 
    google_ad_output = 'js';
	google_encoding = "utf8";
	if (adTest)
		google_adtest = 'on';
	google_safe = adSafe;
	google_language = locale.substring(0,2);

	google_ad_client = clientId;
	document.writeln('<script language="JavaScript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>');

}
function google_afs_request_done(google_ads) {
	if (google_ads.length > 0 && google_ad_request_done)
		google_ad_request_done(google_ads);
}
function trackClick(trackerurl) {
	if (trackerurl!="undefined" && trackerurl) 
		(new Image).src=trackerurl;
	return true;
}

function SBStyleA(google_ads,mplx) {
	var str = '<li class="title"><span class="sponsoredLinks">Sponsored Links</span></li>';
	var sta = [];
	sta.push('<li class="title"><span class="sponsoredLinks">Sponsored Links</span></li>');
    for(var i=0; i < google_ads.length; i++) {

    	var a = '<a class="t" href="' +
    	google_ads[i].url + 
    	'" target="_blank" onclick="return trackClick(\'' + 
    	mplx + '\');"' + 
		' onmouseout="window.status=\'\'" ' + 
		'onmouseover="window.status=\'go to ' + 
		google_ads[i].visible_url + 
		'\'; return true;" >';

    	sta.push('<li>');
    	sta.push(a);
    	sta.push('<div class="adsensePlaceHolder"></div></a><div class="adsenseInfo"><span class="adsenseLine1">'); 
    	sta.push(a); 
    	sta.push(google_ads[i].line1); 
    	sta.push('</a></span><br/><span class="adsenseContent">'); 
    	sta.push(a); 
    	sta.push(google_ads[i].line2); 
    	sta.push(' '); 
    	sta.push(google_ads[i].line3); 
    	sta.push('</a></span><br/><span class="adsenseUrl">'); 
    	sta.push(a); 
    	sta.push(google_ads[i].visible_url); 
    	sta.push('</a></span></div></li>');

    }
	if (sta) {
		$('#bottomAdSense').append(sta.join("")).show();
	}

}
function VAStyleA(google_ads,mplx) {
	SBStyleA(google_ads,mplx);
}
/**** Webtrend codes ***/
var gService = false;
var gTimeZone = 1;
// Code section for Enable First-Party Cookie Tracking
function dcsCookie() {
    if (typeof(dcsOther)=="function") {
        dcsOther();
    }
    else if (typeof(dcsPlugin)=="function") {
        dcsPlugin();
    }
    else if (typeof(dcsFPC)=="function") {
        dcsFPC(gTimeZone);
    }
}
function dcsGetCookie(name) {
    var pos=document.cookie.indexOf(name+"=");
    if (pos!=-1) {
        var start=pos+name.length+1;
        var end=document.cookie.indexOf(";",start);
        if (end==-1) {
            end=document.cookie.length;
        }
        return unescape(document.cookie.substring(start,end));
    }
    return null;
}
function dcsGetCrumb(name,crumb) {
    var aCookie=dcsGetCookie(name).split(":");
    for (var i=0;i<aCookie.length;i++) {
        var aCrumb=aCookie[i].split("=");
        if (crumb==aCrumb[0]) {
            return aCrumb[1];
        }
    }
    return null;
}
function dcsGetIdCrumb(name,crumb) {
    var cookie=dcsGetCookie(name);
    var id=cookie.substring(0,cookie.indexOf(":lv="));
    var aCrumb=id.split("=");
    for (var i=0;i<aCrumb.length;i++) {
        if (crumb==aCrumb[0]) {
            return aCrumb[1];
        }
    }
    return null;
}
function dcsFPC(offset) {
    if (typeof(offset)=="undefined") {
        return;
    }
    var name=gFpc;
    var dCur=new Date();
    dCur.setTime(dCur.getTime()+(dCur.getTimezoneOffset()*60000)+(offset*3600000));
    var dExp=new Date(dCur.getTime()+315360000000);
    var dSes=new Date(dCur.getTime());
    if (document.cookie.indexOf(name+"=")!=-1) {
        var id=dcsGetIdCrumb(name,"id");
        var lv=parseInt(dcsGetCrumb(name,"lv"));
        var ss=parseInt(dcsGetCrumb(name,"ss"));
        if ((id==null)||(id=="null")||isNaN(lv)||isNaN(ss)) {
            return;
        }
        WT.co_f=id;
        var dLst=new Date(lv);
        dSes.setTime(ss);
        if ((dCur.getTime()>(dLst.getTime()+1800000))||(dCur.getTime()>(dSes.getTime()+28800000))) {
            dSes.setTime(dCur.getTime());
            WT.vt_f_s="1";
        }
        if ((dCur.getDay()!=dLst.getDay())||(dCur.getMonth()!=dLst.getMonth())||(dCur.getYear()!=dLst.getYear())) {
            WT.vt_f_d="1";
        }
    }
    else{
        var tmpname=name+"_TMP=";
        document.cookie=tmpname+"1";
        if (document.cookie.indexOf(tmpname)!=-1) {
            document.cookie=tmpname+"; expires=Thu, 01-Jan-1970 00:00:01 GMT";
            if ((typeof(gWtId)!="undefined")&&(gWtId!="")) {
                WT.co_f=gWtId;
            }
            else if ((typeof(gTempWtId)!="undefined")&&(gTempWtId!="")) {
                WT.co_f=gTempWtId;
                WT.vt_f="1";
            }
            else{
                WT.co_f="2";
                var cur=dCur.getTime().toString();
                for (var i=2;i<=(32-cur.length);i++) {
                    WT.co_f+=Math.floor(Math.random()*16.0).toString(16);
                }
                WT.co_f+=cur;
                WT.vt_f="1";
            }
            if (typeof(gWtAccountRollup)=="undefined") {
                WT.vt_f_a="1";
            }
            WT.vt_f_s="1";
            WT.vt_f_d="1";
        }
        else{
            WT.vt_f="2";
            WT.vt_f_a="2";
            return;
        }
    }
    WT.co_f=escape(WT.co_f);
    WT.vt_sid=WT.co_f+"."+dSes.getTime();
    var expiry="; expires="+dExp.toGMTString();
    document.cookie=name+"="+"id="+WT.co_f+":lv="+dCur.getTime().toString()+":ss="+dSes.getTime().toString()+expiry+"; path=/"+(((typeof(gFpcDom)!="undefined")&&(gFpcDom!=""))?("; domain="+gFpcDom):(""));
}

// Code section for Use the new first-party cookie generated with this tag.
var gFpc="WT_FPC";
var gWtId="";
var gTempWtId="";
var gConvert=true;

function dcsAdv() {
    dcsFunc("dcsET");
    dcsFunc("dcsCookie");
    dcsFunc("dcsAdSearch");
    dcsFunc("dcsTP");
}

var gVersion="1.0";
var RE={"%09":/\t/g,"%20":/ /g,"%23":/\#/g,"%26":/\&/g,"%2B":/\+/g,"%3F":/\?/g,"%5C":/\\/g};
var gImages=new Array;
var gIndex=0;
var DCS=new Object();
var WT=new Object();
var DCSext=new Object();
DCSext.origpage = null;
var gQP=new Array();

var gDomain="statse.webtrendslive.com";

function dcsVar() {
    var dCurrent=new Date();
    WT.tz=dCurrent.getTimezoneOffset()/60*-1;
    if (WT.tz==0) {
        WT.tz="0";
    }
    WT.bh=dCurrent.getHours();
    WT.ul=navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
    if (typeof(screen)=="object") {
        WT.cd=navigator.appName=="Netscape"?screen.pixelDepth:screen.colorDepth;
        WT.sr=screen.width+"x"+screen.height;
    }
    if (typeof(navigator.javaEnabled())=="boolean") {
        WT.jo=navigator.javaEnabled()?"Yes":"No";
    }
    if (document.title) {
        WT.ti=document.title;
    }
    WT.js="Yes";
    if (typeof(gVersion)!="undefined") {
        WT.jv=gVersion;
    }
    if (document.body&&document.body.addBehavior) {
	try {
        document.body.addBehavior("#default#clientCaps");
        if (document.body.connectionType) {
            WT.ct=document.body.connectionType;
        }
        document.body.addBehavior("#default#homePage");
        WT.hp=document.body.isHomePage(location.href)?"1":"0";
	} catch(ex) {}
    }
    if (parseInt(navigator.appVersion)>3) {
        if ((navigator.appName=="Microsoft Internet Explorer")&&document.body) {
            WT.bs=document.body.offsetWidth+"x"+document.body.offsetHeight;
        }
        else if (navigator.appName=="Netscape") {
            WT.bs=window.innerWidth+"x"+window.innerHeight;
        }
    }
    WT.fi="No";
    if (window.ActiveXObject) {
        if ((typeof(gFV)!="undefined")&&(gFV.length>0)) {
            WT.fi="Yes";
            WT.fv=gFV;
        }
    }
    else if (navigator.plugins&&navigator.plugins.length) {
        for (var i=0;i<navigator.plugins.length;i++) {
            if (navigator.plugins[i].name.indexOf('Shockwave Flash')!=-1) {
                WT.fi="Yes";
                WT.fv=navigator.plugins[i].description.split(" ")[2];
                break;
            }
        }
    }
    WT.sp="@@SPLITVALUE@@";
    DCS.dcsdat=dCurrent.getTime();
    DCS.dcssip=window.location.hostname;
    DCS.dcsuri=window.location.pathname;
    if (window.location.search) {
        DCS.dcsqry=window.location.search;
        if (gQP.length>0) {
            for (var i=0;i<gQP.length;i++) {
                var pos=DCS.dcsqry.indexOf(gQP[i]);
                if (pos!=-1) {
                    var front=DCS.dcsqry.substring(0,pos);
                    var end=DCS.dcsqry.substring(pos+gQP[i].length,DCS.dcsqry.length);
                    DCS.dcsqry=front+end;
                }
            }
        }
    }
    if ((window.document.referrer!="")&&(window.document.referrer!="-")) {
        if (!(navigator.appName=="Microsoft Internet Explorer"&&parseInt(navigator.appVersion)<4)) {
            DCS.dcsref=window.document.referrer;
        }
    }
}

function A(N,V) {
    return "&"+N+"="+dcsEscape(V);
}

function dcsEscape(S) {
    if (typeof(RE)!="undefined") {
        var retStr = new String(S);
        for (R in RE) {
            retStr = retStr.replace(RE[R],R);
        }
        return retStr;
    }
    else{
        return escape(S);
    }
}

function dcsCreateImage(dcsSrc) {
    if (document.images) {
        gImages[gIndex]=new Image;
        if ((typeof(gHref)!="undefined")&&(gHref.length>0)) {
            gImages[gIndex].onload=gImages[gIndex].onerror=dcsLoadHref;
        }
        gImages[gIndex].src=dcsSrc;
        gIndex++;
    }
    else{
        document.write('<IMG BORDER="0" NAME="DCSIMG" WIDTH="1" HEIGHT="1" SRC="'+dcsSrc+'">');
    }
}

function dcsMeta() {
    var elems;
    if (document.all) {
        elems=document.all.tags("meta");
    }
    else if (document.documentElement) {
        elems=document.getElementsByTagName("meta");
    }
    if (typeof(elems)!="undefined") {
        for (var i=1;i<=elems.length;i++) {
            var meta=elems.item(i-1);
            if (meta.name) {
                if (meta.name.indexOf('WT.')==0) {
                    WT[meta.name.substring(3)]=meta.content;
                }
                else if (meta.name.indexOf('DCSext.')==0) {
                    DCSext[meta.name.substring(7)]=meta.content;
                }
                else if (meta.name.indexOf('DCS.')==0) {
                    DCS[meta.name.substring(4)]=meta.content;
                }
            }
        }
    }
}

function dcsTag(domain, dcsId) {
    var P="http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+domain+(dcsId==""?'':'/'+dcsId)+"/dcs.gif?";
    for (N in DCS) {
        if (DCS[N]) {
            P+=A(N,DCS[N]);
        }
    }
    for (N in WT) {
        if (WT[N]) {
            P+=A("WT."+N,WT[N]);
        }
    }
    for (N in DCSext) {
        if (DCSext[N]) {
            P+=A(N,DCSext[N]);
        }
    }
    if (P.length>2048&&navigator.userAgent.indexOf('MSIE')>=0) {
        P=P.substring(0,2040)+"&WT.tu=1";
    }
    dcsCreateImage(P);
}

function dcsFunc(func) {
    if (typeof(window[func])=="function") {
        window[func]();
    }
}

function dcsMultiTrack() {
    if (arguments.length%2==0) {
        for (var i = 0; i < arguments.length; i+=2) {
            if (arguments[i].indexOf('WT.')==0) {
                WT[arguments[i].substring(3)]=arguments[i+1];
            }
            else if (arguments[i].indexOf('DCS.')==0) {
                DCS[arguments[i].substring(4)]=arguments[i+1];
            }
            else if (arguments[i].indexOf('DCSext.')==0) {
                var name = arguments[i].substring(7);
                DCSext[name]=arguments[i+1];
                if (name == "page")
                	DCSext.origpage=arguments[i+1];
            }
        }
        var dCurrent=new Date();
        DCS.dcsdat=dCurrent.getTime();
        dcsFunc("dcsCookie");
        if (eclLucky()) {
            dcsTag(gDomain, gDcsId);
        }
    }
}

function eclGetQuery() {
	var res = null;
	var inp = ""+document.URL;
	var indx = inp.lastIndexOf("/");
	if (indx > 0) {
		indx = inp.indexOf("?", indx);
		if (indx > 0) {
			res = inp.substring(indx+1);
		} else {
			indx = inp.indexOf("W0QQ", indx);
			if (indx>0) {
				inp = inp.substring(indx+4);
				res = inp.replace(/QQ/g, "&").replace(/Z/g, "=");
			}
		}
	}
	if (res)
		res = res.replace(/Page=/g, "PageZ=");

	return res;
}
function eclMods() {
    if (document.title) {
        WT.ti=escape(document.title);
    }
    if (typeof(DCSext.page)!="undefined") {
        DCS.dcsuri='/'+DCSext.page;
    }else if (DCS.dcsuri) {
        DCSext.page=DCS.dcsuri.substr(1,DCS.dcsuri.length-1);
    }
    if (DCS.dcsref) {
		DCS.dcsref=DCS.dcsref.replace(/(http:\/\/.*?\.(kijiji|gumtree|ebayclassifieds)\..*?)\/.*/,'$1');
    }
    var kjj_query = eclGetQuery();
    if (kjj_query)
        DCS.dcsqry=kjj_query;
}

function eclLucky() {
    var cn = 'luckynumber';
    ln = dcsGetCookie(cn);
    if (ln == null) {
        ln = Math.floor(Math.random()*1000000);
        var date = new Date();
        date.setTime(date.getTime()+(30*24*60*60*1000));
        document.cookie = cn+"="+ln+"; expires="+date.toGMTString()+"; path=/; domain="+gCookieDomain+";";
    }
    return ((ln % 1000) < 100);
}
function wtExternalPage(pageName) {
	if (DCSext.origpage == null)
		DCSext.origpage = DCSext.page;
	DCSext.page = pageName + "-" + DCSext.origpage;
	eclMods();
	dcsTag(gDomain, gDcsId);
}

function initWebTrend() {
	if ((document.cookie.indexOf("WT_FPC=")==-1)&&(document.cookie.indexOf("WTLOPTOUT=")==-1)) {
        var url = "http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+gDomain+"/"+gDcsId+"/wtid.js";
		$(document).executeOnce('webtrend',2000, function() {
			$.getScript(url,doWebTrend);
		});
	} else {
		doWebTrend();
	}
}
function doWebTrend() {
	dcsVar();
	dcsMeta();
	dcsFunc("dcsAdv");
	eclMods();
	if (eclLucky()) {
		dcsTag(gDomain, gDcsId);
		$('.twitter').click(function() {
			wtExternalPage('twitter');
		});
		$('.facebook').click(function() {
			wtExternalPage('facebook');
		});
	}
}

var agt = navigator.userAgent.toLowerCase();
var isIE	= (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin	= (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isSafari = (agt.indexOf("safari") != -1) ? true : false;

function ControlVersion() {
	var version;
	var axo;
	var e;

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.9");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	
	if (!version)
	{
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.8");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	
	if (!version)
	{
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

function GetSwfVer() {

	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;			
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			if (descArray[3] != "") {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if (isIE && isWin && !isOpera) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	
	if (versionStr == -1) {
		return false;
	} else if (versionStr != 0) {
		if (isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0]; //2
		var versionMinor      = versionArray[1]; //0	
		var versionRevision   = versionArray[2]; //0
		
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function initCopyClipBoard(config) {

    ZeroClipboard.setMoviePath( config.pathToFlash+'ZeroClipboard.swf' );
    var clip = new ZeroClipboard.Client();
    clip.setHandCursor( true );
    clip.setText( '' ); 
    clip.setHandCursor( true );
    clip.setCSSEffects( true );

    if(document.getElementById(config.zero_clipboard)){
        document.getElementById(config.zero_clipboard).innerHTML =  clip.getHTML(config.clipWidth, config.clipHeight).replace(/align="middle"/i, 'align="top"');
    }

    var btn = document.getElementById( config.d_clip_button );

    clip.addEventListener( 'mouseOver', function(client) {
        btn.style.backgroundPosition = "0px -14px";                                 
    } );

    clip.addEventListener( 'mouseOut', function(client) { 
        btn.style.backgroundPosition = "0px -0px";
    } );

    clip.addEventListener( 'mouseDown', function(client) { 
        btn.style.backgroundPosition = "0px -28px";
        clip.setText(config.shortAdUrl);
    } );

    clip.addEventListener( 'mouseUp', function(client) { 
        btn.style.backgroundPosition = "0px -14px";
    } );
}

function displayBlogEntries(url) {
	
	$.jGFeed(url,
		function(feeds){
		    // Check for errors
		    if(!feeds){
		      // there was an error
		    	return false;
		    }
		    var html = '<ul>';
		    
		    // do whatever you want with feeds here
		    for(var i=0; i<feeds.entries.length; i++){
		      var item = feeds.entries[i];
		      // Entry title
		      	//feed +=entry.title+"<br/>";
		    	html += '<li>' +
                '<a href ="' + item.link + '"  style="text-decoration:underline" target="_blank">' +
                	item.title + '</a> ' +
                //'<p>' + item.description + '</p>' +
                '</li>';		    	
		    }
		    $("#blog-feed").append(html);
	  }, 3);
}




//implementing recent view ads
var rva = (function (recentlyViewedAdsURL, imagePath) {
    var number_of_pages, number_of_ads,
	
    animate = (function () {

        var movingDistance	    = 875;

        var $panels				= $('#slider .scrollContainer > div');

        var $container			= $('#slider .scrollContainer');

        $panels.css({
            'float' : 'left',
            'position' : 'relative'
        });

        $("#slider").data("currentlyMoving", false);

        $container.css('width', (($($panels[0]).width() + 107) * $panels.length)).css('left', "0px");

        var scroll = $('#slider .scroll').css('overflow', 'hidden');

        //direction true = right, false = left
        function change(direction) {

            if (curPage === 1 && !direction) {
                return false;
            } else if (curPage === number_of_pages && direction) {
                return false;
            }
            //if not currently moving
            if (($("#slider").data("currentlyMoving") === false)) {

                $("#slider").data("currentlyMoving", true);

                var next         = direction ? curPage + 1 : curPage - 1;

                var leftValue    = $(".scrollContainer").css("left");

                var movement	 = direction ? parseFloat(leftValue, 10) - movingDistance : parseFloat(leftValue, 10) + movingDistance;

                $(".scrollContainer").stop().animate({
                    "left": movement
                },
                'fast',

                function () {
                    $("#slider").data("currentlyMoving", false);
                });

                curPage = next;

                /*handling left arrow*/
                if (curPage === 1) {
                    $("#left_arrow").removeClass('left-arrow-normal');
                    $("#left_arrow").addClass('left-arrow-disable');
                } else {
                    $("#left_arrow").removeClass('left-arrow-disable');
                    $("#left_arrow").addClass('left-arrow-normal');
                }

                if (curPage === number_of_pages) {
                    $("#right_arrow").removeClass('right-arrow-normal');
                    $("#right_arrow").addClass('right-arrow-disable');
                } else {
                    $("#right_arrow").removeClass('right-arrow-disable');
                    $("#right_arrow").addClass('right-arrow-normal');
                }

                /* displaying current page number*/
                $('#current_page_number').html(curPage);
            }
        }

        var curPage = 1;
        $("#right_arrow").click(function (event) {
            change(true);
            event.preventDefault();
        });

        $("#left_arrow").click(function (event) {
            change(false);
            event.preventDefault();
        });

        $(window).keydown(function (event) {
            switch (event.keyCode) {
                case 13: //enter
                    $(".right").click();
                    break;
                case 32: //space
                    $(".right").click();
                    break;
                case 37: //left arrow
                    $(".left").click();
                    break;
                case 39: //right arrow
                    $(".right").click();
                    break;
            }
        });

    });

	

    thisObj = {	
        init: function () {
		
            $.ajax({
                type: "GET",

                url: recentlyViewedAdsURL,

                data : "p=0&s=5&jsoncallback=?",

                dataType: "json",

                success: function (json) {

                    if (json.ads) {

                        number_of_pages = json.numPages;
					
                        number_of_ads = json.total;
					
                        $('#current_page_number').html("1");

                        $('#number_of_pages').html(number_of_pages);
					
                        $('#number_of_ads').html(number_of_ads);
					
					
                        thisObj.refreshControl();

                        var ar = [], start = 0;
					
                        ar = thisObj.getPageArray(start, json);
					
                        $('#rva').html(ar.join(""));

                    }
                },
                complete: function (xhr, status) {
                    if (number_of_pages > 1) {
                        thisObj.loadOtherPages();
                    } else {
                        thisObj.handleDeleteAd();
                        thisObj.googleAnalylicFnCall();
                    }
                }
            });
        },
	
        googleAnalylicFnCall: function () {
        	
        	$('#slider a').each(function () {
                $(this).click(function (e) {
                    var target = $(this).attr('name');
                    var className = $(this).attr('class');

                    if (target && className && className.indexOf('disable') == -1) {
                        trackRecentlyViewedEvent(target);
                    }
                });
            });
        },
        
        getPageArray: function (start, json) {

            var i, len = json.ads.length, ad, ar = [];
		
            for (i = start; i < len; i++) {
			
                ad = json.ads[i];
			
                ar.push('<div class="panel" id="panel_' + ad.id + '">');
			
                ar.push('<a href="#" name="Listing_Delete" class="delete-icon-hover">delete icon</a>');

                ar.push('<div class="inside">');
			
                if (!ad.outOfArea) {
                	
                    ar.push('<a name="Listing" href="' + ad.viewAdUrl + '">');
                    
                    ar.push('<img  src="' + ad.photoUrl + '" />');
        			
                    ar.push('</a>');
    			
                    ar.push('</div>');
    			
                    ar.push('<span class="ad-detail">');
    			
                    ar.push('<a class="price op" href = \'' + ad.viewAdUrl + '\'>' + thisObj.displayPrice(ad) + '</a>');
    				
                    ar.push('<div class="gallery-ad-title"><a class="t" name="Listing" href="' + ad.viewAdUrl + '">' + ad.title + '</a></div>');
                    
                } else {
                	
                    ar.push('<a name="Listing" target="_blank" href="' + ad.viewAdUrl + '">');
                    
                    ar.push('<img  src="' + ad.photoUrl + '" />');
        			
                    ar.push('</a>');
    			
                    ar.push('</div>');
    			
                    ar.push('<span class="ad-detail">');
    			
                    ar.push('<a class="price op" target="_blank" href = \'' + ad.viewAdUrl + '\'>' + thisObj.displayPrice(ad) + '</a>');
    				
                    ar.push('<div class="gallery-ad-title"><a class="t" name="Listing" target="_blank" href="' + ad.viewAdUrl + '">' + ad.title + '</a></div>');
                }

                ar.push('<div class="gallery-ad-loc-cat"><span>' + ad.city + '</span></div>');
				
                ar.push('<div class="post-date">Posted: ' + thisObj.dateConvert(ad.startDate ? ad.startDate : ad.dateCreated) + '</div>');
			
                ar.push('</span>');
		
                ar.push('</div>');
            }
            return ar;
        },

        refreshControl: function () {
		
            if (number_of_pages > 0) {
                $('#number_of_pages').html(number_of_pages);
            }

            if (number_of_pages > 1) {
			
                $("#right_arrow").removeClass('right-arrow-disable').addClass('right-arrow-normal');
			
            } else {
                $("#right_arrow").removeClass('right-arrow-normal').addClass('right-arrow-disable');
            }
		
		
            if (number_of_ads === 0) {
                $('#deleteAll, #seeAll').addClass('disable');

                $('#rva').html('<div id="emptyPanel" class="emptyPanel">&nbsp;</div>');

                $('body').trigger('emptyAds');
            } else {
                $('#deleteAll, #seeAll').removeClass('disable');
            }
		
            $('.adCnt').html(number_of_ads);
		
        },
	
        displayPrice: function (ad) {
		
            var displayPrice;
		
            if (ad.priceType === 'SPECIFIED_AMOUNT') {
            	displayPrice = '$' + addComma(ad.price);
            } else if (ad.priceType === 'FREE') {
			
                displayPrice = 'Free';
			
            } else if (ad.priceType == 'PLEASE_CONTACT') {
	    	
                displayPrice = 'Please contact for price';
	    	
            } else {
	    	
                displayPrice = '&#160;';
            }
            return displayPrice;
        },

        dateConvert: function (timeStamp) {
        	
            var d = new Date(timeStamp);
		
            return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear().toString().substring(2);
        },

        loadOtherPages: function () {

            $.ajax({

                type: "GET",

                url: recentlyViewedAdsURL,

                data : "s=48&jsoncallback=?",

                dataType: "json",

                success: function (json) {

                    if (json.ads) {
					
                        var ar = [], start = 5;
					
                        ar = thisObj.getPageArray(start, json);

                        $('#rva').append(ar.join(""));

                        animate();
                    }
                },
                complete: function (xhr) {

                    thisObj.handleDeleteAd();
                    
                    thisObj.googleAnalylicFnCall();
                }
            });
        },

        handleDeleteAd: function () {
            $('.delete-icon-hover').bind('click', function (event) {
			
                var id = $(this).parent().attr("id").split("_")[1];
			
                var thisElem = this;

                $.ajax({

                    type: "GET",

                    url: recentlyViewedAdsURL,

                    data : 'cmd=DELETE_AD&s=5&id=' + id + '&jsoncallback=?',

                    dataType: "json",

                    success: function (json) {

                        number_of_pages = json.numPages;
					
                        number_of_ads = json.total;
					
                        $('#number_of_ads').html(number_of_ads);
					
                        $(thisElem).unbind();
		
                        $(thisElem).parent().remove();
					
                        thisObj.refreshControl();
                    }
                });
                event.preventDefault();
            });
		
            $('#deleteAll').bind('click', function (event) {
			
                if (parseInt($('.adCnt').html(), 10) === 0) {
                    return false; 
                }
			
                if (confirm("Are you sure you want to clear all recently viewed ads?")) { 
				
                    trackRecentlyViewedEvent('Delete_All_Confirm');

                    $.ajax({

                        type: "GET",

                        url: recentlyViewedAdsURL,

                        data : 'cmd=DELETE_ALL_ADS&jsoncallback=?',

                        dataType: "json",

                        success: function (json) {
				
                            number_of_pages = json.numPages;
					
                            number_of_ads = json.total;

                            $('#number_of_pages').html('1');
					
                            $('#number_of_ads').html(number_of_ads);
					
                            $('#rva').empty();
					
                            thisObj.refreshControl();
                        }
                    });
                }
	
                event.preventDefault();
            });
		
            $('#slider .panel').mouseenter(function () {
                var thisElem = $(this);
                thisElem.children(':first-child').addClass('active-ad-delete-icon');
                thisElem.addClass('active-ad-background-color');
            }).mouseleave(function () {
                var thisElem = $(this);
                thisElem.children(':first-child').removeClass('active-ad-delete-icon');
                thisElem.removeClass('active-ad-background-color');
            });
        },

        initAllRva: function (o) {
            $.searchBrowseViewConfig({
                galleryView: o.galleryView,
                toggleViewURL: o.toggleViewURL
            });

            var sortMenuOption = {
                name: 'Sort',
                container : '#ui-search-result-sort', 
                list : o.sortList,
                menuSelected : function (li, val) {
                    trackRecentlyViewedEvent('Change_Sort');
                    window.location = val; 	
                    return false;
                }
            };
		
            $('#ui-search-result-sort a').popupMenu(sortMenuOption, o.sortMenuOptionValue);

            thisObj.handleDeleteAd();

            $('body').bind('emptyAds', function (e) { 
                window.location.reload();
            });
            
        },
				
        initTabRva: function (option) {
        	var rva_current_tab;
            $('#rva-main .topCurve, #rva-main .header, #rva-main .bottomCurve ').remove();
            
            $("#rva-main").addClass("rva-tabs");

            $(function () {
                function handleSelect(event, tab) {
                    $('#viewAdtabs li.ui-state-default span').css({
                        'background': 'transparent url(' + imagePath + "NotActiveTabRightCorner.gif" + ') no-repeat right top'
                    });
                    document.getElementById(tab.index + '').style.background = 'transparent url(' + imagePath + "ActiveTabRightCorner.gif" + ') no-repeat right top';
                    
                    $.cookie("rva_current_tab", tab.index, { path: '/' });
                }
                
                rva_current_tab = ($.cookie('rva_current_tab') === null) ? -1 : $.cookie('rva_current_tab'); 

                var tabOpts = {},
                st = option.has_similarAds ? 0 : 4;
        		st = st + (option.has_recentlyViewedAds ? 0 : 6);
        		st = st + ((rva_current_tab === -1) ? 0 : 12);

        		switch(st) {
        			case 0: // There is no empty tabs
        				tabOpts.selected = 0;
        				break;
        			case 4: // similarAds is empty
        				tabOpts.disabled = [0];
        				tabOpts.selected = 1;
        				break;
        			case 6: // recentlyViewedAds is empty
        				tabOpts.disabled = [1];
        				tabOpts.selected = 0;
        				break;
        			case 10: // recentlyViewedAds and similarAds are empty
        				tabOpts.disabled = [0, 1];
        				break;
        			case 12: // select the last open tab
        				tabOpts.selected = rva_current_tab;
        				break;
        			case 16: // similarAds is empty
        				tabOpts.disabled = [0];
        				tabOpts.selected = 1;
        				break;
        			case 18: // recentlyViewedAds is empty
        				tabOpts.disabled = [1];
        				tabOpts.selected = 0;
        				break;
        		}
        		
        	    tabOpts.select = handleSelect;
                
                $("#viewAdtabs").tabs(tabOpts);
                
                handleSelect(null, {"index": tabOpts.selected});

            });
        }
    };

    /*trackRecentlyViewedEvent('Widget_Display');*/
    return thisObj;
});


trackRecentlyViewedEvent = function(action) {
	if(typeof trackEvent === 'function'){
		var p=[];
		p.cat='Recently_Viewed';
		p.action=action;
		trackEvent(p);
	}
}
trackLoginButtonClick =  function(cat){
    if(typeof trackEvent === 'function'){
		var p=[];
		p.cat=cat;
		p.action='Button_Click';
		trackEvent(p);
	}
}
trackLoginButtonSuccess =  function(cat){
    if(typeof trackEvent === 'function'){
		var p=[];
		p.cat=cat;
		p.action='Success';
		trackEvent(p);
	}
}
trackAdViewedFromNaturalSearch = function(cat) {
	if(typeof trackEvent === 'function'){
		var p=[];
		p.cat=cat;
		p.action='Ad_Viewed_From_Natural_Search';
		trackEvent(p);
	}
}

var redBeacon = (function () {
	trackRedbeacon("redbeacon_banner_display");
	$('.redbeacon').bind('click', {msg: 'redbeacon_banner_clicked'}, trackRedbeacon);
	var win = $('.redbeacon').popupWindow({ 
		centerBrowser:1,
		height:595, 
		width:317,
		resizable:1  
	});
});

var trackRedbeacon = function(action) {
	if(typeof trackEvent === 'function'){
		var p={};
		p.cat='redBeacon';
		p.action= (action.data) ? action.data.msg: action;
		trackEvent(p);
	}
}

/*global javascript function*/
function addComma(price)
{
	price += '';
	x = price.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	/*return x1 + x2;*/
	return x1;
}


var POLARISWEB = POLARISWEB || {}; 
POLARISWEB.namespace = function (ns_string) {
		var parts = ns_string.split('.'),
		parent = POLARISWEB,
		i; 
		// strip redundant leading global
		if (parts[0] === "POLARISWEB") { 
			parts = parts.slice(1);
		}
		for (i = 0; i < parts.length; i += 1) { 
			// create a property if it doesn't exist
			if (typeof parent[parts[i]] === "undefined") { 
				parent[parts[i]] = {};
			} parent = parent[parts[i]];
		} 
		return parent;
	};
//longer namespace example
//POLARISWEB.namespace('once.upon.a.time.there.was.this.long.nested.property');
	
//creating a new namespace, POLARISWEB.viewAdContent 	
POLARISWEB.namespace('viewAdContent');

POLARISWEB.viewAdContent = function (o) {

		
	
			jQuery('#shortAdUrl').click(function() {
				selectAllText(jQuery(this)) 
			});
	
			function selectAllText(textbox) {
		        textbox.focus();
		        textbox.select();
		    }
			$('#email-share').click(function(e) {
				e.preventDefault();
				showModal(); 
			});
		
			
			
			
			$('#ad-reply-form').appendTo('#ad-reply');
			
			$('#ask-question-form').appendTo('#ad-reply');
			
			
			$('#fromAddress')[0].value = '';
			$('#message')[0].value = '';
			   $('.flagAdUrl').click(function(ev) {
			   	$('.flagAdUrl').unbind('click');
			    ev.preventDefault();
			    var link = this;
			    $.getJSON(o.flagAdUrl + '?adid=' + $(this).attr('flag') + '&jsoncallback=?', 
			        function(json) {
			            $('#ui-flag-list ul').html('<li>Flagged.  Thanks!</li>');
			        });
			});
			$('#flag-ad, #ui-flag-list').bind('mouseover',function(e){
			    $('#flag-ad').parent().addClass('over');
			    $('#ui-flag-list').show();
			});
			$('#ui-flag-list').bind('mouseout',function(e){
			    $('#flag-ad').parent().removeClass('over');
			    $(this).hide();
			});
			$('#flag-this').bind('mouseout',function(e){
			    $('#flag-ad').parent().removeClass('over');
			    $('#ui-flag-list').hide();
			});
			$('#ui-flag-list').appendTo('#flag-this li');//.show(); 
			$("#reply-by-email").click(
			    function() {
			    	 $("#ask-question-form").hide();	
			        $("#ad-reply-form").toggle("slow", 
			            function(){
							$('#message').focus();
							$('#fromAddress').focus();
			                var bbinp = document.getElementById("BbUserInputId");
			                insertThreatMetrix();
			            }
			        );
					$("#email-attachment").show(); /*to fix for opera browser which sets display none*/
			        $("#on-reply-mesg").html('');
			    }
			);
			
			/*
			$("#closeReplyFormXLink").click(
			    function() {
			        $("#ad-reply-form").hide("slow");
			    }
			);
			$('#reply-submit').click(submitByAjax);
			*/
			
			
			
			
			
			/*$('#ask-question-form').appendTo('#ad-reply');*/
			
			$("#ask-question").click(
				    function() {
						$("#ad-reply-form").hide();
				        $("#ask-question-form").toggle("slow", 
				            function(){
								$('#message').focus();
								$('#fromAddress').focus();
				                var bbinp = document.getElementById("BbUserInputId");
				                insertThreatMetrix();
				            }
				        );
				    }
				);
				/*
			   $("#askQuestionFormXLink").click(
		            function() {
		                $("#ask-question-form").hide("slow");
		            }
		        );
		        */
			
	}



POLARISWEB.namespace('jqueryui.dialog.feedback');

POLARISWEB.jqueryui.dialog.feedback = function (deletionFeedbackURL) {
    $("#feedbackDiv").dialog({
        autoOpen: false,
        height: 575,
        width: 410,
        modal: true,
        draggable: true,
        open: function (event, ui) {
            $('body').css('overflow', 'hidden');
            $('.ui-widget-overlay').css('width', '100%');
            $('#feedbackDiv').data('thisDialog', $(this));
            $('#feedbackDiv').parent().removeClass('ui-widget-content');
            $('#feedbackDiv').parent().children(':first-child').css('display', 'none');
            $('.ui-dialog .ui-resizable-se').css('bottom', '7px');
            $('.ui-dialog .ui-resizable-se').css('right', '7px');
            if ($.browser.msie) {
            	window.scrollTo(0,0);
            	$('.ui-widget-overlay').css('position','fixed'); 
            }	
        },
        close: function (event, ui) {
            $('body').css('overflow', 'auto');
            $('#errorMsg').empty();
            $("#userComments").val('');
            $("#feedBackForm input:radio").removeAttr("checked");
        }
    });
	
    $.each([$('#closeIcon'), $('#close')], function () {
        this.bind('click', function () {
            $("#feedbackDiv").data("thisDialog").dialog("close");
        });
    });
	
    $('#userComments').keyup(function () {
        var isChecked = $("#feedBackForm input:radio").is(':checked');
        if (!isChecked) {
            $('#feedbackDiv input:radio:nth(5)').attr("checked", "checked");
        }
    });

    $("#submitButon").bind('click', function (e) {
        submitThisForm();
        e.preventDefault();
    });

    function submitThisForm() {
        var valid = false;
        valid = $("#feedBackForm input:radio").is(':checked');
        $('#errorMsg').empty();
			
        if (!valid) {
            $('#errorMsg').append('<span>Please select an option</span>');
            return false;
        } else {
            $('#errorMsg').empty();
        }
			
        valid = ($("#userComments").val().length < 1001);
			
        if (!valid) {
            $('#errorMsg').append('<span>Max 1000 characters allowed</span>');
            return false;
        } else {
            $('#errorMsg').empty();
        }
				
        if (valid) {
            $.ajax({
                type: 'POST',
                url: deletionFeedbackURL,
                data: $('#feedBackForm').serialize(),
                success: function () {
                    $('#feedbackDiv #content').css('display', 'none');
                    $('#feedbackDiv .thanks').css('display', 'block');
                    window.setTimeout(function () {
                        $('#feedbackDiv #content').css('display', 'none');
                        $('#feedbackDiv .thanks').css('display', 'block');
                        $("#feedbackDiv").data("thisDialog").dialog("close");
                    }, 2000);
                }
            });
        }
    }
    
};	

POLARISWEB.namespace('myAds');
POLARISWEB.myAds = function () {
	if ($('#myAdMsg').html().indexOf('has been deleted successfully.') > -1){
		_gaq.push(['_trackPageview', '/vp/delete-ad/userdelete/']);
	}
};	


POLARISWEB.namespace('apiPartnerRequest');
POLARISWEB.apiPartnerRequest = function () {
    var that = {
        page0: function () {
            $('#applicationFormBtn').bind('click', function () {
                $("#apiPartnerForm0").submit(); 
            });
        },

        page1: function (state) {
        	$('#nextBtn').bind('click', function () {
                $("#apiPartnerForm").submit(); 
            });
        	$('#state').attr('value', state);
            $('#BbUserInputId_field label:first').append('<span class="required"> *</span>');
            $("#apiPartnerForm").validate({
                rules: {
                    companyName: {
                        required: true
                    },
                    street: {
                        required: true
                    },
                    city: {
                        required: true
                    },
                    state: {
                        required: true
                    },
                    zipCode: {
                        required: true,
                        postalcode: true
                    },
                    contactPersonName: {
                        required: true
                    },
                    contactPersonEmail: {
                        required: true,
                        email: true
                    },
                    contactPersonPhone: {
                        required: true,
                        phoneUS: true
                    },

                    websiteUrl: {
                        required: true,
                        url3: true
                    },
                    reasonforAPIRequest: {
                        required: true,
                        maxlength: 500
                    },
                    isProvider: {
                    	checkboxes: true
                    }
                },
                messages: {
                    companyName: "Please enter company name",
                    street: "Please enter street address",
                    city: "Please enter city",
                    state: "Please select a state",
                    zipCode: "Please enter zip code",
                    contactPersonName: "Please enter contact person name",
                    contactPersonEmail: "Please enter contact person email address",
                    contactPersonPhone: "Please enter contact person phone number",
                    websiteUrl: "Please enter website URL",
                    reasonforAPIRequest: "Please enter website description (max 500 characters)"
                }
            });
        },
        page2: function() {
        	$('#apiPatnerAgreeButton').animate({'opacity' : .5});
        	$('#apiPatnerAgreeButton').bind('click', function () {
        		$("#apiPartnerForm2").submit(); 
            });

        	$('#apiPatnerScroll').bind('scroll', function() {
        		if ($("#apiPatnerScroll").scrollTop()>6100){
        			$('#apiPatnerAgreeButton').animate({'opacity' : 1}); 
        			$(this).unbind("scroll");
        		}
        	});
        }
    };
    return that;
};

POLARISWEB.namespace('nakedApartment');
POLARISWEB.nakedApartment = function (ub) {
    $.ajax({
        url: ub.url,
        type: 'GET',
        dataType: 'jsonp', 
        data: {
            'key': ub.key
        },
        success: function (json) {
            if (json.photo_url === null) {
                $("#broker-profile-picture #brokerPicture").attr("src", ub.aImage);
            } else {
                $("#broker-profile-picture #brokerPicture").attr("src", json.photo_url);
            }
            $("#broker-profile-header #name").html(json.name);
            $("#broker-profile-header #company").html(json.company);
            if (json.rating === null) {
                $("#broker-profile-rating #rating").html('<span class = "italic bld"> Not yet rated</span>');
            } else {
                $("#broker-profile-rating #rating").html('<span id="a_rating"><img class="rating-image" src = ' + json.rating_image_url + '/></span>');
            }

            $('#broker-link-div .profileUrl, #broker-profile-rating #a_rating').bind('click', function (e) {
                _gaq.push(['_trackPageview', '/vp/view-ad/naked-apartments-profile-clicked']);

                var url = json.profile_url,
                win = window.open();
            	
                function setUrl() {
                    win.document.location.href = url;
                }
                setTimeout(setUrl, 100);
            });
        }
    });
};


POLARISWEB.namespace('userInfo');
POLARISWEB.userInfo = function (ui) {
    
    $('#poaurl').bind('click', function (e) {
        e.preventDefault();
        _gaq.push(['_trackPageview', '/vp/view-ad/' + ui.userType + '/view-all-ads-clicked/' ]);
        var url = ui.poaUrl,
        win = window.open();
        function setUrl() {
            win.document.location.href = url;
        }
        setTimeout(setUrl, 100);
    });
    
    $('#userBadge .facebook-userbadge-link').bind('click', function (e) {
        e.preventDefault();
        _gaq.push(['_trackPageview', '/vp/view-ad/' + ui.userType + '/profile-fb-clicked/']);
        win = window.open();
        function setUrl() {
            win.document.location.href = polaris.facebook.profileLink;
        }
        setTimeout(setUrl, 100);
    });
};



POLARISWEB.namespace('apiDocs');
POLARISWEB.apiDocs = function(){
	$('.apiDocs #s_response_0').bind('click', function() {
		$('#sample_response_0').toggle('slow');
	});
	
	$('.apiDocs #s_response_1').bind('click', function() {
		$('#sample_response_1').toggle('slow');
	});
	
	$('.apiDocs #s_response_2').bind('click', function() {
		$('#sample_response_2').toggle('slow');
	});

	$('.apiDocs #s_response_3').bind('click', function() {
		$('#sample_response_3').toggle('slow');
	});

	$('.apiDocs #s_response_4').bind('click', function() {
		$('#sample_response_4').toggle('slow');
	});

	$('.apiDocs #s_response_5').bind('click', function() {
		$('#sample_response_5').toggle('slow');
	});
	
	$('.apiDocs .sample-response a').bind('click', function(e) {
		e.preventDefault();
	});
};

POLARISWEB.namespace('common.nextPrevious');
POLARISWEB.common.nextPrevious = function () {

    $('.gallery-ad-title a').click(function (e) {
        submitForm(e, $(this));
    });
	
    $('.gallery-ad-top-nopic, .ad-detail div.price').click(function (e) {
        submitForm(e, $(this).parent().find('a'));
    });
	
    $('.tn img').click(function (e) {
        submitForm(e, $(this).parent().parent().parent().find('a'));
    });
    
    
    /* handling list view*/
    $('.search-results .tn img').click(function (e) {
        submitForm(e, $(this).parent().parent().find('a'));
    });
    
    $('.search-results a.t').click(function (e) {
        submitForm(e, $(this));
    });
    /* handling list view end*/
    
    

    function submitForm(e, va) {
        e.preventDefault();
        var adId = va.attr('id'),
        url = va.attr('href'),
        target = va.attr('target');
        $('#currAdId').val(adId);	
        $('#browseAds').attr("action", url);
        if (target !== "") {
            vac = va.clone();
            vac.attr('target', '');
            window.open(vac.attr('href'));
        } else {
            $('#browseAds').submit();
        }
    }
};

POLARISWEB.namespace('common.ga');
POLARISWEB.common.ga = function (o) {
    var vp = '/vp/',
    category  = (o.categoryName !== undefined && o.categoryName !== '') ? "/" + o.categoryName.replace(/\s+/g, "-"):"",
    parentCategory = (o.parentCategoryName !== undefined && o.parentCategoryName !== '') ?  "/" + o.parentCategoryName.replace(/\s+/g, "-"):"";
	
    if (o.pageId === 'AreaHome' || o.pageId === 'Home') {
        _gaq.push(['_trackPageview']);
    } else {
        if (o.pageId === 'ViewAd' || o.pageId === 'Reply' || o.pageId === 'SearchAd' || o.pageId === 'BrowseAd') {
            _gaq.push(['_trackPageview', vp + o.pageId + parentCategory + category]);
        } else if (o.pageId === 'SelectCategory' || o.pageId === 'PostAd' || o.pageId === 'PreviewAd' || o.pageId === 'ConfirmAd') {
        	_gaq.push(['_trackPageview', vp + o.postType + o.pageId + parentCategory + category]);
        }
    }
};

POLARISWEB.questionAndAnswer = function (o) {
    var qnaUrl = "/m/qna",
    refresh = function (o) {
        $.ajax({
            type: "GET",
            url: qnaUrl,
            data : "adId=" + o.adId + "&sellerView= " + o.isOwnAd + "&now=" + (new Date()),
            dataType: "json",
            success: function (json) {
                if (o.clear) {
                    $("#qnaMainDiv .content").children().each(function () {
                        var that = $(this);
                        if (!that.hasClass("hide")) {
                            that.remove();
                        }
                    });
                }
                var i, clone, noOfQuestions, noOfAnswers, ar = [];
                
                
                

                if (o.isOwnAd === "true") {
                	if (json.numUnansweredQuestions == 0) {
                		$('#qnaMainDiv .titleSuffix').html(" Management");
                	}else if (json.numUnansweredQuestions == 1) {
                		$('#qnaMainDiv .titleSuffix').html(" Management (1 new question)");
                	} else {
                    	$('#qnaMainDiv .titleSuffix').html(" Management (" + json.numUnansweredQuestions + " new questions)");
                	}
                }
    		
                for (i = 0 ; i < json.numUnansweredQuestions; i = i + 1) {
                    clone = $('.template-qna-mgmt-div').clone();
                    $(clone).find(".question-text").text('' + json.data[i].questionText + " ");
                    $(clone).find(".send-by-text").html(" - Sent by <b>" 
                    		+ ((json.data[i].buyerName === "") ? "interested user" : escapeHTML(json.data[i].buyerName)) 
                    		+ "</b> on " + json.data[i].questionDate + "");
                    $(clone).find(".adId").val(o.adId);
                    $(clone).find(".sellerView").val(o.isOwnAd);
                    $(clone).find(".questionId").val(json.data[i].questionId);
                    $(clone).find(".sellerName").val(json.data[i].sellerName);
                    $(clone).removeClass('hide');
                    $(clone).removeClass('template-qna-mgmt-div');
                    ar.push(clone);
                }
    		
                for (i = 0 ; i < ar.length; i = i + 1) {
                    $('#qnaMainDiv .content').append(ar[i].html());
                }
    		
                noOfQuestions = ar.length;

                if (o.isOwnAd  === "true" && json.data.length === 0) {
                    $('#qnaMainDiv .content').append("<div class='noAdMsg'>There are currently no questions about this ad</div>");
                }
    		
                ar.length = 0; // clear array 
    		
                for (i = noOfQuestions; i < json.data.length; i = i + 1) {
                    clone = $('.template-qna-answer-div').clone();
                    
                    $(clone).find('.question-text').text('' + json.data[i].questionText + '');
                    $(clone).find('.post-question-text').html('&nbsp;-&nbsp;'
                    		+ ((json.data[i].buyerName === "") ? "interested user" : escapeHTML(json.data[i].buyerName))
                    );
                    
                    $(clone).find('.answer-text').text(json.data[i].answerText);
                    if(json.data[i].answerType === "SELLER_ANSWER_PRIVATE") {
	                    $(clone).find('.post-answer-text').html('&nbsp;(private)');
                    }
                    $(clone).removeClass('hide');
                    $(clone).removeClass('template-qna-answer-div');
                    ar.push(clone);
                }

                for (i = 0 ; i < ar.length; i = i + 1) {
                    $('#qnaMainDiv .content').append(ar[i].html());
                }
                
                noOfAnswers = json.data.length - noOfQuestions; 
                
                if (o.isOwnAd  === "true" || noOfAnswers > 0 ) {
                    $("#qnaMainDiv").removeClass('undisplay');
                }
                
                $(".qnaAnswer").val('');
            }
        });
    };


    $('body').delegate('#qnaMainDiv .answerBtn', 'click', {
        o: o
    }, function (e) {
        e.preventDefault();
        // Will find the first form that is a parent of the answer button
        var form = $(this).parents('form:first');
        qnaAnswer = form.find('textarea[name=answerText]'),
        qnaAnswerLength = $.trim(qnaAnswer.val()).length;
        var ansEnum = {
            "EMPTY": -1,
            "LESS_THAN_FIVE": 5,
            "GREATER_THAN_FOUR_HUNDRED": 400
        };
        var ans = ((qnaAnswerLength === 0) ?  -1 : 0) + ((qnaAnswerLength > 0 && qnaAnswerLength < 6) ?  5 : 0) + ((qnaAnswerLength > 400) ?  400 : 0);
        switch (ans) {
            case  ansEnum.EMPTY:
                form.find('.field-error-message').html('Please enter your answer.');
                qnaAnswer.addClass('field-error');
                break;
            case ansEnum.LESS_THAN_FIVE:
                form.find('.field-error-message').html('Your answer must be at least 5 characters long.');
                qnaAnswer.addClass('field-error');
                break;
            case ansEnum.GREATER_THAN_FOUR_HUNDRED:
                form.find('.field-error-message').html('Your answer must be less than 400 characters long.');
                qnaAnswer.addClass('field-error');
                break;
            default:
                $.post(qnaUrl, form.serialize(), function (result) { 
                    if (result.success) {
                        o.clear = true;
                        refresh(o);
                    } else {
                    	alert('You have already answered the question.');
                        o.clear = true;
                        refresh(o);
                    }
                });
        }
    });

    $('body').delegate('#qnaMainDiv .deleteQuestion', 'click', {
        o: o
    }, function (e) {
        e.preventDefault();
        var questionId = $(this).parents('form:first').find('input[name=questionId]').val();
        $.ajax({
            type: "GET",
            url: qnaUrl,
            data : "questionId=" + questionId,
            dataType: "json",
            success: function (json) {
                o.clear = true;
                refresh(o);
            }
        });
    });

    window.onload =  function () {
		 if (this.location.hash !== ''){
		 	this.location.href = this.location.hash;
		 }	
	  };

    refresh(o);
};


function escapeHTML(str) {
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}














