var fontClassFilters = [];
var Font = function(){this.init.apply(this, arguments)};
Font.prototype = {
	fontPath: basePath+'/swf/',
	init: function(swf, options){
		this.swf = this.fontPath + swf;
		this.setOptions(options || {});
		String.prototype.rgbToHex = this.rgbToHex;
		String.prototype.toHex = this.toHex;
		Array.prototype.indexOf = this.indexOf;
	},
	setOptions: function(o){
		this.options = {
			sizeAdjust: o.sizeAdjust || 0,
			color: o.color || o.sColor,
			bgcolor: o.bgcolor,
			width: o.width,
			height: o.height,
			sWmode: o.sWmode || 'transparent',
			tags: o.tags || '',
			classFilter: o.classFilter || ''
		}
		if(o.classFilter) fontClassFilters[fontClassFilters.length] = o.classFilter;
	},
	replace: function(tags){
		var tags = (tags || this.options.tags).split(',');
		for(var i=0; tag=tags[i]; i++)
			this.replaceTag(tag);
	},
	replaceTag: function(tag){
		this.replaceElements(document.getElementsByTagName(tag));
	},
	replaceElements: function(els){
		for(var i=0; el=els[i]; i++)
			this.replaceElement(el);
	},
	replaceElement: function(el){
		var o = this.options;
		if(!this.hasFlash || el.oldHTML || (!o.classFilter && this.hasClassName(el, fontClassFilters)) || (o.classFilter && el.className.indexOf(o.classFilter)==-1) ) return;
		var c = this.options.color || el.style.color || document.defaultView ? document.defaultView.getComputedStyle(el, null).color : el.currentStyle ? el.currentStyle.color : '#000001';
		if(c.indexOf('rgb') > -1) c = '#'+c.rgbToHex();
		else if(c.length == 4) c = '#'+c.charAt(1)+c.charAt(1)+c.charAt(2)+c.charAt(2)+c.charAt(3)+c.charAt(3);
		var width = o.width || (el.offsetWidth + o.sizeAdjust) * .9;//fix for ie floats
		var height = o.height || el.offsetHeight;
		var sVars = 'txt=' + escape(el.innerHTML) + '&amp;textcolor=' + c + '&amp;w=' + width + '&amp;h=' + (height+o.sizeAdjust) + '';
		el.oldHTML = el.innerHTML;
		el.innerHTML = '<embed type="application/x-shockwave-flash" src="' + this.swf + '" quality="best" wmode="' + o.sWmode + '" bgcolor="' + o.bgcolor + '" flashvars="' + sVars + '" width="' + width + '" height="' + height + '" sifr="true"></embed>';
	},
	hasClassName: function(el, classNames) {
		var classNames = el.className.split(' ');
		for(var i=0; cn=classNames[i]; i++)
			if(classNames.indexOf(cn)) return true;
		return false;
	},
	indexOf: function(needle){
		for(var i=0; val=this[i]; i++)
			if(val == needle) return i;
		return -1;
	},
	toHex: function(){//borrowed from mootools.net
		var N = parseInt(this);
		if (N==0 || isNaN(N)) return "00";
		N = Math.round(Math.min(Math.max(0,N),255));
		return "0123456789abcdef".charAt((N-N%16)/16) + "0123456789abcdef".charAt(N%16);
	},
	rgbToHex: function(){//borrowed from mootools.net
		var rgb = this.match(/[rgba]{3,4}\(([\d]{0,3}),[\s]([\d]{0,3}),[\s]([\d]{0,3})\)/);
		return rgb[1].toHex()+rgb[2].toHex()+rgb[3].toHex();
	},
	hasFlash: function(){//borrowed from the original sIFR
		var nRequiredVersion = 6;
		if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") > -1){
			document.write('<script language="VBScript"\> \non error resume next \nhasFlash = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & ' + nRequiredVersion + '))) \n</script\> \n');
			if(window.hasFlash != null)
				return window.hasFlash;
		};
		if(navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
			var flashDescription = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description;
			return parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1)) >= nRequiredVersion;
		};
		return false;
	}()
}


$(document).ready(function(){
	
	$('ul.profile-list-large li dl dd, ul.profile-list-small li dl dd').hover(function(){
		$(this).siblings('dt').addClass('on');
	},
	function(){
		$(this).siblings('dt').removeClass('on');
	});

	$('ul.profile-list-large li dl dt, ul.profile-list-small li dl dt').hover(function(){
		$(this).addClass('on');
	},
	function(){
		$(this).removeClass('on');
	});
	
	// Every other item in style guide is grey
	$('.style-guide .article-list li:odd').addClass('odd');
	
	// Style guide stuff, the scrolling
	topMargin =  0;
	ulHeight = $('.style-guide .article-list ul').height();
	$('.style-guide .scroll').click(function(){
		//console.log('before click '+topMargin);
		ulMargin = $('.style-guide .article-list ul').css('marginTop');
		if($(this).hasClass('up')){
			if(topMargin==0){
				return false;
			}
			else{
				topMargin--;
				$('.article-list ul').animate({
					"marginTop": (topMargin * -500)
				}, { queue: true, duration: 1000 });
				
			}
		}
		else{
			if(topMargin== 6){
				return false;
			}
			else{
				topMargin++;
				$('.article-list ul').animate({
					"marginTop": (topMargin * -500)
				}, { queue: true, duration: 1000 });
			}
			
		}
		//console.log('after click '+ topMargin);
		return false;
	});
	
	
	//Checking the height of browse images
	/*$('#main ul.profile-list-small li dl dd img').each(function(){
		var imgh = $(this).height();
		if(imgh<195){
			var imgp = (193 - imgh) / 2;
			$(this).css('paddingTop',imgp);
		}
	});*/
	
	// $('#main .admin ul.tools li.message > a').click(function(){
	// 	$(this).parent().addClass('on');
	// 	$(this).siblings('div.send-message').addClass('message-on');
	// 	return false;
	// 	
	// });
	$('#main .admin ul.tools li.message > a').live('click', function () {
		$(this).parent().addClass('on');
		$(this).siblings('div.send-message').addClass('message-on');
		return false;
	});
	
	$('div.send-message a.close').live('click', function () {
		$('.send-message').removeClass('message-on');
		return false;
	});
	
	
	$('#footer').parent('div').addClass('wrapperbottom');
	
	//Jquery countdown
	var endDate = new Date();
	endDate = new Date(2010, 9 - 1, 7);
	// new Date(year, mth - 1, day, hr, min, sec)
	$('.countdown span').countdown({until: endDate, format: 'D'});
	
	
	$('.signup-login dd a.loginbox').click(function(){
		var url = $(this).attr('href');
		$('.signup-search div').removeClass('current');
		$('.signup-search div.'+url).addClass('current');
		return false;
	});
	
	$('.signup-login .close, .signup-search .close').click(function(){
		$('.signup-search div').removeClass('current');
		return false;
	});


	$('.defaultable').focus(function() { if( this.value == this.defaultValue ) { this.value = ""; } }).blur(function() { if( !this.value.length ) { this.value = this.defaultValue; } });
	
	$('a.btn-delete-photo').live('click', function () {
		if(confirm('Are you sure you want to delete this image?')) {
				$.get(basePath+'users/del_image/' + $(this).parent().parent().parent().attr('id').replace('userImage', ''), null, 
				function(response){
						eval('response = ' + response);
						if (response.result == 'success') {
							$('#userImage'+response.id).slideUp('slow');
						}
				});
		}
		return false;
	});
	
	$('a#btnAccept').live('click', function(){
		id = $(this).attr('rel');
		$.post(basePath+'users/update_status', {'data[User][id]': id, 'data[User][status]': 'public'}, 
		function(response){
				//$('#btnAccept').parent().parent().html('').append(response).hide().fadeIn('slow');
				location.reload();
		});
	});
	
	$('a#btnReject').live('click', function(){
		id = $(this).attr('rel');
		$.post(basePath+'users/update_status', {'data[User][id]': id, 'data[User][status]': 'rejected'}, 
		function(response){
				//$('#btnReject').parent().parent().html('').append(response).hide().fadeIn('slow');
				location.reload();
		});
	});
	
	$('a#btnUnfav').live('click', function(){
		$.post(basePath+'users/update_status', {'data[User][id]': $(this).attr('rel'), 'data[User][favorite]': 'false'}, 
		function(response){
				//$('#btnReject').parent().parent().html('').append(response).hide().fadeIn('slow');
				location.reload();
		});
		//$(this).parent().fadeOut('slow');
		//$(this).parent().next().fadeIn('slow');
		return false;
	});
	
	$('dd a.delete-fav').live('click', function(){
		if(confirm('Are you sure?') == true){
			id = $(this).attr('rel');
			$.post(basePath+'users/update_status', {'data[User][id]': id, 'data[User][favorite]': 'false'}, 
			function(response){
					//$(this).parent().parent().parent().html('').append(response).hide().fadeIn('slow');
			});
			$(this).parent().parent().parent().fadeOut('slow');
			return false;
		} else {
			return false;
		}
	});
	
	$('.wrapperbottom').css('position', 'relative');
	$('.wrapperbottom').append('<a href="http://huntandgather.com" target="_blank" class="hg">Hunt &amp; Gather</a>');
	
	$('.next.upload-images').click(function(){
		$(this).addClass('loading');
		$(this).append('ing');
	})
	
	$('a#btnFav').live('click', function(){
		$.post(basePath+'users/update_status', {'data[User][id]': $(this).attr('rel'), 'data[User][favorite]': 'true'}, 
		function(response){
				//$('#btnReject').parent().parent().html('').append(response).hide().fadeIn('slow');
				location.reload();
		});
		//location.reload();
		//$(this).parent().fadeOut('slow');
		//$(this).parent().prev().fadeIn('slow');
		return false;
	});
	
	$('a#btnUnflag').live('click', function(){
		$.post(basePath+'users/update_status', {'data[User][id]': $(this).attr('rel'), 'data[User][flagged]': '0'}, 
		function(response){
			$('#btnReject').parent().parent().html('').append(response).hide().fadeIn('slow');
		});
	});
	
	$('ul#siteNav li.login a').click(function () {
		$(this).parent().hide();
		$(this).parent().parent().find('form').fadeIn('slow');
		return false;
	})

	/* Browse Tabs navigation */
	$('dt.tabs span').click(function(){
		$('#main .browse .current').removeClass('current');
		$(this).parent().parent().parent().children('dl.' + $(this).attr('class')).addClass('current').find('span.'+$(this).attr('class')).addClass('current');
		return false;
	});
	
	/* Browse sort links */
	$('dl.sort-by dd li a').click(function(){

	});
	
	/* Profile Tabs navigation */
	$('dt.tabs span').click(function(){
		$('#main .profiles .current').removeClass('current');
		$(this).parent().parent().parent().children('dl.' + $(this).attr('class')).addClass('current').find('span.'+$(this).attr('class')).addClass('current');
		return false;
	});

	$('a.btn-flag').click(function() {
		 userId = $(this).attr('class').replace('btn-flag flag-user-', '');
			$.post(basePath + '/users/flag/' + userId, {'data[User][id]' : userId}, function(){
		 		$('a.btn-flag').replaceWith('<span>Thanks for flagging.</span>').hide().fadeIn('slow');
		 	});
		
		return false;
	});
	
	//alert($('#headerMain #siteNav li.current strong').val());
	
	/* Feature Scroll */

		var featureWidth = $('#galleryFeature ul li').length*125;
		if(featureWidth<630){
		//alert('this '+featureWidth);
		//$('#galleryFeature dd span').css('display','none');
		}
		$('#galleryFeature ul').width(featureWidth);

		$('#galleryFeature span.back').click(function(){
			var position = $('#galleryFeature ul').position();
			if ( position.left != 0 && !$('#siteFeature dd ul').is(':animated') ) {  // Checks to see if its at the beginning and if its still animating
				$('#galleryFeature ul').animate({
					"left": position.left + 625
				}, { queue: true, duration: 2000 });
			} else {
				/*$('#galleryFeature ul').animate({
					"left": -(position.left + (featureWidth-125))
				}, { queue: true, duration: 2000 });*/
				return false; 
			}
		});

		$('#galleryFeature span.forward').click(function(){
			var position = $('#galleryFeature ul').position();
			if ( position.left > (0-(featureWidth-625)) && !$('#galleryFeature ul').is(':animated') ) {  // Are we at the end?  Is the list still animating?
				$('#galleryFeature ul').animate({
					"left": position.left - 625
				}, { queue: true, duration: 2000 });
			} else{
				/*$('#galleryFeature ul').animate({
					"left": 0
				}, { queue: true, duration: 2000 });*/
				return false; 
			}
		});
		if($('#galleryFeature ul').width() <= 625){
			$('#galleryFeature span.forward, #galleryFeature span.back').addClass('off');
		}


		$('#main ul.profile-list-large li dl dt a span:not(.details)').each(function(){
			var dtLength = $(this).text().length;
			if(dtLength>=13){
				$(this).parent().parent().addClass('tall');
			}
		});
		
		$('#main ul.profile-list-small li dl dt a span:not(.details)').each(function(){
			var dtLength = $(this).text().length;
			if(dtLength>=16){
				$(this).parent().parent().addClass('tall');
			}
		});

	/* End Feature Scroll */
	
	/*#### add form element things */
	
	var appendNum = 0;
	var savedPhotos = $('.uploaded-photos li').length;
	
	if(savedPhotos!=0){
		appendNum = savedPhotos;
	}
	
	if(savedPhotos>=10){
		$('.register .photo-select fieldset').html('<div><h5>You can not add any more photos</div>');
		$('.next.upload-images').hide();
		$('.add-photo').hide();
	}
	
	//alert(appendNum);
	$('.register .photo-select fieldset div').each(function(){
		appendNum++;
		$(this).children('label').html('Photo '+appendNum);
	});
	
	// var selectNum = savedPhotos;
	// $('.photo-select fieldset div').each(function(){
	// 	selectNum++;
	// 	$(this).children('label').html('Photo '+selectNum);
	// });

	$('.register .uploaded-photos li a.image').click(function(){
		var el = $(this).parent();
		$.get($(this).attr('href'), null, 
		function(response){
				eval('response = ' + response);
				if (response.result == 'success') {
					$('.register .uploaded-photos li').removeClass('profile-image');
					el.addClass('profile-image');
				}
		});
	});
	
	$('.register .uploaded-photos li').click(function(){
		var imgIndex = $('.uploaded-photos li').index(this)+1;
		$('#mainProfileImage').val(imgIndex);
		return false;
	});
	
	$('.register .uploaded-photos li a.cancel').click(function(){
		if(confirm('Are you sure you want to delete this image?')) {
			var el = $(this).parent();
			$.get(basePath+'users/del_image/' + $(this).attr('href'), null, 
			function(response){
					eval('response = ' + response);
					if (response.result == 'success') {
						el.slideUp('slow');
					}
			});
		}
		return false;
	});
	
	$('.add-photo a.new-photo').click(function(){
		if(appendNum<10){
			appendNum++;
			$('.register .photo-select fieldset').append('<div class="input file">'
															+'<label for="UserPhoto'+appendNum+'">Photo '+appendNum+'</label>'
															+'<input type="file" id="UserPhoto'+appendNum+'" name="data[UserImage]['+appendNum+'][filename]" />'
															+'</div>');
		}
		else{
			alert('You can only upload 10 photos');
		}
		return false;
	});
	
		$('#main .link-list ul li.wide').bookmark({
			popup: true, 
			popupText: 'More Options',
			sites: ['delicious', 'digg', 'facebook', 'google', 'linkedin', 'livejournal', 'mixx', 'myspace', 'netvibes', 'orkut', 'reddit', 'stumbleupon', 'tumblr', 'yammer'],
			addEmail: true,
			addFavorite: true,
			compact: false
		});
	
	
		$('#header img, .wrapperbottom img').each(function(){
			$(this).attr('onmouseout', '');
			$(this).attr('onmouseover', '');

			var imgSrc = $(this).attr('src');
			var finalSrc = 'http://esquire.com'+imgSrc;
			$(this).attr('src',finalSrc);
			var imgName = $(this).attr('alt').toLowerCase();
		});
		
		$('.nav_item a img').hover(function(){
			//var imgSrc = $(this).attr('src');
			//var finalSrc = 'http://esquire.com'+imgSrc;
			//$(this).attr('src',finalSrc);
		},
		function(){
			//imgSrc = $(this).attr('src');
			//finalSrc = 'http://esquire.com'+imgSrc;
			//$(this).attr('src',finalSrc);
		});
		
		$('#content #callouts ul li').hover(function(){
			if($(this).hasClass('odd')){
				$(this).addClass('odd-on');
			}
			else{
				$(this).addClass('on');
			}
		},
		function(){
			if($(this).hasClass('odd')){
				$(this).removeClass('odd-on');
			}
			else{
				$(this).removeClass('on');
			}
		});
		
	
			$('#galleryFeature ul li div').hide();  // close any that are open

			var photoNum = jQuery.url.attr("anchor");
			if(photoNum!=null){
				var loadguts = $('#galleryFeature ul li div.'+photoNum).html();
				if(loadguts==null){
					loadguts = $('#galleryFeature ul li div.photo1').html();
				}
				$('#galleryDetail').html(loadguts);
			}
			$('#galleryFeature ul li a.'+photoNum).parent().addClass('current');
		    $('#galleryFeature ul li a').click(function(){
					invokeOmniture();
			        var mom = $(this).parent('li');
			        var guts = mom.find('div').html();
			        $('#galleryDetail').html(guts);
					$('#galleryFeature ul li').removeClass('current');
					$(this).parent().addClass('current');
					//return false;
			    });
	
	$('.close-popup').click(function(){
		$('.close-popup').hide();
		$('.home-callout').slideUp('slow');
	});
});

function invokeOmniture() {
	if (top.s) {
		s.pageName="Esquire: " + (location.href);
		s.server="ESQ"
		s.channel="Best Dressed Real Man 2009"
		s.prop5=""
		s.prop26="Men"
		s.hier1="Best Dressed Real Man 2009"
		s.hier2="ESQ|Best Dressed Real Man 2009"
		/* E-commerce Variables */
		s.events=""
		s.linkInternalFilters="javascript:,esquirebdrm.com,esquire.com"
		s.eVar2=s.pageName
		s.eVar3=s.channel
		s.eVar4=s.hier1
		s.referrer=(location.href);
		void(s.t());
	}
}