( function ( ) {

	var flashShimFlag = ""; //global var to trigger showing/hiding or covering a flash ad in the header so it doesnt cover the login box.
	
	function checkLogin ( ) {

		if ( link = $('openLoginLink') ) {
			var loginForm = $('loginForm');
			
			var response = function ( ) {
			
				confirmSlide.slideIn();
				( function ( ) {
					confirmSlide.slideOut();
					slide.slideIn();
					flashShimFlag = "confirm";
				} ).delay ( 5000 );
			}// response

			var forgotField = new Element ( "input", {
				type : 'text',
				'class' : 'text',
				size : 40,
				styles : {
					width : 225
				}
			} );

			var forgotForm = new Element ( "div", {
				styles : {
					display : 'none',
					 paddingTop : 10
				}
			} ).adopt (
				new Element ( "form", {
					events : {
						submit : function ( e ) {
							forgotField.blur();
							e = new Event ( e );
							e.stop();
							
							flashShimFlag = "forgotPsw";
							//alert(flashShimFlag);				
							
							if ( ( email = forgotField.value.replace(/(^\s+|\s+$)/) ).length ) {
								forgotSlide.slideOut();
								forgotField.value = "";
								API.requestPassword ( email, {
									onComplete : response,
									onError : response
								} )
							}
						}
					}
				} ).adopt (
					new Element ( "p", {
						'class' : "full",
						'id'	: "forgotEmail"
					} ).adopt (
						forgotField
					).adopt (
						new Element ( "span", {'class' : "buttonWrapper"}).adopt (
							new Element ( "input", {
								type : 'submit',
								'class' : 'btn submit',
								value : 'Send'
							} )
						)
					)
				).adopt (
					new Element ( "p", { 'class' : 'enterEmail' } ).setText ( "Enter your email... we'll send you a new password" )
				)
			);
			loginForm.getParent().adopt(forgotForm);
			var forgotSlide = new Fx.Slide ( forgotForm ).hide();
			forgotForm.setStyle ( 'display', 'block' );
			forgotForm.setStyle ( 'margin-top', -1 * forgotForm.offsetHeight );

			var forgotConfirm = new Element ( "div", {
				styles : {
					display : 'none',
					paddingTop : 10
				}
			} ).adopt (
				new Element ( "form" ).adopt (
					new Element ( "p", {
						'class' : "enterEmail"
					} ).setText ( "Thanks... check your email for your new password!" )
				)
			);
			loginForm.getParent().adopt(forgotConfirm);
			var confirmSlide = new Fx.Slide ( forgotConfirm ).hide();
			forgotConfirm.setStyle ( 'display', 'block' );
			forgotConfirm.setStyle ( 'margin-top', -1 * forgotConfirm.offsetHeight );
			var slide = new Fx.Slide( loginForm ).hide();
			loginForm.setStyle ( 'display', 'block' );
			loginForm.setStyle ( 'margin-top', -1 * loginForm.offsetHeight );

			var forgotLink = new Element( "a" , {
				events : {
					click : function ( e ) {
						e = new Event ( e );
						e.stop();
						slide.slideOut();
						forgotSlide.slideIn();
						flashShimFlag = "forgotPsw";
					}
				},
				'id' : "forgotLink", // just to make it easy to check the class - again to set up some flag...
				href : "#"}).appendText( "Forgot Your Password?" );

			$E('p.full', loginForm).adopt ( forgotLink );

			if ( $E('p.errorMsg', loginForm) ) {
				// if there was an error logging in...
				slide.slideIn.delay(1000,slide);
			}
			
			
			
			var newLink = new Element ( "a", {
				events : {
					click : function ( e ) {
						e = new Event( e );
						forgotSlide.slideOut();
						slide.toggle();
						e.stop();
						toggleIFrameShim();
						flashShimFlag = "";
					}
				},
				href : "#"
			} ).appendText ( link.getText() );
			link.replaceWith ( newLink );
		}
	}
	

// hide flash ad - firefox/opera
//  should check if wmode is set, then simply swap zindexes so we can show the ad.
// revisit when we have flash ad w wmode set
function toggleFlashLeaderboard() {
// check if there's a leaderboard and if the ad inside is flash
	var leaderboard = $E("#headerWrapper .leaderboard");
	var flashAds = $$('#header .leaderboard embed, #header .leaderboard object');

	flashAds.each ( function () {
		if(flashShimFlag != "forgotPsw"){
			(function(){leaderboard.style.display != "none"? leaderboard.style.display = "none" : leaderboard.style.display = "block";}).delay(220);
		}
		else {
			(function(){leaderboard.style.display = "none";}).delay ( 220 );
		}
	});
}

function toggleIFrameShim(){
	// in Firefox/Opera, only way to show above the flash movie is to set wmode="transparent". 
	// if wmode is not set, hide the ad
		if (!window.ie) {
			toggleFlashLeaderboard();
		}
		else {
		// in IE, do the iframe shim thing. Shim is inlined in the page because adding to DOM is way to sluggish in IE6
			if (document.getElementById("flashShim")) {
				var flashShim = $("flashShim");
				if(flashShimFlag != "forgotPsw"){
							(function(){flashShim.hasClass("hidden")?flashShim.removeClass("hidden"):flashShim.addClass("hidden");}).delay(250);
					}
					else {
							(function(){flashShim.removeClass("hidden");}).delay(250);
					}
				}
		}
}






	
	function resetTooltips ( ) {
		var tt_tooltip = null;
		var get_tooltip_html = function(str) {
		return   '<div class="tooltip-tip" style="position:absolute;z-index:100">'
			+ '<div class="tooltip-text">'
			+		'<span class="inner">'+str+'</span>'
			+	'</div>'
			+ '</div>';
		}
			
		var translateTooltip = function ( tt ) {
			// turns html title values into more useful tooltips...
			// > [*Title:* Something; *Another Title:* Something else; More somethings]
			// ... becomes ...
			// > <span class="pair"><strong>Something:</strong> Something</span><br />
			// > <span class="pair"><strong>Another Title:</strong> Something else</span><br />
			// > More somethings
			if ( tt.length < 40 && tt.indexOf(':') < 0 && tt.indexOf(';') < 0 ) {
				tt = "[" + tt + "]";
			}
			return tt
				.replace ( /;\s+/g, ';\n' )
				.replace ( /(^|\n)([^:]+:[^;]+)(?:;\s+|$)/gm, '<span class="pair">$2</span>; ' )
				.replace ( /\[([^\]]+)\]/gm, '<span class="pair">$1</span>' ) 
				.replace ( /\*([^\s\*]+(\s+[^\s\*]+)*)\*/g, '<strong>$1</strong>' )
				.replace ( /;\s*/g, '\n' )
				.replace ( /(^\s+|\s+$)/g, '' )
				.replace ( /\n+/g, '<br />\n' );
		}
		var makeTooltip = function ( owner ) {
//			"
//			
//			
//			"
			var el = new Element ( "div", {
				'class' : 'tooltip-tip',
				styles : {
					opacity : 0,
					position : 'absolute',
					zIndex : 100
				}
			} ).adopt (
				new Element ( "div", {
					'class' : 'tooltip-text'
				} ).setHTML ( '<span class="inner">' + owner.tooltipValue + '</span>' )
			);
			
			var tt = new Fx.Style ( el, 'opacity', {
				duration : 250,
				wait : false,
				onStart : function ( ) {
					var pos = owner.getCoordinates();
					el.injectInside ( document.body );
					el.setStyles ( {
						left : pos.left + pos.width / 2,
						top : pos.top
					} );
				},
				onComplete : function ( ) {
					if ( el.getStyle ( 'opacity' ) < 0.1 ) {
						el.remove();
						owner.tooltip = null;
						delete tt;
					}
				}
			} ).set ( 0 );

			el.show = function ( ) {
				tt.start ( 0.8 );
				document.title = "Showing tooltip: " + owner.tooltipValue;
			}
			el.hide = function ( ) {
				tt.start ( 0 );
			}

			return el;
		}
		var showTooltip = function ( ) {
		if(!tt_tooltip) {
			tt_tooltip = new RelativePopupWindow({
				htmlSource : get_tooltip_html(this.tooltipValue),
				vAlign : "topOf",
				hAlign : "center",
				snapTarget : this,
				useIframeShim : false
			});
		}
		else {
			tt_tooltip.setContent(get_tooltip_html(this.tooltipValue));
			tt_tooltip.snapTarget = this;
			tt_tooltip.showWindow();
		}
		}
		var hideTooltip = function ( ) {
			if(tt_tooltip)	tt_tooltip.hideWindow();
		}
		
		$$('.tooltip').each ( function ( el ) {
			if ( el.title ) {
				el.tooltipValue = el.tooltipValue || translateTooltip ( el.title );
				el.title = "";
				( function ( ) {
					el.addEvents ( {
						'mouseover' : showTooltip,
						'mouseout' : hideTooltip
					} );
				} ).delay ( 1000, el );
			}
		} );
	}
	// make this one publicly available
	window.resetTooltips = resetTooltips;

	function initGalleries() {

		var pageOptions = {
			transition : Fx.Transitions.Cubic.easeInOut,
			mode : 'horizontal',
			duration : 1000
		};

		function startLoading ( ) {
			this.loading = true;
			this.loader = ( this.loader
				|| ( new Fx.Style (
					new Element ( "div" )
						.setStyles ( {
							'background' : '#000 url(/static/css/base/img/loading.gif) 50% 50% no-repeat',
							'opacity' : 0,
							'position' : 'absolute'
						} )
						.injectInside ( document.body ),
					'opacity',
					{
						'wait' : false,
						duration : 350
					}
				)
			) );
			this.loader.element.setStyles(this.getCoordinates());
			this.loader.start ( 0.85 );
		}

		function stopLoading ( ) {
			this.loading = false;
			this.loader.start ( 0 );
		}

		function addPage ( page, pageNum ) {
			this.pageContainer.adopt ( page );
			page.setStyles ( {
				'width' : this.offsetWidth
					- parseInt ( this.pageContainer.getStyle('marginLeft') )
					- parseInt ( this.pageContainer.getStyle('marginRight' ) ),
				'margin' : 0
			} );

			var slider = new Fx.Slide ( page, pageOptions );
			var p = (pageNum || this.pages.length);
			this.pages[p] = slider;
			page.getParent().setStyle ( 'float', 'left' );
			slider.pageNum = p;
			
			if ( typeof this.onNewPage == "function" ) {
				this.onNewPage ( page, pageNum );
			}

			this.pageContainer.setStyle ( 'width', this.pageContainer.offsetWidth + this.offsetWidth );
			
			return slider;
		}

		function showPage ( pageNum,override ) {
			this.finalize = function() {
				this.finalize = null;
				if ( pageNum < this.current_page - 1 ) {
					for ( var p = 0, page; page = this.pages[p]; p ++ ) {
						if ( p == pageNum ) {
							page.slideIn.delay(100,page);
						} else if ( p == pageNum + 1 ) {
//							page.show();
						} else {
//							page.hide();
						}
					}
				} else {
					for ( var p = 0; page = this.pages[p]; p ++ ) {
						if ( p == pageNum ) {
//							page.show();
						} else if ( p == this.current_page - 1 ) {
							page.slideOut.delay(100,page);
						} else {
//							page.hide();
						}
					}
				}

				this.stopLoading();
				this.current_page = pageNum + 1;

				this.prev.enable ( pageNum > 0 );
				this.next.enable ( this.pages[pageNum+1] );
				resetTooltips.delay ( 100 ); /* DA - 1/30/2008. show tooltips for the items that weren't loaded in initial page load */

			}
			// pageNum is 1-based
			pageNum = (parseInt(pageNum) || 1) - 1;
			if ( (this.loading
				|| pageNum < 0
				|| pageNum == this.current_page - 1
				|| this.pages[pageNum] == false) 
				&& !override) return this;

			this.startLoading();
			if ( this.pages[pageNum] ) {
				this.finalize();
				return this;
			} 
			var self = this;
			API.fragments ( this.fragment,{rows:this.rows}, pageNum + 1, {
				onComplete : ( function ( obj ) {
					fragment = obj["fragment"];
					if ( fragment ) {
						var newPage = new Element ( "div" ).setHTML(fragment );
						this.addPage ( newPage.getFirst(), pageNum );
						this.finalize();
					} else {
						this.next.enable(false);
						this.pages[pageNum] = false;
						this.stopLoading();
					}
				} ).bind ( self ),
				onError : ( function ( err ) {
					this.next.enable(false);
					this.pages[pageNum] = false;
					this.stopLoading();
				} ).bind ( self )
			} );
			
			return this;
		}

		function showNextPage ( ) {
			this.showPage ( this.current_page + 1 );

			return this;
		}

		function showPreviousPage ( ) {
			this.showPage ( this.current_page - 1 );
			return this;
		}
		function initGallery(gallery){
			gallery.reset = function() {
				for(var i in gallery["pages"]) {
					if(gallery["pages"][i].element)
						gallery["pages"][i].element.remove();
				}
				gallery["pages"] = [];
				gallery["current_page"] = 0;
				gallery.showPage(1);
			}
			if ( scroller = $E('ul.scroller', gallery) ) {
			
				var p = $E('li.previous', scroller);
				var n = $E('li.next', scroller);
				if(gallery.getAttribute('fragment') == 'none') {
				//don't do anything.
				}
				else if ( gallery.fragment = gallery.getAttribute('fragment') ) {
					gallery.rows = gallery.getAttribute('rows');
					gallery.pages = [];
					gallery.current_page = 1;
					gallery.addPage = addPage;
					gallery.showPreviousPage = showPreviousPage;
					gallery.showNextPage = showNextPage;
					gallery.showPage = showPage;
					gallery.startLoading = startLoading;
					gallery.stopLoading = stopLoading;

					gallery.setStyles ( {
						'width' : gallery.getStyle('width'),
						'overflow' : 'hidden'
					} );
					gallery.getParent().setStyles ( {
						'overflow' : 'hidden'
					} );
					
					var curPage = $E('ul.thumbGallery', gallery);

					
					
					gallery.pageContainer = new Element ( "div", {
						'class' : 'pageContainer',
						styles : {
							//margin : curPage.getStyle ( 'margin' ),   // DA - commented out - 12/7/2007. setting it in css. 
																	// 12/11 - undoing my change. breaking profile sliders.
														// redo for battle? 
							overflow : 'hidden'//,
							/* height : '1%',*/ /* DA jan 2008 */ /* this is probably the issue. why is it set to 97px sometimes though? 
													MUST BE height of item 92 + margin 5px ? */
							//marginBottom : '10px'
	
						}
					} ).injectBefore(curPage).adopt(curPage);

					gallery.addPage ( curPage );

					gallery.pageContainer.setStyles ( { // ? first setting class, margin and height when creating the element, then
														// resetting it here after we do something?
						//height: "150px",
						//height: "1%", // maybe this is the problem: we start with 1% if then substract the margin. this is why we're left with not enough  height
						//height : gallery.pageContainer.offsetHeight
							//- parseInt ( gallery.pageContainer.getStyle('marginBottom') ),
						width : gallery.pageContainer.offsetWidth//,
						//height: "102px"
						// should be height: height of an item + top/bottom padding/margin - so if icon 92 + 10 or something.
						// else set it in the css per element...
					} );

					p.addEvents ( {
						"click" : function ( e ) {
							e = new Event ( e );
							e.stop();
							gallery.showPreviousPage();
						}
					} );
					n.addEvents ( {
						"click" : function ( e ) {
							e = new Event ( e );
							e.stop();
							gallery.showNextPage();
						}
					} );

					var enablePaginator = function ( dir ) {
						return function ( enabled ) {
							if ( enabled == null || enabled ) {
								this.getFirst().setStyles ( {
									'backgroundImage' : 'url(/static/css/base/img/scroller_' + dir + '08.gif)'//,
									//'cursor' : null
								} );
							} else {
								this.getFirst().setStyles ( {
									'backgroundImage' : 'url(/static/css/base/img/scroller_' + dir + 'None08.gif)'//,
									//'cursor' : 'default'
								} );
							}
						}
					}

					p.enable = enablePaginator('prev');
					n.enable = enablePaginator('next');
					p.enable(false);

					gallery.prev = p;
					gallery.next = n;
				} else {
					var f = function ( e ) { e = new Event ( e );  e.stop(); }
					p.addEvents ( { "click" : f } );
					p.getFirst().setStyles ( {
						'backgroundImage' : 'url(/static/css/base/img/scroller_prevNone08.gif)'//,
						//'cursor' : 'default'
					} );
					n.addEvents ( { "click" : f } );
					n.getFirst().setStyles ( {
						'backgroundImage' : 'url(/static/css/base/img/scroller_nextNone08.gif)'//,
						//'cursor' : 'default'
					} );
				}

//				gallery.addPage(curPage.clone()).hide();
//				gallery.addPage(curPage.clone()).hide();
			}
			gallery.fireEvent("loaded");
			gallery.loaded = true;
		}

		$ES('.section .gallery').each ( function ( gallery ) {
			initGallery(gallery);
		} );
		return {
			init_gallery:function(gal) {
				initGallery(gal);
			}
		};
	}

	function initSliders ( ) {
		$ES('.section').each ( function ( section ) {
			if ( section.hasClass('slidable') ) {
				var track = $E('.slider',section);
				var handle = $E('.handle',track);
				var content = $E('.content',section).getFirst();
				var items = $ES('li',content);
				var itemSize = 0;
				if ( items.length ) {
					itemSize = items[0].getCoordinates().width
						+ parseInt ( items[0].getStyle('marginLeft') )
						+ parseInt ( items[0].getStyle('marginRight') );
				}
				var width = ( items.length * itemSize )
					+ parseInt ( content.getStyle('marginLeft') )
					+ parseInt ( content.getStyle('marginRight') )
					+ parseInt ( content.getStyle('paddingLeft') )
					+ parseInt ( content.getStyle('paddingRight') );
				
				if ( width >= section.getCoordinates().width ) {
					content.setStyle ( 'width', width + 100 );
					var factor = 10;
					var steps = ( width - section.offsetWidth ) / factor;
				} else {
					factor = 0;
					steps = 1;
				}
	
				var slider = new Slider ( track, handle, {
					steps : steps,
					offset : 0,
					onChange : function ( step ) {
						this.step = step;
						content.setStyle ( 'left', ( -factor * step ) + "px" );
					}
				} );
				slider.set ( steps / 2 );
				handle.setStyle('margin',0);
			}
		} );
	}

	// set up cookie object
	( function ( ) {
		var cookies = { };
		var names = [];

		var cs = document.cookie.split ( ';' );
		for ( var i = 0, c; c = cs[i]; i ++ ) {
			c = c.replace(/(^\s+|\s+$)/,'').split('=');
			cookies[c[0]] = c[1];
			names.push ( c[0] );
		}

		window.COOKIES = {
			names : names,
			get : function ( name ) {
				return cookies[name];
			},
			set : function ( name, value, seconds, path ) {
				var expires = "";
				if ( seconds ) {
					var date = new Date();
					date.setTime ( date.getTime() + ( seconds * 1000 ) );
					expires = "; expires=" + date.toGMTString();
				}
				var expires = seconds ? $time() + seconds : "";
				document.cookie = name + "=" + value + expires + "; path=" + ( path || "/" );
				window.COOKIES.names.remove ( name );
				window.COOKIES.names.push ( name );
				cookies[name] = value;
			},
			remove : function ( name ) {
				window.COOKIES.set ( name, "", -1 * 60 * 60 * 24 );
				window.COOKIES.names.remove ( name );
			}
		}

	} )();
	
	// Nav funtions for IE 6  and lower 
		var navIe6Fix = function() {
			if( ! document.getElementById('nav')) { //IE6 hack, just in case it isn't loaded yet
				window.addEvent ( "load", function( ) { navIe6Fix(); } );
				return;
			}
			var sfEls = document.getElementById("nav").getElementsByTagName("LI");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					this.className+=(this.className.length>0? " ": "") + "sfhover";
				}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp("( ?|^)sfhover\\b"), "");				
				}
			}
		}
		// Begin iframe hack for IE 6 and lower for select boxes 
		sfHover = function() {
			// Support the standard nav without a class of nav.
			var el = document.getElementById("nav");
			if (el) {
				if(!/\bnav\b/.test(el.className) && el.getTag() == "ul") {
					setHover(el);
				}
			}
			// Find all unordered lists.
			var ieNavs = document.getElementsByTagName('ul');
			for(i=0; i<ieNavs.length; i++) {
				var ul = ieNavs[i];
				// If they have a class of nav add the menu hover.
				if(/\bnav\b/.test(ul.className))
					setHover(ul);
			}
	
		}
		function setHover(nav) {
			var ieULs = nav.getElementsByTagName('ul');
			if (navigator.appVersion.substr(22,3)!="5.0") {
				// IE script to cover <select> elements with <iframe>s
				for (j=0; j<ieULs.length; j++) {
					var ieMat=document.createElement('iframe');
					if(document.location.protocol == "https:")
						ieMat.src="//0";
					else if(window.opera != "undefined")
						ieMat.src="";
					else
						ieMat.src="javascript:false";
					ieMat.scrolling="no";
					ieMat.frameBorder="0";
					ieMat.style.width=ieULs[j].offsetWidth+"px";
					ieMat.style.height=ieULs[j].offsetHeight+"px";
					ieMat.style.zIndex="-1";
					ieULs[j].insertBefore(ieMat, ieULs[j].childNodes[0]);
					ieULs[j].style.zIndex="101";
				}
				// IE script to change class on mouseover
				var ieLIs = nav.getElementsByTagName('li');
				for (var i=0; i<ieLIs.length; i++) if (ieLIs[i]) {
					// Add a sfhover class to the li.
					ieLIs[i].onmouseover=function() {
						if(!/\bsfhover\b/.test(this.className))
							this.className+=" sfhover";
					}
					ieLIs[i].onmouseout=function() {
						if(!this.contains(event.toElement))
							this.className=this.className.replace(' sfhover', '');
					}
				}
			} else {
				// IE 5.0 doesn't support iframes so hide the select statements on hover and show on mouse out.
				// IE script to change class on mouseover
				var ieLIs = document.getElementById('nav').getElementsByTagName('li');
				for (var i=0; i<ieLIs.length; i++) if (ieLIs[i]) {
					ieLIs[i].onmouseover=function() {this.className+=" sfhover";hideSelects();}
					ieLIs[i].onmouseout=function() {this.className=this.className.replace(' sfhover', '');showSelects()}
				}
			}
		}
		// If IE 5.0 hide and show the select statements.
		function hideSelects(){
			var oSelects=document.getElementsByTagName("select");
			for(var i=0;i<oSelects.length;i++)
				oSelects[i].className+=" hide";
		}
		function showSelects(){
			var oSelects=document.getElementsByTagName("select");
			for(var i=0;i<oSelects.length;i++)
				oSelects[i].className=oSelects[i].className.replace(" hide","");
		}	
		// Run this only for IE.
		if (isIE6) window.attachEvent('onload', sfHover);
		// end iframe hack
		// end nav
	// check to see if the user is logged in... if not, prepare the log-in box
	window.addEvent ( "domready", function ( ) { checkLogin.delay ( 100 ); } );
	if (window.ie6 == 1) {
		window.addEvent( "domready", function( ) { navIe6Fix.delay( 100 ) } ); 
	}
	function _initGalleries() {
		GalleryManager = initGalleries();
	}
	// set up elements that require a tool tip
	window.addEvent ( "load", function ( ) { resetTooltips.delay ( 100 ); } );
	window.addEvent ( "load", _initGalleries );
	window.addEvent ( "load", function( ) { initSliders.delay ( 100 ); } );
	window.addEvent ( "load", RatingManager.init );
	window.addEvent ( "load", Top100RatingManager.init );

	window.addEvent ( "load", function ( ) {
		if ( user = COOKIES.get('user') ) {
			eval ( "TAKKLE.user = " + unescape ( user ) );
		}
	} );
	window.addEvent ( "load", function ( ) {
		var skip = false;
		if( window.location.href.match(/login/) )	skip = true;
		if( Cookie.get('after_login') && !skip )	after_login = Json.evaluate( Cookie.get('after_login') );
		else return false;
		if(!	
			( !Cookie.get('uli') ) 					//not logged in
		||	( window.location.href != after_login["referrer"] ) 	//not where they came from
		||	( skip ) )						//on login page somehow
			if(after_login["js"])	eval(after_login["js"]);
		if(!skip)	Cookie.set('after_login','',{ path : "/" }); //Delete the cookie if you're not logging in.
			
	});

} )();
