﻿var TRAILS = {
	objects: new Object(),
	settings: {
		time: new Date(),
		domain: document.domain,
		scripts: new Array(),
		advertisement: new Object(),
		trackingPixels: new Array()
	}
};
// Static read-only base class properties
Object.type			= typeof Object();
Boolean.type		= typeof Boolean();
Function.type		= typeof Function();
String.type			= typeof String();
Number.type			= typeof Number();
RegExp.type			= typeof RegExp(/\\/);
Array.type			= typeof Array();
Function.empty		= new Function();
String.empty		= new String();
String.whiteSpace	= ' ';
/* Cookie plugin * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses. */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options=$.extend({},options);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();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{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]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};
/* Viewport - jQuery selectors for finding elements in viewport * Copyright (c) 2008-2009 Mika Tuupola * Licensed under the MIT license * http://www.appelsiini.net/projects/viewport */
eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(3($){$.e=3(1,2){c 8=$(6).l()+$(6).o();4 8<=$(1).b().9-2.5};$.f=3(1,2){c 9=$(6).o();4 9>=$(1).b().9+$(1).l()-2.5};$.g=3(1,2){c 8=$(6).k()+$(6).h();4 8<=$(1).b().7-2.5};$.d=3(1,2){c 7=$(6).h();4 7>=$(1).b().7+$(1).k()-2.5};$.j=3(1,2){4!$.g(1,2)&&!$.d(1,2)&&!$.e(1,2)&&!$.f(1,2)};$.r($.s[\':\'],{"y-n-8":3(a,i,m){4 $.e(a,{5:0})},"u-n-9":3(a,i,m){4 $.f(a,{5:0})},"7-p-q":3(a,i,m){4 $.d(a,{5:0})},"w-p-q":3(a,i,m){4 $.g(a,{5:0})},"t-x":3(a,i,m){4 $.j(a,{5:0})}})})(v);',35,35,'|element|settings|function|return|threshold|window|left|fold|top||offset|var|leftofscreen|belowthefold|abovethetop|rightofscreen|scrollLeft||inviewport|width|height||the|scrollTop|of|screen|extend|expr|in|above|jQuery|right|viewport|below'.split('|'),0,{}))
/* SWFObject v1.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/ * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('5(18 8=="1s"){7 8=j Q()}5(18 8.L=="1s"){8.L=j Q()}5(18 8.15=="1s"){8.15=j Q()}8.K=g(1m,p,w,h,1n,c,1p,1o,1v,1w,1u){5(!u.2b||!u.25){f}4.1N=1u?1u:"2j";4.1W=8.L.1t(4.1N);4.1A=j Q();4.S=j Q();4.1l=j 14();5(1m){4.k("1j",1m)}5(p){4.k("p",p)}5(w){4.k("P",w)}5(h){4.k("N",h)}5(1n){4.k("I",j 8.v(1n.2k().W(".")))}4.T=8.15.1Y(4.d("I"),1p);5(c){4.1E("2n",c)}7 q=1o?1o:"2m";4.1E("2l",q);4.k("1H",1p);4.k("M",G);7 1M=(1v)?1v:2s.16;4.k("28",1M);4.k("11","");5(1w){4.k("11",1w)}};8.K.19={k:g(1L,1J){4.1l[1L]=1J},d:g(1K){f 4.1l[1K]},1E:g(1I,1P){4.1A[1I]=1P},1i:g(){f 4.1A},O:g(1U,1T){4.S[1U]=1T},2a:g(1S){f 4.S[1S]},1Q:g(){f 4.S},1c:g(){7 1a=j 14();7 m;7 1C=4.1Q();V(m 1e 1C){1a.1r(m+"="+1C[m])}f 1a},1Z:g(){7 l="";5(E.1h&&E.1g&&E.1g.y){5(4.d("M")){4.O("1R","2h")}l="<2u 2i=\\"2g/x-2d-2o\\" 2B=\\""+4.d("1j")+"\\" P=\\""+4.d("P")+"\\" N=\\""+4.d("N")+"\\"";l+=" p=\\""+4.d("p")+"\\" X=\\""+4.d("p")+"\\" ";7 1b=4.1i();V(7 m 1e 1b){l+=[m]+"=\\""+1b[m]+"\\" "}7 1d=4.1c().1V("&");5(1d.y>0){l+="1F=\\""+1d+"\\""}l+="/>"}1x{5(4.d("M")){4.O("1R","2G")}l="<1G p=\\""+4.d("p")+"\\" 2F=\\"2y:2v-2z-2A-2D-2P\\" P=\\""+4.d("P")+"\\" N=\\""+4.d("N")+"\\">";l+="<1y X=\\"2E\\" 1B=\\""+4.d("1j")+"\\" />";7 1k=4.1i();V(7 m 1e 1k){l+="<1y X=\\""+m+"\\" 1B=\\""+1k[m]+"\\" />"}7 1D=4.1c().1V("&");5(1D.y>0){l+="<1y X=\\"1F\\" 1B=\\""+1D+"\\" />"}l+="</1G>"}f l},2I:g(13){5(4.d("1H")){7 1O=j 8.v([6,0,2f]);5(4.T.17(1O)&&!4.T.17(4.d("I"))){4.k("M",F);4.O("2J",2H(4.d("28")));u.1z=u.1z.2K(0,2L)+" - 1X 2O 2w";4.O("2C",u.1z)}}5(4.1W||4.d("M")||4.T.17(4.d("I"))){7 n=(18 13=="2x")?u.25(13):13;n.2N=4.1Z();f F}1x{5(4.d("11")!=""){u.16.1f(4.d("11"))}}f G}};8.15.1Y=g(B,24){7 t=j 8.v([0,0,0]);5(E.1h&&E.1g.y){7 x=E.1h["2M 1X"];5(x&&x.22){t=j 8.v(x.22.1f(/([a-z]|[A-Z]|\\s)+/,"").1f(/(\\s+r|\\s+b[0-9]+)/,".").W("."))}}1x{21{7 R=j 23("U.U");V(7 i=3;R!=1q;i++){R=j 23("U.U."+i);t=j 8.v([i,0,0])}}20(e){}5(B&&t.o>B.o){f t}5(!B||((B.C!=0||B.Y!=0)&&t.o==B.o)||t.o!=6||24){21{t=j 8.v(R.2t("$I").W(" ")[1].W(","))}20(e){}}}f t};8.v=g(H){4.o=10(H[0])!=1q?10(H[0]):0;4.C=10(H[1])||0;4.Y=10(H[2])||0};8.v.19.17=g(D){5(4.o<D.o){f G}5(4.o>D.o){f F}5(4.C<D.C){f G}5(4.C>D.C){f F}5(4.Y<D.Y){f G}f F};8.L={1t:g(26){7 q=u.16.2r||u.16.2p;5(q){7 J=q.12(26+"=");7 29=(q.12("&",J)>-1)?q.12("&",J):q.y;5(q.y>1&&J>-1){f q.2q(q.12("=",J)+1,29)}}f""}};5(14.19.1r==1q){14.19.1r=g(27){4[4.y]=27;f 4.y}}7 2c=8.L.1t;7 2e=8.K;7 K=8.K;',62,176,'||||this|if||var|deconcept|||||getAttribute||return|function|||new|setAttribute|_19|key||major|id||||_25|document|PlayerVersion|||length|||_23|minor|fv|navigator|true|false|_29|version|_2d|SWFObject|util|doExpressInstall|height|addVariable|width|Object|axo|variables|installedVer|ShockwaveFlash|for|split|name|rev||parseInt|redirectUrl|indexOf|_20|Array|SWFObjectUtil|location|versionIsValid|typeof|prototype|_16|_1a|getVariablePairs|_1c|in|replace|mimeTypes|plugins|getParams|swf|_1d|attributes|_1|_5|_8|_7|null|push|undefined|getRequestParameter|_b|_9|_a|else|param|title|params|value|_18|_1f|addParam|flashvars|object|useExpressInstall|_11|_f|_10|_e|_d|DETECT_KEY|_21|_12|getVariables|MMplayerType|_15|_14|_13|join|skipDetect|Flash|getPlayerVersion|getSWFHTML|catch|try|description|ActiveXObject|_24|getElementById|_2b|_2f|xiRedirectUrl|_2e|getVariable|createElement|getQueryParamValue|shockwave|FlashObject|65|application|PlugIn|type|detectflash|toString|quality|high|bgcolor|flash|hash|substring|search|window|GetVariable|embed|D27CDB6E|Installation|string|clsid|AE6D|11cf|src|MMdoctitle|96B8|movie|classid|ActiveX|escape|write|MMredirectURL|slice|47|Shockwave|innerHTML|Player|444553540000'.split('|'),0,{}))
// String methods
if(!String.strip)
String.strip = function(){
	var _string = arguments[0];
	
	if(typeof _string !== String.type)
		return _string;
	
	if(arguments.length != 0)
		for(var i = 1, n = arguments.length; i !== n; i++)
			while(_string.indexOf(arguments[i]) !== -1){ _string = _string.replace(arguments[i], String.empty) };
	
	return _string;
};
if(!String.format)
String.format = function(){
	if(arguments.length == 0)
		return null;
	
	var _string = arguments[0];
		
	for(var i = 1, n = arguments.length; i < n; i++)		
		_string = _string.replace(RegExp('\\{' + (i-1) + '\\}','gm'), arguments[i]);
	
	return _string;
};
if(!String.concat)
String.concat = function(){
	return Array.prototype.join.call(arguments, String.empty);
};
if(!String.toRegExp)
String.toRegExp = function(pattern, flags){
	return new RegExp(pattern.replace(/[\[\]\\{}()+*?.$^|]/g, function(m){return '\\'+m;}), flags);
};
if(!String.isNullOrEmpty)
String.isNullOrEmpty = function(value){
	return typeof value === String.type && value.length ? value.trim().length == 0 : true;
};
if(!String.prototype.trim)
String.prototype.trim = function(){
	return this.replace(RegExp.filter.whitespace, String.empty);
};
if(!String.prototype.toHex)
String.prototype.toHex = function(){
	return parseInt(this,10).toHex();
};
// RegExp methods
RegExp.filter = {
	whitespace: /^\s+|\s+$/g,
	nonAlphaNumeric: /[^0-9a-zA-Z]/g,
	nonNumeric: /[^0-9]/g,
	nonAlpha: /[^a-zA-Z]/g
};
RegExp.match = {
	alphaNumeric : /^[0-9a-zA-Z]+$/,
	alphaNumericWhitespace : /^[0-9a-zA-Z\s]+$/,
	url: /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ // needs review
};
// Array methods
if(!Array.prototype.contains)
Array.prototype.contains = function(value){
	for (var i = 0, n = this.length; i < n; i++)
		if(this[i] === value)
			return true;
			
	return false;
};
if(!Array.prototype.remove)
Array.prototype.remove = function(from, to){
	if(this.length === 0) return;

	var rest = this.slice((to || from) + 1 || this.length);
	
	this.length = from < 0 ? this.length + from : from;

	return this.push.apply(this, rest);
};
if(!Array.prototype.indexOf) // ECMA-262 standard implementation
Array.prototype.indexOf = function(value, from){
	var length = this.length >> 0;
	var from = Number(from) || 0;

	from = from < 0
		? Math.ceil(from)
		: Math.floor(from);

	if(from < 0)
		from += length;

	for(; from < length; from++)
		if (from in this && this[from] === value)
			return from;

	return -1;
};
// Boolean methods
if(!Boolean.parse)
Boolean.parse = function(value){
	switch(typeof value){
		case Number.type:
			return value > 0;
		case Function.type:
			return value() || false;
		case Object.type:
			return value && value.length ? value.length > 0 : false;
		case String.type:
			var _string = value.trim().toLowerCase();

			return _string.length
				? _string == 'true' || _string == 'on' || _string == 'success' || (isNaN(_string) ? false : parseInt(_string,10) > 0)
				: false;
	}

	return false;
};
// jQuery properties
jQuery.browser.msie6 = jQuery.browser.msie && jQuery.browser.version < 7;
// jQuery plugins
jQuery.each(['lt','gt'], function(i, n){
	jQuery.fn[n] = function(num, fn){
		return this.filter(':' + n + '(' + num + ')', fn);
	};
});
jQuery.fn.disableTextSelect = function(){
	return this.each(function(){
		jQuery(this).bind(jQuery.browser.msie ? 'selectstart' : 'mousedown',
			function(){ return false; }
		);
	});
};
jQuery.fn.hoverClass = function(className){
	return String.isNullOrEmpty(className) ? this : this.each(function(){
		jQuery(this).hover( 
			function(){ jQuery(this).addClass(className); },
			function(){ jQuery(this).removeClass(className); }
		);
	});
};
TRAILS.utils = {
	applyAlphaImageFilter: function(selector, src){
		jQuery(selector).each(function applyFilter(index, element){
			if(!src){
				src = jQuery(element).css('backgroundImage');
				src = src.substring(4, src.length-1);
			}
			
			element.style.background = String.empty;
			element.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + src + ',sizingMethod=scale)';
		});
	},
	removeLinkByHref: function(href, maxTrys){
		(function remove(){
			for(var links = document.getElementsByTagName('link'), index = 0, length = links.length; index < length; index++)
				if(links[index].href.indexOf(href) !== -1)
					return jQuery(links[index]).attr('href','#').remove();
			
			if(--maxTrys !== 0)
				setTimeout(remove, 1000);
		})();
	},
	cleanObject: function(object){
		for(var property in object)
			if(typeof object[property] === 'undefined')
				delete object[property];
				
		return object;
	},
	getViewportDimensions: function(){
		if(typeof window.innerWidth === Number.type)
			return { width: window.innerWidth, height: window.innerHeight };
		else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
			return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
		else if(document.body && (document.body.clientWidth || document.body.clientHeight))
			return { width: document.body.clientWidth, height: document.body.clientHeight };

		return { width: 0, height: 0 };
	},
	getElementPadding: function(e){
		var padding = 0;
		
		jQuery(e).each(function(){
			var $element = jQuery(this);

			padding += parseInt($element.css('padding-left'), 10) || 0;
			padding += parseInt($element.css('padding-right'), 10) || 0;
		});
		
		return padding;
	},
	getElementBorderWidth: function(e){
		var borderWidth = 0;
		
		jQuery(e).each(function(){
			var $element = jQuery(this);
			var borderRightWidth = $element.css('border-right-width');
			var borderLeftWidth = $element.css('border-left-width');
			
			borderWidth += parseInt(borderRightWidth, 10)
				|| borderRightWidth == 'medium' ? 1 : 0;
			borderWidth += parseInt(borderLeftWidth, 10)
				|| borderLeftWidth == 'medium' ? 1 : 0;
		});
		
		return borderWidth;
	},
	addTrackingPixel: function(url){
		var trackingPixelInformation = {
			time: new Date() - TRAILS.settings.time,
			url: url	
		};
		
		if(document.images){
			trackingPixelInformation.element = new Image(1, 1);
			trackingPixelInformation.element.src = url;
			trackingPixelInformation.type = 'preload';
		}
		else{
			trackingPixelInformation.element = jQuery('<img width="1" height="1" src="' + url + '" alt="zig" />').prependTo('body')[0];
			trackingPixelInformation.type = 'prepend';
		}
		
		TRAILS.settings.trackingPixels.push(trackingPixelInformation);
	},
	abortXmlHttpRequest: function(xhr){
		if(xhr === null) return;
			
		try{ xhr.status; }
		catch(error){
			xhr.abort();
			jQuery.active--;
			jQuery.event.trigger('ajaxStop');	
		}
		finally { xhr = null; }
	},
	deferScript: function(url, fn){
		jQuery(window).load(function getScript(){
			jQuery.getScript(url, function(script){
				TRAILS.settings.scripts.push(url);
				(fn || Function.empty)(script);
			});
		});
	},
	importScript: function(url, fn){
		return jQuery.getScript(url, function(script){
			TRAILS.settings.scripts.push(url);
			(fn || Function.empty)(script);
		});
	},
	importSymbols: (function(){
		var self = this;
		var symbolCallerDictionary = new Object();

		function stackSymbolCaller(symbolName, fn){
			console.warn('adding symbol name to import queue >> ', symbolName);

			if(!symbolCallerDictionary[symbolName])
				symbolCallerDictionary[symbolName] = new Array();

			symbolCallerDictionary[symbolName].push(fn);
		}
		function dumpSymbolTree(symbolNameTree, indexOfUnresolvedSymbol, fn){
			console.error('unable to resolve symbol >> ', symbolNameTree.slice(0, indexOfUnresolvedSymbol).toString().replace(/,/g, '.'));
			stackSymbolCaller(symbolNameTree.slice(0, indexOfUnresolvedSymbol).toString().replace(/,/g, '.'), fn);

			for(var i = indexOfUnresolvedSymbol, l = symbolNameTree.length - 1, symbolName = symbolNameTree[indexOfUnresolvedSymbol - 1]; i <= l; i++)
				stackSymbolCaller(symbolName += '.' + symbolNameTree[i], fn);
		}
		function getIndexOfUnresolvedSymbol(symbolNameTree){		
			for(var i = 1, l = symbolNameTree.length, symbol = window[symbolNameTree[0]]; i <= l; i++){
				console.info('resolving symbol >> ', symbolNameTree.slice(0, i).toString().replace(/,/g, '.'));

				if(typeof symbol == 'undefined')
					return i;

				symbol = symbol[symbolNameTree[i]];			
			}
			
			return -1;
		}
		function processSymbolCaller(fn, symbolName, xhr){
			setTimeout(function(){
				console.info('processing symbol "' + symbolName + '" caller')
			
				if(getIndexOfUnresolvedSymbol(symbolName.split('.')) == -1)
					fn.resolvedSymbols.push(symbolName);
				if(fn.resolvedSymbols.length == fn.requiredSymbols.length)
					fn();
			}, 0);
		}

		return function(fn, symbolNames){
			fn.requiredSymbols = symbolNames;
			fn.resolvedSymbols = new Array();

			for(var i = 0, l = symbolNames.length; i < l; i++){
				console.info('parsing import statement >> "' + symbolNames[i] + '"');

				var symbolNameTree = symbolNames[i].split('.');
				var indexOfUnresolvedSymbol = getIndexOfUnresolvedSymbol(symbolNameTree);

				if(indexOfUnresolvedSymbol == -1)
					processSymbolCaller(fn, symbolNames[i]);
				else	
					dumpSymbolTree(symbolNameTree, indexOfUnresolvedSymbol, fn);
			}
			for(var symbolName in symbolCallerDictionary){
				var xhr = TRAILS.utils.importScript('/ui/scripts/' + symbolName + '.js', function(){
					console.info('resolved symbol "' + symbolName + '"');

					for(var i = 0, symbolCallers = symbolCallerDictionary[symbolName], l = symbolCallers.length; i < l; i++)
						processSymbolCaller(symbolCallers[i], symbolName, xhr);
				});
			}
		};
	})()
};
TRAILS.utils.QuerystringParser = function(uri){
	var self = this;
	var query = new Object();
	var splitUri = (uri || window.location.toString()).trim().replace(/\+/g,' ').split('?');

	self.path = splitUri[0];

	self.contains = function(field){
		return !String.isNullOrEmpty(query[field]);
	};
	self.deleteField = function(field){
		delete query[field];
		return self;
	};
	self.setField = function(field, value){			
		return query[field] = value.toString();
	};
	self.getField = function(field){
		return query[field];
	};
	self.toString = function(){
		var fieldValuePairs = new Array();
		
		for(var field in query)
			fieldValuePairs.push(field + '=' + query[field]);

		return self.path + '?' + fieldValuePairs.toString().replace(/,/g,'&');
	};
	self.dispose = function(){
		for(var property in self)
			delete self[property];
		
		return self = null;
	};

	(function(){
		if(!splitUri[1])
			return;
			
		var fieldValuePairs = splitUri[1].split('&');
		
		if(!fieldValuePairs.length)
			return;
		
		for(var index = 0, length = fieldValuePairs.length; index < length; index++){
			var fieldValuePair = fieldValuePairs[index].split('=');

			query[decodeURIComponent(fieldValuePair[0])] = fieldValuePair.length === 2
				? decodeURIComponent(fieldValuePair[1])
				: String.empty;
		}
	})();
};
TRAILS.utils.AddThis = (function(){
	var self = new Object();
	var defaults = {
		username					: 'dmseo',
		ui_cobrand					: 'Trails.com',
		ui_header_color				: "#4C4C4C",
		ui_header_background		: "#F2F2F2",
		ui_delay					: 200,
		ui_click					: false,
		ui_use_addressbook			: true,
		services_compact			: 'facebook, google, twitter, delicious, stumbleupon, friendfeed, mixx, netvibes, reddit, favorites, more'
	};
	
	self.scriptUrl = (document.location.protocol == 'http:' ? 'http://s7' : 'https://secure') + '.addthis.com/js/250/addthis_widget.js';
	
	self.configure = function(configuration){		
		window.addthis_config = jQuery.extend(new Object(), defaults, configuration);
		
		return self;
	};

	return self.configure();
})();
TRAILS.utils.RightMediaAd = function($targetElement, url, options){
	var self = this;
	var timeoutId = null;
	var settings = jQuery.extend(new Object(), self.defaults, options);
	var querystring = new TRAILS.utils.QuerystringParser(url);
	var hasLoaded = false;

	function timeout(fn){
		clearTimeout(timeoutId);
		
		timeoutId = fn
			? setTimeout(fn, settings.timeout * 1000)
			: null;
	}
	function createAdUnit($adElement, fn){
		var start = new Date();
		
		timeout(function(){
			self.timings.push(null)
			createAdUnit($adElement, fn);
		});
		$adElement.load(function(event){
			timeout(null);
			//self.adUnitManager.restoreHistory();
			self.timings.push((new Date(event.timeStamp) - start) / 1000);
			$targetElement.removeClass(settings.loadingClass);
			$adElement[settings.animation.method](settings.animation.duration, fn || settings.callback);
		}).appendTo($targetElement);
	}

	self.url = querystring.toString();
	self.element = null;
	self.timings = new Array();
	self.section = parseInt(querystring.getField('section'), 10)
		|| querystring.setField('section', settings.section);
	self.dimensions = settings.dimensions
		|| (function(d){ return { width: parseInt(d[0], 10), height: parseInt(d[1], 10) }; })(querystring.getField('ad_size').split('x'));

	self.createAdUnit = function(fn){
		var $adElement = jQuery(String.format(settings.template, self.url, self.dimensions.width, self.dimensions.height)).hide();

		if(self.element){
			jQuery(self.element).remove();
			self.adUnitManager.count--;
		}
			
		$targetElement.addClass(settings.loadingClass);
		
		self.element = $adElement[0];
		
		self.adUnitManager.count++;
		
		if(hasLoaded)
			createAdUnit($adElement, fn);
		else
			jQuery(function(){ createAdUnit($adElement, fn, hasLoaded = true); });

		return self;
	};
	self.targetAdUnit = function(selector){
		return selector
			? $targetElement = jQuery(targetElement)
			: $targetElement;
	};
	self.removeAdUnit = function(){
		timeout(null);
		
		if(self.element){
			jQuery(self.element).remove();
			self.adUnitManager.count--;
			
			self.element = null;
		}
		
		$targetElement.removeClass(settings.loadingClass);

		return self;
	};

	self.createAdUnit();
};
TRAILS.utils.RightMediaAd.prototype.adUnitManager = (function(){
	var url = document.referrer;

	return {
		count: 0,
		restoreHistory: function(){
			if(--this.count > 0) return;
			
			// implement restoreHistory method
		}
	}
})();
TRAILS.utils.RightMediaAd.prototype.defaults = {
	template: '<iframe frameborder="0" marginwidth="0" marginheight="0" scrolling="no" src="{0}" width="{1}" height="{2}"></iframe>',
	timeout: 30,
	section: 577146,
	callback: null,
	dimensions: null,
	loadingClass: 'loading',
	animation: { method: 'slideDown', duration: 400 }
};
TRAILS.utils.DropDownMenu = function($menuElement, $tabElements, options){
	var self = this;
	var timeoutId = null;
	var settings = jQuery.extend({  }, self.defaults, options);
	var menu = new Object();

	function isOutOfBounds($element){
		return $element.offset().left + $element.width()
			> settings.containment.offset().left + settings.containment.width();
	}
	function buildMenu($tabElement){
		var $menuContent = jQuery('.body .content', $tabElement);
		var $menuTab = jQuery('.head .content', $tabElement);
		
		if($menuContent.length == 0 || $menuTab.length == 0) return;
		
		menu.content.html($menuContent.clone(false));
		menu.tab.html($menuTab.clone(false));
	
		var menuHeadWidth = $tabElement.width()
			+ menu.borderWidth
			+ menu.padding;
		
		$menuElement.width(menuHeadWidth);
		menu.body.css('left', null);
		$menuElement.fadeIn(settings.animation.fadeIn);
		menu.body.width(settings.maxWidth);
		
		var menuBodyWidth = jQuery('*', menu.content).width()
			+ menu.borderWidth
			+ TRAILS.utils.getElementPadding(menu.content);
		
		menuBodyWidth = menuBodyWidth > settings.maxWidth
			? settings.maxWidth
			: menuBodyWidth;
		
		menu.body.width(menuBodyWidth);
		
		var position = $tabElement.position();
		
		position.top += Math.floor(menu.marginTop) + (menu.borderWidth / 2);
		
		$menuElement.css(position);
		
		var isOutOfRightBound = isOutOfBounds(menu.body);
		
		if(isOutOfRightBound)
			menu.body.css('left', menu.body.position().left - menuBodyWidth + menuHeadWidth);
			
		menu.body.removeClass('left right');
		menu.body.addClass(isOutOfRightBound ? 'right' : 'left');
	}

	self.open = function(e){
		clearTimeout(timeoutId);
		
		var $tabElement = typeof e === Number.type
			? $tabElements.eq(e)
			: jQuery(e.currentTarget || e);
		
		buildMenu($tabElement);

		return self;
	};
	self.close = function(hideMenu){
		clearTimeout(timeoutId);
		timeoutId = setTimeout(function(){
			$menuElement.fadeOut(settings.animation.fadeOut);
		}, settings.animation.delay);
		
		return self;
	};
	
	settings.containment = settings.containment
		? jQuery(settings.containment)
		: $tabElements.parent();
	menu.body = $menuElement.children('.body');
	menu.head = $menuElement.children('.head');
	menu.content = menu.body.children('.content');
	menu.tab = menu.head.children('.content');
	menu.borderWidth = TRAILS.utils.getElementBorderWidth(menu.content);
	menu.marginTop = (parseInt($tabElements.eq(1).css('margin-top'), 10) || 0) / 2;
	menu.padding = TRAILS.utils.getElementPadding($tabElements.eq(1));
	menu.maxHeight = $tabElements.gt(0).hide().parent().height();
	menu.maxWidth = settings.containment.width();
	menu.width = 0;

	$tabElements.gt(0).show().each(function(i){
		if((menu.width += jQuery(this).width()) < menu.maxWidth)
			return true;
		
		if(!jQuery.support.cssFloat) i--;
		
		var $moreElement = $tabElements.eq(0).clone(false).insertBefore($tabElements.eq(i--));
		var $overflowElements = $tabElements.gt(i).hide();
		
		$moreElement.find('.title').html('More');
		$moreElement.find('.body .content').html($overflowElements.find('li'));
		$overflowElements.remove();
		
		$tabElements = $tabElements.filter(':visible').add($moreElement);
		
		return false;
	});
	
	$tabElements.bind('mouseenter.DropDownMenu', self.open);
	$menuElement.bind('mouseenter.DropDownMenu', function(){ clearTimeout(timeoutId); });
	$tabElements.bind('mouseleave.DropDownMenu', self.close);
	$menuElement.bind('mouseleave.DropDownMenu', self.close);
}
TRAILS.utils.DropDownMenu.prototype.defaults = {
	maxWidth: 660,
	containment: null,
	animation: { delay: 400, fadeIn: 200, fadeOut: 100 }
};