/*th-js start*/
/****DETECT SWIPE CODE***/

/**
 * jquery.detectSwipe v2.1.1
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch, iPad and Android
 * http://github.com/marcandre/detect_swipe
 * Based on touchwipe by Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 */
(function($) {

  $.detectSwipe = {
    version: '2.1.1',
    enabled: 'ontouchstart' in document.documentElement,
    preventDefault: true,
    threshold: 50
  };

  var startX,
    startY,
    isMoving = false;

  function onTouchEnd() {
    this.removeEventListener('touchmove', onTouchMove);
    this.removeEventListener('touchend', onTouchEnd);
    isMoving = false;
  }

  function onTouchMove(e) {
    if ($.detectSwipe.preventDefault) {e.preventDefault();}
    if(isMoving) {
      var x = e.touches[0].pageX;
      var y = e.touches[0].pageY;
      var dx = startX - x;
      var dy = startY - y;
      var dir;
      if(Math.abs(dx) >= $.detectSwipe.threshold) {
        dir = dx > 0 ? 'left' : 'right'
      }
      else if(Math.abs(dy) >= $.detectSwipe.threshold) {
        dir = dy > 0 ? 'down' : 'up'
      }
      if(dir) {
        onTouchEnd.call(this);
        $(this).trigger('swipe', dir).trigger('swipe' + dir);
      }
    }
  }

  function onTouchStart(e) {
    if (e.touches.length == 1) {
      startX = e.touches[0].pageX;
      startY = e.touches[0].pageY;
      isMoving = true;
      this.addEventListener('touchmove', onTouchMove, false);
      this.addEventListener('touchend', onTouchEnd, false);
    }
  }

  function setup() {
    this.addEventListener && this.addEventListener('touchstart', onTouchStart, false);
  }

  function teardown() {
    this.removeEventListener('touchstart', onTouchStart);
  }

  $.event.special.swipe = { setup: setup };

  $.each(['left', 'up', 'down', 'right'], function () {
    $.event.special['swipe' + this] = { setup: function(){
      $(this).on('swipe', $.noop);
    } };
  });
})(jQuery);


/**** END DETECT SWIPE CODE ***/




/*HEADER JS*/ 

var relPage = 0,_th_imgLoaded = true,_th_gettingMore = false,_th_ap = "/ta", _th_signupLoaded = false,_th_gs = {g:0,c:1}, _th_rrLoaded = false, _th_$menuReq = null, _th_lastClick = 0 ;

var _md = {li:null,t:null,l:false, m:null,to:null};
var _th_initHeader = function(){

	if(typeof ieMenuOff != 'undefined' && ieMenuOff == true){
		return false;
	}

	$('.header .megaMenu > li').on('mouseenter',function(){
		if(!_md.l){
			_md.l = true;
			
			if(window.innerWidth > 1104){ //dont load the pages on tablets or below
				$.get('/ta',{ajax:true,act:'gmm'},function(r){
					if(!r.success){
						_md.l = false;
						return;
					}
					$('.header .headerMenuContainer .container').append(r.data);
					_md.l = true;
					var m = $('.header .megaMenu > li.selected').data('m');
					if(m != null){
						_th_lazyMenu($('.header .headerMenuContainer div[data-m="'+m+'"]'));
						$('.header .headerMenuContainer div[data-m="'+m+'"]').addClass('').fadeIn('fast');
						
						
						if(typeof _th_trackEvent == 'function'){
							_th_trackEvent('menu',$('.megaMenu li.selected a').attr('href').substr($('.megaMenu li.selected a').attr('href').lastIndexOf('/') + 1));
						}

						if(typeof _th_trackHeader == 'function'){
							_th_trackHeader($('.megaMenu li.selected a').attr('href'),'1');
						}
					}
				},'json');
				}
		}
		if($(this).data('m') == null){
			return false;
		}
		_md.li = $(this).data('m');

		if(_md.t != null && new Date().getTime()/1000 - _md.t < 0.2){
			if(_md.to != null){
				clearTimeout(_md.to);
				_md.to = null;
			}
			$('.header .megaMenu > li').removeClass('selected');
			$('.header .headerMenuContainer div.menuPage').removeClass('selected').hide();
			$('.header .megaMenu > li[data-m="'+_md.li+'"]').addClass('selected');
			_th_lazyMenu($('.header .headerMenuContainer div[data-m="'+_md.li+'"]'));
			$('.header .headerMenuContainer div[data-m="'+_md.li+'"]').addClass('').show();
			if(typeof _th_trackEvent == 'function'){
				_th_trackEvent('menu',$('.megaMenu li.selected a').attr('href').substr($('.megaMenu li.selected a').attr('href').lastIndexOf('/') + 1));
			}	
			
			if(typeof _th_trackHeader == 'function'){
				_th_trackHeader($('.megaMenu li.selected a').attr('href'),'2');
			}
			
			
			return;
		}
		setTimeout(function(){
			if(_md.li == null){return;}
			$('.header .megaMenu > li[data-m="'+_md.li+'"]').addClass('selected');
			
			_th_lazyMenu($('.header .headerMenuContainer div[data-m="'+_md.li+'"]'));
			$('.header .headerMenuContainer div[data-m="'+_md.li+'"]').addClass('').fadeIn('fast');

			if(typeof _th_trackEvent == 'function'){
				_th_trackEvent('menu',$('.megaMenu li.selected a').attr('href').substr($('.megaMenu li.selected a').attr('href').lastIndexOf('/') + 1));
			}	
			if(typeof _th_trackHeader == 'function'){
						_th_trackHeader($('.megaMenu li.selected a').attr('href'),'3');
			}
			
		},500);
	});
	$('.header .megaMenu > li').on('mouseleave',function(){
		_md.to = setTimeout(function(){
			if(_md.m == _md.li){return;}
			_md.li = null;
			$('.header .megaMenu > li').removeClass('selected');
			$('.header .headerMenuContainer div.menuPage').removeClass('selected').hide();
		},150);
		_md.t = new Date().getTime()/1000;

	});
	$('.header .headerMenuContainer').on('mouseenter','.menuPage',function(){
		_md.m = $(this).data('m');
	}).on('mouseleave','.menuPage',function(){
		_md.m = null;
		_md.li = null;
		$('.header .megaMenu > li').removeClass('selected');
		$('.header .headerMenuContainer div.menuPage').removeClass('selected').hide();
		_md.t = new Date().getTime()/1000;
	});
	
	
	$('.header .headerMenuContainer').on('mouseenter','.menuPage:not([data-m="g"]) .left a:not(.alink)',function(){
		var href = $(this).attr('href');
		href = href.substr(href.lastIndexOf('/') + 1).toLowerCase();
		
		if(href == ""){
			return false;
		}
		
		var mPage = $(this).parents('.menuPage').data('m');
		var params = {ajax:true, act:'gmc', cat:href};
		
		if(_th_$menuReq != null){_th_$menuReq.abort();}
		
		_th_$menuReq = $.get(_th_ap,params,function(r){
			_th_$menuReq = null;
			if(!r.success){
				return false;
			}
				
			$('.headerMenuContainer .menuPage[data-m="'+mPage+'"] .right').html(r.data);
				
			
		},'json').fail(function(jqXHR, textStatus, errorThrown){});});


	if($('.headerMenuContainer').length > 0 && (window.innerWidth > 1104)){
		$(window).on('scroll',function(){
		//+ $('.headerMenuContainer').height() + 100
		//window.pageYOffset > $('.headerMenuContainer').position().top 
			if($(window).scrollTop() > 150){$('.headerMenuContainer').addClass('fixed');}else{$('.headerMenuContainer').removeClass('fixed');}
		//$('.adMobile3').position().top - 70
		//	if(window.innerWidth <= 767 && $('.adMobile3').length > 0){
		//		if($(window).scrollTop() > 30 ){
		//			$('.adMobile3').addClass('fixed');
		//		}else{
		//			$('.adMobile3').removeClass('fixed');
		//		}
		//	}
			
		});
	}
}

var _th_lazyMenu = function($cont){
	console.log('lazy loading menu');
	$cont.find('img').each(function(){
		if($(this).attr('src') == null || $(this).attr('src') == ""){
			if($(this).data('src') != null){$(this).attr('src',$(this).data('src'));}
		}
	});
	
}


if($_GET['ca'] != null ){$('.wrapper').addClass('sponsored');}

var _th_trackEvent = function(category,action, label){

	label = label == null ? '' : label;
	category = category+"";
	action = action+"";
	label = label+"";
	_gaq.push(['_trackEvent',category,action,label]);
}

var _th_trackHeader = function(url,which){
	url = url.substr(url.indexOf("trendhunter.com")+15);
	_gaq.push(['_trackPageview', url]);
}




/*END HEADER JS*/

var _th_out = function(msg){
	if(_th_debug){alert(msg);}
}




$(function(){
	_th_initHeader();
	_th_getMemberInfo();
	_th_checkFancy();
	_th_checkAmazon();
	//_th_galleryBuffer();
	
	if($('.note').length > 0){console.log($('.note').html());}
	
	//enable swipe 
	if(window.innerWidth <= 1104){
		if(typeof $.detectSwipe != 'undefined' && $.detectSwipe.enabled){
			$.detectSwipe.preventDefault = true;
			$(".mainGallery").on('swipeleft',  function(e){ 
				e.stopPropagation();
				$.detectSwipe.preventDefault = true;
				_th_galleryNext();
				_th_trackEvent('swipe','left');

			}).on('swiperight', function(){ 
				$.detectSwipe.preventDefault = true;
				_th_galleryPrev();
				_th_trackEvent('swipe','right');
			}).on('swipeup',function(){
				$.detectSwipe.preventDefault = false;
			}).on('swipedown',function(){
				$.detectSwipe.preventDefault = false;
			});
						
			$(".wrapper").on('swipeleft',  function(){ 
				$.detectSwipe.preventDefault = true;
				if($('.topHeader li:nth-of-type(3) a').length > 0){
					window.location.href = $('.topHeader li:nth-of-type(3) a').attr('href');
				}
				_th_trackEvent('swipe','page-next');
			}).on('swiperight', function(){ 
				$.detectSwipe.preventDefault = true;

			}).on('swipeup',function(){
				$.detectSwipe.preventDefault = false;
			}).on('swipedown',function(){
				$.detectSwipe.preventDefault = false;
			});
			
		}
	}
	
	
	$('.randomBlock').on('click','div',function(){
		if($(this).data('href') == null){
			return ;
		}else{
			var rLink = $(this).data('href') == '' ? "" : "/"+$(this).data('href');
			window.location.href = "http://www.trendhunter.com/randomizer"+rLink;
		}
	});
	

	$('.statLink').on('click',function(){
		$('body,html').animate({
			scrollTop: $(".ratingsBoxExtra").position().top - 300
		}, 953);

		/*if($('.ratingsBoxExtra').length == 0){
			$('body,html').animate({
				scrollTop: $(document).height() - 400
			}, 953);
		}else{
			$('body,html').animate({
				scrollTop: $(".relatedHeader").position().top - 300
			}, 953);
		}*/
	});
	
	$('.header .searchForm input[name="search"]').on('keyup',_th_tagSearch);
	
	$('.header').on('click','.uMenu', function(){
		if(window.innerWidth <= 767 ){
			window.location.href = $('.uMenuDropdown li a')[0].href;
		}else{
			$('.header .uMenuDropdown').fadeToggle();
		}
	});
	
	$(window).on('scroll',function(){_th_handleScroll();});
	
	$('.mainGallery').on('click','.galleryResize',function(e){
		e.stopPropagation()
		$('.mainGallery .mainImage').toggleClass('toFit');
		
	});

	$('.mainGallery .next').on('click',_th_galleryNext);
	$('.mainGallery .previous').on('click',_th_galleryPrev);
	
	$(document).on('keydown', function(e){
		//37 left
		//39 right
		var keycode = (e.keyCode ? e.keyCode : e.which);
		
		if(keycode == 37){
			if($('.mainGallery .previous:visible').length > 0){
				_th_galleryPrev();
				_th_trackEvent('arrowKey','left');
				
			}
			return false;
		}else if(keycode == 39){
			if($('.mainGallery .next:visible').length > 0){
				_th_galleryNext();
				_th_trackEvent('arrowKey','right');
			}
			return false;
		}
		
	});
	
	$('.mainGallery .subImages img').on('click',function(){
		var gs = _th_gs;
		gs.c = $(this).data('pic');
		gs.g = $(this).data('gallery');
		_th_galleryPut()
		_th_galleryBuffer(); 		
	});
	$('.mainGallery .subImages .relatedPhotosBox').on('click',function(){_th_galleryNext();});
	
	$('body').on('click','.more', function(){_th_getMore();});
	
	if($('.mainGallery .mainImage img').length > 0){
	
		//$('.mainGallery .mainImage > img').attr('onload','_th_imgLoad();return false;').attr('onerror','_th_imgError();return false;');
	}
	
	//$('body').on('click',)
	$('body').on('close','#lightboxContent1',function(){
	});
	
	$('body').on('click','.diggieBlock ul li',function(){
	
		if(!loggedIn){
			_th_showSignUp();
			return;
		}
	
		var on = $(this).hasClass('selected'),r = $(this).data('r');
		if(r == 'f' || r == 'b' || r =='c' ){$(this).toggleClass('selected');}else{
			$('.diggieBlock .reactions li').removeClass('selected');
			if(!on){$(this).addClass('selected');}
		}
		
		if(r == 'c'){
			_th_openComments();
			return;
		}
		
		_th_react(r);
	});
	
	$('.mainGallery').on('click','.mainImage',function(){_th_galleryNext();});
	
	$('.headerButton.sToggle').on('click',function(){
	
		var showSocial = true;
		if($('.header .socialButton:visible').length > 0){
			$('.header .socialButton').hide();
			showSocial = false;
		}
	
		$('.header .searchForm').fadeToggle('fast',function(){
			if(showSocial){
				$('.header .socialButton').fadeIn('fast');	
			}
		});
		
	});
	

	$('body').on('mouseenter','.diggieToggle',function(){
			$('.diggieBlock').fadeIn('fast');	
			$('.diggieToggle').hide();
			_th_openComments();	

	});	
	
	
	$('.headerButton.socialButton').on('mouseenter',function(){
		if($('.header .socialDropdown:visible').length == 0){
			$('.header .socialDropdown').fadeToggle('fast');
			$(this).addClass('ccBg2');
		}
	}).on('mouseenter',function(){
		if($.trim($('.socialDropdown').html()).length > 0){return;}
		
		$.get(_th_ap,{ajax:true,act:'gsd'},function(r){
			if(!r.success){return;}
			$('.socialDropdown').html(r.data);
		},'json');

		
	});

	
	$('.headerMenuContainer').on('mouseleave',function(){
		if($('.searchResults:visible').length > 0 ){
			$('.searchResults').fadeOut('fast');
			$('.headerMenuContainer .search').val('');
		}
		
		if($('.socialDropdown:visible').length > 0){
			$('.header .socialDropdown').fadeOut('fast');
			$('.headerButton.socialButton').removeClass('ccBg2');
		}
		
	});
	
	$('.headerMenuContainer .search').on('focus',function(){$(this).val('');});
	
	$('.tabletMenu .tabletSearch').on('keyup',function(e){
		var key = (e.keyCode ? e.keyCode : e.which);
		if(key == 13){
			window.location.href = "http://www.trendhunter.com/results?search="+$(this).val();
		}
	});
	$('.tabletMenu select').on('change',function(){
	
		if($(this).val() == 0){return;}
	
		window.location.href = "http://www.trendhunter.com"+$(this).val();
	});
	
	/*$('.mobileSearchToggle').on('click',function(){
		$('.tabletMenu .tabletSearch').fadeToggle();
	});*/
	
	$('.mobileToggle,.mobileSearchToggle').on('click', function(){
		$('.headerTop').toggle();
		/* $('.tabletMenu .tabletSearch').toggle(); */
		$('.tabletMenu select').toggle();
		$('.socialMediaBlock').toggle();
		
		/*if($('.headerTop:visible').length > 0){$('body').css('overflow','hidden');}else{$('body').css('overflow','');}*/
		
	});
	
	
	$('.topHeader,.galleryButtons').on('mouseenter',function(){
		if(!_th_rrLoaded){_th_rrLoad();}
	}).on('click','button.headerNext' ,function(){
		if(!_th_rrLoaded){
			_th_rrLoad();

			return false;
		}
		//count 
		for(var i = 0; i < 5; i ++){
			//hide the first visible, show the next invisible
			
			if($('.topHeader li:hidden:first img').attr('src') == null 
			|| $('.topHeader li:hidden:first img').attr('src') == ''
			){
				$('.topHeader li:hidden:first img').attr('src',$('.topHeader li:hidden:first img').data('src'));
			}
			
			$('.topHeader li:hidden:first').show();
			var $old = $('.topHeader li:first').hide();
			//move $old to end of list 
			$old.remove();
			$('ul.topHeader').append($old);
		}
		
	}).on('click','button.headerPrev',function(){
		if(!_th_rrLoaded){
			_th_rrLoad();

			return false;
		}
		//move the last invisible one to the front, hide the last visible one 
		for(var i = 0; i < 5; i ++){
			$('.topHeader li:visible:last').hide();
			if($('.topHeader li:hidden:last img').attr('src') == null 
			|| $('.topHeader li:hidden:last img').attr('src') == ''
			){
				$('.topHeader li:hidden:last img').attr('src',$('.topHeader li:hidden:last img').data('src'));
			}
			var $new = $('.topHeader li:hidden:last').remove();
	
			$('ul.topHeader').prepend($new);
			$new.show();
		}
	});
	
	
	
	
	
	/*Tracking and Event Tracking*/ 
	
	$('body').on('mousedown','.topHeader li', function(){_th_trackEvent('hotbar',$(this).index());}).on('mousedown','.siteLinks a',function(){_th_trackEvent('menu',$(this).data('tracking'));}).on('mousedown','.megaMenu a,.menuPage .left a',function(){
		var href = $(this).attr('href');
		href = href.substr(href.lastIndexOf("/")+1);
		_th_trackEvent('menu-click',href);
	}).on('mousedown','.menuPage .right a',function(){_th_trackEvent('megamenu','menu-item');}).on('mousedown','.sidebarGallery li',function(){_th_trackEvent('trends-related-small',$(this).index());}).on('mousedown','.featuredSlideshow',function(){_th_trackEvent('toplists-featured',$(this).index());}).on('mousedown','.magazineTrend:not(.featuredSlideshow)',function(){
		if($(this).parents('.relatedContainer.first').length > 0){
			_th_trackEvent('trends-related', $(this).index()+1);
		}else{
			//get offset 
			var offset = $('.relatedContainer.first .magazineTrend').length + $(this).parents('.contentMain').data('offset') + $(this).index()+1;
			_th_trackEvent('trends-related',offset);
		}
	}).on('mousedown','.sidebarTrend',function(){
		var offset = $(this).parents('.contentSidebar').data('offsetsidebar') + $(this).index();
		_th_trackEvent('trends-related-sidebar',offset);
	}).on('mousedown','.socialMediaBlock li', function(){_th_trackEvent('social-media-click',$(this).attr('class'));}).on('mousedown','.diggieBlock li',function(){_th_trackEvent('reaction',$(this).data('r'));}).on('mousedown','.thProperty',function(){_th_trackEvent('th-ad-click',$(this).find('a').attr('href'));}).on('mousedown','.randomBlock .randomHide div.imgButton',function(){_th_trackEvent('randomizer',$(this).data('href'));}).on('mousedown','.randomBlock .triangle',function(){_th_trackEvent('randomizer','next-trends');}).on('mousedown','.randomBlock .randomizer-2013',function(){_th_trackEvent('randomizer','random-button');}).on('mousedown','.subscribeBox .submit',function(){_th_trackEvent('newsletter-subscribe',$(this).siblings('input[type="text"]').val());}).on('mousedown','.subscribeBox .socialLinks a',function(){_th_trackEvent('TH-social',$(this).attr('href'));}).on('mousedown','.thProperty a',function(){_th_trackEvent('TH-ad',$(this).attr('href'));}).on('mousedown','.statLink',function(){_th_trackEvent('more-stats','scroll-down');}).on('mousedown','.ratingsBox3 a',function(){_th_trackEvent('demographics-link',$(this).attr('href'));}).on('mousedown','.aboutSocialLinks a',function(){_th_trackEvent('TH-social',$(this).attr('href'));}).on('mousedown','.galleryButtons span',function(){_th_trackEvent('hotbar-button',$(this).attr('class'));}).on('mousedown','.toplistsFeatured > div',function(){_th_trackEvent('toplists-featured',$(this).index());}).on('mousedown','.ad.sad',function(){
		console.log('sponsored click');
		_th_trackEvent('sponsored-ad-click',window.location.href);
	});
	
	
});

//if it's bubbling up from an iframe
var _th_sponsoredClick = function(){
	_th_trackEvent('sponsored-ad-click',window.location.href);
	console.log('sponsored ad click '+window.location.href);
}


var _th_checkAmazon = function(){
	if($('.mainGallery').length == 0){return;}
	
	$('.mainGallery .amazonBuyNow').remove();
	
	var gd = _th_galleryData[_th_entry][_th_gs.g],
	ru = gd.ru,
	su = gd.su,
	c = $('.galleryHeader').length > 0 && $('.galleryHeader').html().length > 0 ? ' gHead ' : '' ;
	
	
	
	if(ru.indexOf('tag=trenhunt0f-20') !== -1 ){		
		$('.mainGallery').append("<a href='"+ru+"' target='_blank' rel='nofollow' class='amazonBuyNow ccBg "+c+"'>Buy at Amazon.com</a>");
	
		if(_th_gs.g == 0 && $('.amazonBuyNowText').length == 0){
			$('.articleRatingsContainer').before("<br><br><a href='"+ru+"' target='_blank' rel='nofollow' class='amazonBuyNowText ccBg "+c+"'>Buy at Amazon.com</a>");
		}
	
	}else if(su.indexOf('tag=trenhunt0f-20') !== -1){
		$('.mainGallery').append("<a href='"+su+"' target='_blank' rel='nofollow' class='amazonBuyNow ccBg "+c+"'>Buy at Amazon.com</a>");
		
		if(_th_gs.g == 0 && $('.amazonBuyNowText').length == 0){
			$('.articleRatingsContainer').before("<br><br><a href='"+su+"' target='_blank' rel='nofollow' class='amazonBuyNowText ccBg "+c+"'>Buy at Amazon.com</a>");
		}
	
	}
	
	return; 
}

var _th_currFancy = false,
_th_checkFancy = function(){
	if(_th_fancyData.length == 0){return;}
	var gd = _th_galleryData[_th_entry], gs = _th_gs, id = gd[gs.g].id;
	
	if(_th_fancyData[id] == null){
		$('.fancyLink').remove(); 
		return;
	}

	if(_th_currFancy != id){
		_th_currFancy = id; 
		$('.fancyLink').remove();
	}else if(_th_currFancy == id && $('.fancyLink').length > 0){return;}
	
	var fancyUrl 	= _th_fancyData[id].url;
	var fancyId		= _th_fancyData[id].id;
	
	var fancyButton = "<a class='fancyLink' href='"+fancyUrl+"'><img class='fancy-id-"+fancyId+"' src='//www.trendhunter.com/images/spacer.gif' width='1' height='1' ></a>";

	
	$('.mainGallery').append(fancyButton)


		//simulate page move to trigger button
	$(window).scrollTop($(window).scrollTop()+1);
	$(window).scrollTop($(window).scrollTop()-1);
	
}


var th_sayProperties = [ "ReadyHandler", "MessageWatcher", "vetd", "vepcreg", "CookieService", "Retargeting", "Cookies", "Capping",  "smutils", "ve_UnloadManager", "ve_swfobject", "SayAdLoader", "deferred", "ve_ifdomain", "prods", "uniqueWordsOnPage", "say_parse_exelate", "say_parse_qc", "__flash__arrayToXML", "__flash__argumentsToXML", "__flash__objectToXML", "__flash__escapeXML", "__flash__toXML", "__flash__request", "__flash__addCallback", "__flash__removeCallback", "sbinvite"];
//, "veprods" "pigeon", "vepc",
function th_cleanSay(){
	for(index in th_sayProperties){
		if(typeof window[th_sayProperties[index]] != 'undefined'){
			delete window[th_sayProperties[index]];
		}
	}
	
	//#div-gpt-ad-1334586884853-728 iframe,
	$('#div-gpt-ad-1334586884853-300 iframe,#div-gpt-ad-1334586884853-300x600 iframe').each(function(i,frame){
		for(index in th_sayProperties){
			if(typeof frame.contentWindow[th_sayProperties[index]] != 'undefined'){
				delete frame.contentWindow[th_sayProperties[index]];
			}	
		}
	});
}


var _th_searchReq = null,
_th_tagSearch = function(){
	var txt = $(this).val();
	
	if(txt.length < 2){
		return false;
	}
	
	if(_th_searchReq != null){
		_th_searchReq .abort(); 
		_th_searchReq  = null;
	}
	
	_th_searchReq  = $.get('/tag_search',{q:txt},function(r){
		if($.trim(r) == ''){return;}
		$('.headerMenuContainer .searchResults').html(r).fadeIn();
		$('.searchResults tr').addClass('ccBgHover');
	}).fail(function(){
		_th_searchReq  = null;
	});

}

function th_regularRefresh(){
	googletag.pubads().refresh(th_regular_ads);
	return;
}
				
//refreshes next ad based on th_adQueue
function th_loadNextAd(){
	if(th_adQueue.length == 0){return;}
	var chosenSlot = th_adQueue.shift();
	th_adQueue.push(chosenSlot);
	console.log('cleaning say media');
	th_cleanSay();
	console.log('refreshing');
	console.log([chosenSlot]);
	googletag.pubads().refresh([chosenSlot]);
}

var _th_socialScripts = false;
var _th_loadSocial = function(){
	if(!_th_socialScripts){
		var d = document, s = 'script', id = 'facebook-jssdk';
		
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) return;
		js = d.createElement(s); js.id = id;
		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=85925738555";
		fjs.parentNode.insertBefore(js, fjs);
		_th_socialScripts = true;
	}else{FB.XFBML.parse();}
}

var _th_openComments = function(r){
	if($.trim($('.commentBlock').html()) == ""){
		var url = window.location.origin+window.location.pathname;
		$('.commentBlock').html("<div class='fb-comments' data-href='"+url+"' data-width='640' data-num-posts='10'></div>");
		_th_loadSocial();
	}
	$('.commentBlock').fadeToggle();
}

var _th_react = function(r){
	$.post(_th_ap,{ajax:true,act:'r',r:r, e:_th_entry},function(r){
		if(!r.success){return;}
	},'json');
}

var _th_getMore = function(){
	_th_gettingMore = true;
	$thisButton = $('.more');
	$thisButton.addClass('loading');
	var id = $thisButton.parents('.wrapper').data('id');
	relPage = relPage + 1;
	
	_gaq.push(['_trackPageview', '/'+_th_view+'/'+_th_url]);
	_th_trackEvent('related-page-load',relPage);
	var params = relPage > 1 ? {ajax:true,act:'rr',c:_th_category,p:relPage} : {ajax:true,act:'rr',id:id,p:relPage,c:_th_category};
	$.get(_th_ap,params,function(r){
		$thisButton.removeClass('loading');
		_th_gettingMore = false;
		if(!r.success){
			relPage = relPage - 1;
			alert(r.data);
			return false;
		}
		
		$('.wrapper .more').before(r.data);
	
		
		return false;
	},'json').fail(function(jqXHR, textStatus, errorThrown){
		relPage = relPage - 1;
		$thisButton.removeClass('loading');
		//alert('Error getting more trends');
	});				
}

var _th_debug = false;
var _th_getMemberInfo = function(){
	//ajax for member data
	var params = {ajax:true,act:'mi',e:_th_entry};
	
	/*if($_GET['ca'] != null){
		params['ca'] = $_GET['ca'];
	}*/
	
	
	$.post(_th_ap,params,function(r){		
		loggedIn = !r.success || !r.data.loggedIn ? false : true; 
		
		if(params['ca'] != null && r.data.corporateAccount != null){
			$('.wrapper').prepend(r.data.corporateAccount);		
			$('.corporateNotification').fadeIn().on('click','.close',function(){$(this).parents('.corporateNotification').remove();});
			
		}
		
		if(!loggedIn){
			
			if(navigator.cookieEnabled && _th_readCookie('TrendhunterPopup') == null && params['ca'] == null){
				//show the signup pop up 
				//setTimeout(showSignUp,1500);
				$('.wrapper').on('click',_th_showSignUp);
				//set the cookie
			}
		}else{
			$('.userLinks .addTrend').attr('href','http://www.trendhunter.com/submit').html('Add a Trend');
			
			if(r.data.username && r.data.username == 'drcohen'){
				_th_debug = true;
			}
			
			
			if(r.data.menu && $('.userLinks .userMenu').length == 0){
				//make dropdown
				$('.userLinks').prepend(r.data.menu);

				$('.aboutUsLink').hide();
				$('.userLogin').hide();
				$('.siteLinks li.userLogout').removeClass('mobileHide')
				$('.userMenu').fadeIn('fast');


			}	
		
			if(r.data.favorite){
				$('.diggieBlock .favorite li').addClass('selected');
			}
			
			if(r.data.reaction){
				$('.diggieBlock .reactions li[data-r="'+r.data.reaction+'"]').addClass('selected');
			}
			
			if(r.data.bookmark){
				$('.diggieBlock .bookmark li').addClass('selected');
			}
		}					
	},'json');
}



var _th_$lb = null;
var _th_showSignUp = function(){
	$('.wrapper').off('click');
	_th_setCookie('TrendhunterPopup',true,1);

	if(window.innerWidth < 1105){return;}
	
	if(_th_signupLoaded && typeof showpopup == 'function' ){
		showpopup();
		return;
	}
	$.get("/lightboxNew_js",function(){
		$.get("/master-js-2012",function(){
			_th_signupLoaded = true;
			showpopup(); 
		});		
	});

}


var _th_readCookie = function(name){

	if(!navigator.cookieEnabled){
		return null;
	}

	name += '=';
	var parts = document.cookie.split(/;\s*/);
	for (var i = 0; i < parts.length; i++){
		var part = parts[i];
		if (part.indexOf(name) == 0){
			return part.substring(name.length);
		}	
	}
	return null;
}
var _th_setCookie = function(c_name,value,expiredays){
	expiredays = 3; 
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString())+"; path=/";
} 


var _th_isVisibleInViewport = function(elem){
    var y = elem.offsetTop;
    var height = elem.offsetHeight;

    while ( elem = elem.offsetParent )
        y += elem.offsetTop;

    var maxHeight = y + height;
    var isVisible = ( y < ( window.pageYOffset + window.innerHeight ) ) && ( maxHeight >= window.pageYOffset );
    return isVisible; 

}

var _th_handleScroll = function(){				
	if(!_th_gettingMore){
		if(relPage == 0 && (window.pageYOffset > 953 || $(document).height() < 953 || _th_isVisibleInViewport($('.more')[0]))){
			//load the first related
			$('.more').trigger('click');
		}else if(relPage > 0){
			//if the more is scrolled into view trigger the click 
			if(_th_isVisibleInViewport($('.more')[0])){$('.more').trigger('click');}
		}
	}
	

	

	
	if($('.box600.box.sbox').length > 0 || $('.relatedContainer.first').length == 0){return;}
	
	if($('.boxStop').length > 0 && window.pageYOffset + window.innerHeight > $('.boxStop').position().top){$('.box.box600').addClass('fixedBottom').removeClass('fixed').css('bottom',"-"+$('.relatedContainer').height()+"px");}else if(window.pageYOffset > ($('.box600Container').position().top +600) && $('.relatedContainer').length > 0){$('.box.box600').addClass('fixedBox').removeClass('fixedBottom').css('bottom','');}else{$('.box.box600').removeClass('fixedBox').removeClass('fixedBottom').css('bottom','');}	



}			

var _th_galleryNext = function(){	

	var timestamp = new Date().getTime();
	if(timestamp - _th_lastClick <= _th_clickDelay ){
		return false;
	}
	_th_lastClick = timestamp;

	$('.mainGallery .subImages').remove();

	var gd = _th_galleryData[_th_entry];				
	
	/*if(!_th_imgLoaded){	
		console.log("Image not loaded click didn't go through");
		setTimeout(function(){_th_imgLoaded = true;},1000);
		return false;
	}*/
	
	_th_imgLoaded = false; 
	var gs = _th_gs;
	if(_th_view != 'slideshow' && _th_view != 'course'){
		gs.c += 1; 
		if(gs.c > gd[gs.g].p){
			gs.c = 1;
			gs.g += 1; 
			if(gs.g >= gd.length){
				gs.g = 0;
			}
		}
	}else{
		gs.g = gs.g == 0 ? gs.g = 1 : gs.g;
		//increment the gallery not the counter
		gs.g += 1;
		if(gs.g >= gd.length){
			gs.g = 1;
		}
	}
	_th_galleryPut();
	_th_galleryBuffer();
	
}


var _th_galleryPrev = function(){

	var timestamp = new Date().getTime();
	if(timestamp - _th_lastClick <= _th_clickDelay ){
		return false;
	}
	_th_lastClick = timestamp;


	$('.mainGallery .subImages').remove();
	var gd = _th_galleryData[_th_entry];
	/*if(!_th_imgLoaded){
		setTimeout(function(){_th_imgLoaded = true;},1000)
		return false;
	}*/
	
	_th_imgLoaded = false;
	var gs = _th_gs;

	if(_th_view != 'slideshow' && _th_view != 'course'){
		gs.c -= 1;
		if(gs.c < 1){
			gs.g -= 1;
			if(gs.g < 0){
				gs.g = gd.length - 1;
			}
			gs.c = gd[gs.g].p;
		}
	}else{
		gs.g -= 1;
		if(gs.g <= 0){
			gs.g = gd.length - 1;
		}
	}
	_th_galleryPut();

	_th_galleryBuffer();
}	

var _th_pageLoad = new Date().getTime(), lastAdLoad1 = 0, lastAdLoad2 = 0, 
_th_changeAds = function(){
	var timestamp = new Date().getTime();
	
	if(timestamp < _th_pageLoad + adStartDelay){
		return false;
	}

	//console.log("1. time: "+timestamp+" lastAd: "+lastAdLoad1+" diff: "+(timestamp - lastAdLoad1)+" delay: "+adDelay1);
	if(timestamp - lastAdLoad1 > adDelay1 ){
		lastAdLoad1 = timestamp;
		th_regularRefresh(); 
	}
	
	//console.log("2. time: "+timestamp+" lastAd: "+lastAdLoad2+" diff: "+(timestamp - lastAdLoad2) +" delay: "+adDelay2);
	if(timestamp - lastAdLoad2 > adDelay2){
		lastAdLoad2 = timestamp;
		th_loadNextAd();
	}

}

var _th_galleryPut = function(){
	var gd = _th_galleryData[_th_entry],
	gs = _th_gs;

	id = gd[gs.g].id,
	imgSrc = _th_imgHost+"/phpthumbnails/"+Math.floor(id/1000)+"/"+id+"/"+id+"_"+gs.c+"_800.jpeg";
	
	$('.mainImage').removeClass('toFitWide');
	
	
	var ret = false;
	
	if(_th_view == 'slideshow' || _th_view == 'course'){
		
		
		if(gs.g > gd.length/2 && !_th_rrLoaded){_th_rrLoad();}
		
		
		
		_th_changeSlideInfo();

		if(_th_view == 'course'){		
			if($.trim(gd[gs.g].sv) != ''){
				$('.mainGallery .mainImage').html("<div class='articleVideo youtube'><iframe wmode='transparent' width='460' height='290' src='http://www.youtube.com/embed/"+gd[gs.g].sv+"?wmode=opaque&mp;showinfo=0' style='border:none;' allowfullscreen></iframe></div>");
				_th_imgLoaded = true;
				ret = true;
				return;
			}else if($.trim(gd[gs.g].vi) != ''){
				$('.mainGallery .mainImage').html("<div class='articleVideo'>"+gd[gs.g].vi+"</div>");
				_th_imgLoaded = true;
				ret = true;
				return; 
			}
		}
	}else if(_th_view == 'trends'){
		if(gs.g > gd.length/2 && !_th_rrLoaded){_th_rrLoad();}
		_th_changeGalleryInfo();

	}else{_th_changeGalleryInfo();}
	
	if(ret == false){
	
		if($('.mainGallery .mainImage img').length == 0){
			$('.mainGallery .mainImage').html("<button type='button' class='galleryResize'></button><img src='' class='ccBorderHover' width='600' height='300'/>");
		}
		
		$('.mainGallery .mainImage img').remove();
		$('.mainGallery .mainImage').append("<img src='"+imgSrc+"' class='ccBorderHover'/>");
	}
	
	_th_changeAds();
	_th_checkFancy();
	_th_checkAmazon(); 
	_th_trackView();
	_th_trackEvent('view-tracking','page-click-'+_th_view);
}
var _th_trackingCount = 1;
var _th_trackView = function(){
	if($('.trackingPixels').length == 0){
		$('.articleBody').before("<div class='trackingPixels'></div>");
	}
	if($('.trackingIframe').length == 0){
		$('.articleBody').before("<div class='trackingIframe'></div>");
	}
	
	_th_trackingCount += 1;
	
	_gaq.push(['_trackPageview', '/'+_th_view+'/'+_th_url]);
	var img = new Image();
	img.src = 'http://live.trendhunter.com/trackingpixel?entry_id='+_th_entry+'&_t='+new Date().getTime();
	$('.trackingPixels').append(img);	
	
	/*	
	$('.trackingIframe').html("<iframe src='http://www.trendhunter.com/trends-iframe-lite.php/"+_th_url+"' height='10' width='300' scrolling='no' frameborder='0' allowTransparency='true' style='border:none; overflow:hidden; display:inline;'></iframe>");
	*/
	
	$('.quantTags').append('<img src="//pixel.quantserve.com/pixel/p-e60YSoLxat1s2.gif" style="border:0px;float:left;" height="1" width="1" alt="Quantcast"/>');
}

var _th_changeGalleryInfo = function(){
	if($('.mainGallery .galleryHeader').length == 0 || $('.mainGallery .galleryFooter').length == 0){return;}
	var gs = _th_gs;

	var gd = _th_galleryData[_th_entry][gs.g];

	if(gd['id'] == _th_entry){
		$('.mainGallery .galleryHeader').empty();
		$('.mainGallery .galleryFooter').empty();
		return;
	}
	
	var headerHtml = "";
	headerHtml += "<a class='ccHover' href='/"+gd['v']+"/"+gd['u']+"'>Related > "+gd['t1']+"</a> > Photo "+gs.c;
	$('.mainGallery .galleryHeader').html(headerHtml);
	var footerHtml = ""; 
	
	if(gd.su != ''){
		footerHtml += "<a  class='ccHover' target='_blank' href='"+gd.su+"' >"+gd.s+"</a>";
	}
	
	if(gd.ru != ''){
		if(gd.su != ''){
			footerHtml += ", ";
		}
		footerHtml += "<a class='ccHover'  target='_blank' href='"+gd.ru+"'>"+gd.r+"</a>"
	}
	$('.mainGallery .galleryFooter').html(footerHtml);
	
	
}

var _th_rrLoad = function(){

	var params = {ajax:true,act:'gse',e:_th_entry};
	$.get(_th_ap,params,function(r){
		_th_rrLoaded = true;

		if(!r.success){
			return false;
		}

		if(_th_view == 'slideshow' || _th_view == 'trends'){
			_th_galleryData[_th_entry] = _th_galleryData[_th_entry].concat(r.data);
		}
		
		if($('ul.topHeader:visible').length > 0){
			var html = "";
			for(i in r.data){
				var t = r.data[i];
				
				var url = "/"+t.v+"/"+t.u;
				var imgSrc = _th_imgHost+"/phpthumbnails/"+Math.floor(t.id/1000)+"/"+t.id+"/"+t.id+"_1_230c.jpeg";
				html += "<li style='display:none;' ><a  class='ccHover' href='"+url+"'>"
				+"<div class='imgContainer ccBorderHover'><img data-src='"+imgSrc+"' src='' width='230' height='150'/></div>"
				+"<span class='title1'>"+t.t1+"</span></a></li>";
				
			}
			
			$('ul.topHeader').append(html);
		
		}
		return false;
	},'json').fail(function(jqXHR, textStatus, errorThrown){});}

var _th_slideCount = _th_galleryData[_th_entry].length;
var _th_changeSlideInfo = function(){
	var gs = _th_gs;
	var si = _th_galleryData[_th_entry][gs.g];
	
	var countDown = typeof _th_countDown == 'undefined' || _th_countDown == false ? false : true;
	
	if(gs.g >= _th_slideCount){
		$('.slideInfo .number').html('+');
	}else{
		var newNum = countDown ? _th_slideCount - gs.g : gs.g;
		
		$('.slideInfo .number').html('#'+newNum);
	}
	$('.slideInfo .title1').html(si.t1);
	$('.slideInfo .title2').html(si.t2);
	$('.slideInfo a').attr('href',"/"+si.v+"/"+si.u);
	var imgHtml = "", iter = si.p < 3 ? si.p : 3; 

	for(var i = 1; i <= iter; i++){
		var imgSrc = _th_imgHost+"/phpthumbnails/"+Math.floor(si.id/1000)+"/"+si.id+"/"+si.id+"_"+i+"_80.jpeg";
		imgHtml += "<img width='80' height='80' src='"+imgSrc+"' />";
	}
	$('.slideInfo .slideImages').html(imgHtml);
	
}

var _th_imgLoad = function(){
	//console.log('image finished');
	_th_imgLoaded = true;
}
var _th_imgError = function(){
	_th_imgLoaded = true;
}
var _th_buffered = {};
var _th_galleryBuffer = function(){
	if($('.mainGallery .galleryBuffer').length == 0){
		return false;
	}
	
	//load all the images from the current trend into the buffer 
	var gd = _th_galleryData[_th_entry],
	gs = _th_gs,
	cur = gd[gs.g],
	id = cur.id,
	pc = cur.p,
	sb = typeof _th_sb == 'undefined' ? 10 : _th_sb;
	
	if(_th_view == 'slideshow' || _th_view == 'course'){
		
		var currentlyOn = gs.g == 0 ? 1 : gs.g;
		
		var iter = Math.min(sb + 1, gd.length - 1 - currentlyOn);
		
		//buffer the next 10 or up to how many there are
		for(var i = currentlyOn; i < currentlyOn+iter; i++){
						
			if(gd[i] == null){break;}
			//$('.mainGallery .galleryBuffer [data-id='+gd[i].id+']').length == 0			
			if(_th_buffered[gd[i].id] == null){
				var imgSrc = _th_imgHost+"/phpthumbnails/"+Math.floor(gd[i].id/1000)+"/"+gd[i].id+"/"+gd[i].id+"_1_800.jpeg";
				
				var img = new Image(); 
				img.src = imgSrc;
				
				_th_buffered[gd[i].id] = [];
				_th_buffered[gd[i].id].push(img);
				
				//$('.mainGallery .galleryBuffer').append("<img data-id='"+gd[i].id+"' src='"+imgSrc+"' />");
			}
		}
		
		
	}else{
		//$('.mainGallery .galleryBuffer [data-id="'+id+'"]').length == 0
		if(_th_buffered[id] == null){
			_th_buffered[id] = [];
			//buffer this gallery 
			var iter = pc;
			for(var i = 1; i <= iter; i++){
				var imgSrc = _th_imgHost+"/phpthumbnails/"+Math.floor(id/1000)+"/"+id+"/"+id+"_"+i+"_800.jpeg";
				var img = new Image(); 
				img.src = imgSrc;
				_th_buffered[id].push(img);
				
				//$('.mainGallery .galleryBuffer').append("<img data-id='"+id+"' src='"+imgSrc+"' />");
			}
		}
		
		//buffer the next gallery if we're on the last image of the current gallery
		var nextG = gs.g + 1;
		//$('.mainGallery .galleryBuffer [data-id="'+gd[nextG].id+'"]').length == 0
		if(gd[nextG] != null && _th_buffered[gd[nextG].id] == null){
			var iter = gd[nextG].p;
			_th_buffered[gd[nextG].id] = [];
			for(var i = 1; i <= iter; i++){
				var imgSrc = _th_imgHost+"/phpthumbnails/"+Math.floor(gd[nextG].id/1000)+"/"+gd[nextG].id+"/"+gd[nextG].id+"_"+i+"_800.jpeg";
				
				var img = new Image(); 
				img.src = imgSrc;
				_th_buffered[gd[nextG].id].push(img);
				
				//$('.mainGallery .galleryBuffer').append("<img data-id='"+gd[nextG].id+"' src='"+imgSrc+"' />");
			}	
		}
		
		
	}

}

//tracking
/*var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-630126-1']);
_gaq.push(['_setDomainName', 'www.trendhunter.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.locatamaion.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();*/
//	setTimeout("_gaq.push(['_trackEvent','15_seconds','read'])",15000);


/*var _qevents = _qevents || [];

(function() {
	var elem = document.createElement('script');
	elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js";
	elem.async = true;
	elem.type = "text/javascript";
	var scpt = document.getElementsByTagName('script')[0];
	scpt.parentNode.insertBefore(elem, scpt);
})();

_qevents.push({qacct:"p-e60YSoLxat1s2"});*/