var rotatingList = function(el) {
	this.list = null;
	this.items = null;
	this.active = null;
	this.timer = null;
	this.init(el);
};

rotatingList.prototype.init = function(el) {
	this.list = el;
	this.items = $(this.list).children('li');
	this.showItem(0);
	this.startTimer();
	var self = this;
	$(this.list).hover(function(){clearTimeout(self.timer);self.showList();},function(){self.hideList();self.showItem(0);self.startTimer();});
};

rotatingList.prototype.showItem = function(idx) {
	this.active = idx;
	$(this.items).each(function(i,el){(i==idx)?$(el).show():$(el).hide();});
};

rotatingList.prototype.showList = function() {
	$(this.list).addClass('active');
	$(this.items).each(function(i,el){$(el).show();});
};

rotatingList.prototype.hideList = function() {
	$(this.list).removeClass('active');
};

rotatingList.prototype.startTimer = function() {
	var self = this;
	i = (this.active+1==this.items.length)?0:this.active+1;
	this.timer = setTimeout(function(){self.showItem(i);self.startTimer();},5000);
};

function h() {
	var browserWidth = screen.width;
	// alert (browserWidth);
	if (browserWidth >= 1000){
	  $("#column-inner").length > 0 && ($(window).scrollTop() > $("#column-inner").height() + $("#column-inner").offset().top ? (
	        $("#column-inner .item-skyscraper").css({
	        position: "fixed",
	        top: "15px"
	    })) : $("#column-inner, .item-skyscraper").css({
	        position: "static",
	        top: "auto"
	    }))
	}
}

$(document).ready(function(){
    $(window).scroll(function () { h(); });
	// initRotatingList();
	var rl = new rotatingList( $('#header-our-cities .list') );
	var dr = new DetectReferrer( $('#WelcomePlaceHolder'));
	
    // $("li.fav-item a").hover(function() {
    //  $('> div', this).stop().fadeIn("fast");
    // }, function() {
    //  $('> div', this).stop().css({opacity:1}).fadeOut("fast");
    // });

	$('.eyecon').hover(function() {
        $(this).next().fadeIn(70); 
	}, function() {
		$(this).next().hide();
    });

	$("#tipsMessage").click(function(){
		$(".item-email-from").slideDown(1000);
	});
	$('#mobilesitevisit').click(function(){
		$.cookie('mobilepreference',null,{path: '/', domain: hostname});
	});
	
	$("li.fav-item-c a").hover(function() {
		$('> div', this).css("background-color","rgba(170,0,0,0.7)")
	}, function() {
		$('> div', this).css("background-color","rgba(0,0,0,0.7)")
	});
	
	// $("li a.pretty").click(function() {indexView("pretty"); return false; });
	// $("li a.blog").click(function() {indexView("blog"); return false; });
	$(".tipsSubmit").click(function(){					   				   
			$(".error").hide();
			var hasError = false;
			var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

			var emailFromVal = $("#tipsFrom").val();
			if(emailFromVal == '') {
				$("#tipsFrom").after('<span class="error">You forgot to enter the email address to send from.</span>');
				hasError = true;
			} else if(!emailReg.test(emailFromVal)) {	
				$("#tipsFrom").after('<span class="error">Enter a valid email address to send from.</span>');
				hasError = true;
			}

			var messageVal = $("#tipsMessage").val();
			if(messageVal == '') {
				$("#tipsMessage").after('<span class="error">You forgot to enter the message.</span>');
				hasError = true;
			}


			if(hasError == false) {
				$(this).hide();
				$("#item-email-form .item-email-submit").append('<img src="http://labs.gothamistllc.com/images/progress_circle.gif" alt="Loading" id="loading" />');

				$.post("/includes/form/sendemail.php",
	   				{ emailFrom: emailFromVal, message: messageVal },
	   					function(data){
							$("#item-email-form").slideUp("normal", function() {				   

								$("#item-email-form").before('<h1>Success!</h1><p>Your tip was sent. We will follow up with you as soon as possible.</p>');											
							});
	   					}
					 );
			}

			return false;
		});

	$(function() {
   		$('body.hawaii #takeoverHeaderAd').delay(7000).fadeOut("slow");
	});
	$("body.sfist.hawaii #container").click(function(event){
         event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/hawaii_sfist_background']);
         window.open('http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=tf&c=20&mc=click&pli=3438889&PluID=0&ord=[timestamp]');
     });
	$("body.sfist.hawaii #takeoverHeaderAd").click(function(event){
		_gaq.push(['_trackPageview', '/outgoing/hawaii_sfist_header']);
         window.open('http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=tf&c=20&mc=click&pli=3438889&PluID=0&ord=[timestamp]');
     });
     $('body.sfist.hawaii #container-inner').click(function(event){
         event.stopPropagation();
     });

	$(function() {
   		$('body.dcunited #takeoverHeaderAd').delay(7000).fadeOut("slow");
	});
	$("body.dcist.dcunited #container").click(function(event){
         event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/dcunited_dcist_background']);
         window.open('http://www.dcunited.com/tickets?utm_source=DCist&utm_medium=Takeover&utm_campaign=NY');
     });
	$("body.dcist.dcunited #takeoverHeaderAd").click(function(event){
		_gaq.push(['_trackPageview', '/outgoing/dcunited_dcist_header']);
         window.open('http://www.dcunited.com/tickets?utm_source=DCist&utm_medium=Takeover&utm_campaign=NY');
     });
     $('body.dcist.dcunited #container-inner').click(function(event){
         event.stopPropagation();
     });

	$(function() {
   		$('body.walkernyc #takeoverHeaderAd').delay(7000).fadeOut("slow");
	});
	$("body.gothamist.walkernyc #container").click(function(event){
         event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/walkernyc_gothamist_background']);
         window.open('http://ad.doubleclick.net/clk;250161380;69740460;b');
     });
	$("body.gothamist.walkernyc #takeoverHeaderAd").click(function(event){
		_gaq.push(['_trackPageview', '/outgoing/walkernyc_gothamist_header']);
         window.open('http://ad.doubleclick.net/clk;250161380;69740460;b');
     });
     $('body.gothamist.walkernyc #container-inner').click(function(event){
         event.stopPropagation();
     });

	$(function() {
   		$('body.walkerdc #takeoverHeaderAd').delay(7000).fadeOut("slow");
	});
	$("body.dcist.walkerdc #container").click(function(event){
         event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/walkerdc_dcist_background']);
         window.open('http://ad.doubleclick.net/clk;245442501;69740367;i');
     });
	$("body.dcist.walkerdc #takeoverHeaderAd").click(function(event){
		_gaq.push(['_trackPageview', '/outgoing/walkerdc_dcist_header']);
         window.open('http://ad.doubleclick.net/clk;245442501;69740367;i');
     });
     $('body.dcist.walkerdc #container-inner').click(function(event){
         event.stopPropagation();
     });

	$(function() {
   		$('body.walkerla #takeoverHeaderAd').delay(7000).fadeOut("slow");
	});
	$("body.laist.walkerla #container").click(function(event){
         event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/walkerla_laist_background']);
         window.open('http://ad.doubleclick.net/clk;245734509;69740515;p');
     });
	$("body.laist.walkerla #takeoverHeaderAd").click(function(event){
		_gaq.push(['_trackPageview', '/outgoing/walkerla_laist_header']);
         window.open('http://ad.doubleclick.net/clk;245734509;69740515;p');
     });
     $('body.laist.walkerla #container-inner').click(function(event){
         event.stopPropagation();
     });

	$(function() {
   		$('body.walkersf #takeoverHeaderAd').delay(7000).fadeOut("slow");
	});
	$("body.sfist.walkersf #container").click(function(event){
         event.stopPropagation();
		_gaq.push(['_trackPageview', '/ouutgoing/walkersf_sfist_background']);
         window.open('http://ad.doubleclick.net/clk;245734324;69740989;z');
     });
	$("body.sfist.walkersf #takeoverHeaderAd").click(function(event){
		_gaq.push(['_trackPageview', '/outgoing/walkersf_sfist_header']);
         window.open('http://ad.doubleclick.net/clk;245734324;69740989;z');
     });
     $('body.sfist.walkersf #container-inner').click(function(event){
         event.stopPropagation();
     });

	$("body.austinist.car2go #container").click(function(event){
		event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/car2go_austinist_background']);
         window.open('http://www.austincar2go.com/');
     });
     $('body.austinist.car2go #container-inner').click(function(event){
         event.stopPropagation();
     });

	$("body.gothamist.citipond #container").click(function(event){
		event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/citipond_gothamist_background']);
         window.open('http://clk.atdmt.com/NYC/go/370041680/direct;at.64_REW_CTX_LOR_RTO_NYC_GTMS_Skin29AV1400x675_x_1x1_STD_370041680;ct.1/01/');
     });
     $('body.gothamist.citipond #container-inner').click(function(event){
         event.stopPropagation();
     });
     
     $("body.chicagoist.seamless #container").click(function(event){
 		event.stopPropagation();
 		_gaq.push(['_trackPageview', '/outgoing/seamless_chicagoist_background']);
          window.open('http://clk.atdmt.com/481/go/370919727/direct/01/');
      });
      $('body.chicagoist.seamless #container-inner').click(function(event){
          event.stopPropagation();
      });

	$(function() {
   		$('body.nycbroadway #takeoverHeaderAd').delay(7000).fadeOut("slow");
	});
	$("body.gothamist.nycbroadway #container").click(function(event){
         event.stopPropagation();
		_gaq.push(['_trackPageview', '/outgoing/nycbroadway_gothamist_background']);
         window.open('http://ad.doubleclick.net/click;h=v2|3EBD|0|0|%2a|w;251087713;0-0;0;75550274;31-1|1;45792552|45809885|1;;%3fhttp://www.nycgo.com/offbroadwayweek');
     });
	$("body.gothamist.nycbroadway #takeoverHeaderAd").click(function(event){
		_gaq.push(['_trackPageview', '/outgoing/nycbroadway_gothamist_header']);
         window.open('http://ad.doubleclick.net/click;h=v2|3EBD|0|0|%2a|w;251087713;0-0;0;75550274;31-1|1;45792552|45809885|1;;%3fhttp://www.nycgo.com/offbroadwayweek');
     });
     $('body.gothamist.nycbroadway #container-inner').click(function(event){
         event.stopPropagation();
     });



        
     $('#newtab').click(function () {
         if ($(this).is(':checked')) {
            document.cookie = 'tabPreference=;expires=Thu, 10 Jan 1970 00:00:01 GMT;path=/'; 
         } else {
            var expdate = new Date(); 
            expdate.setTime(expdate.getTime() + 1000 * 60 * 60 * 24 * 30);
            document.cookie = 'tabPreference=notab;expires=' + expdate + ';path=/';
         }
     });
     
     $(function() {
     if(document.cookie.indexOf('tabPreference') != -1) {
        $("#newtab").removeAttr("checked");
     }
 });
     $("a[href^=http]").each(function(){
           if((this.href.indexOf(location.hostname) == -1) && (document.cookie.indexOf('tabPreference') == -1)) {
              $(this).attr({
                 target: "_blank",
                 title: "Opens in a new window"
              });
           }
        })



});

function viewBeta(view){
	var expdate = new Date(); 
	expdate.setTime(expdate.getTime() + 1000 * 60 * 60 * 24 * 30);
	if (view == 'beta') {
		document.cookie = 'betaPreference=beta;domain=.gothamist.com;expires=' + expdate + ';path=/';
	} else if (view == 'old'){
		document.cookie = 'betaPreference=;domain=.gothamist.com;expires=Thu, 01-Jan-70 00:00:01 GMT;';
	}
	window.location.reload();
}
function indexView(view){
	var expdate = new Date(); 
	expdate.setTime(expdate.getTime() + 1000 * 60 * 60 * 24 * 30);
	if (view == 'pretty') {
		document.cookie = 'indexPreference=pretty;expires=' + expdate + ';path=/';
		// window.location.href = 'pretty.php';
	} else if (view == 'blog') {
		document.cookie = 'indexPreference=blog;expires=' + expdate + ';path=/';
		// window.location.href = 'blog.php';
	} else if (view == 'popular') {
		document.cookie = 'indexPreference=popular;expires=' + expdate + ';path=/';
	}
	window.location.reload();
}
jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();

var hostname = jQuery.url.attr("host");

if(jQuery.url.attr("host") == 'gothamist.com'){ 
      var sitename = 'It seems you\'ve come to Gothamist via a web search. Please consider <a href="#" onclick="addBookmark(\'http://'+hostname+'\', \''+hostname+'\'); return false;">bookmarking us</a>, <a href="/index.rdf">subscribing to our RSS feed</a>, or checking out <a href="/popular">this week\'s most popular stories</a>.</div><div style="border-top:0px solid #FFF;padding:0px 10px 10px;font-size:14px;line-height:18px"><table><tr><td width="340"><p style="margin:0;padding:0 20px 0 0">Want to know about the best events and deals in New York every day? Subscribe to our newsletter:</p></td><td><form action="http://gothamist.list-manage.com/subscribe/post" method="POST"><input type="hidden" name="u" value="1ff83f6bd9b5621949725cf98"><input class="refer_label" type="hidden" name="id" value="b4f8dc6148"><label for="MERGE0a" style="font-size:11px"><strong>EMAIL</strong> <em> (required)</em></label><br /><input class="refer_input" type="text" name="MERGE0" id="MERGE0a" size="25" value="" style="vertical-align:top;height:17px;"><input class="gothamlistSubscribe" type="image" value="subscribe" src="http://assets.gothamistllc.com/images/spacer.gif"/></form></td></tr></table>';} else { var sitename = 'It seems you\'ve come to us via a web search. Please consider <a href="#" onclick="addBookmark(\'http://'+hostname+'\', \''+hostname+'\'); return false;">bookmarking us</a>, <a href="/index.rdf">subscribing to our RSS feed</a>, or checking out <a href="/popular">this week\'s most popular stories</a>.';} 


var msgs = [
{'url':null,                           'msg':null}
,{'url':/^http:\/\/(\w+\.)?google\.com\/search/,      'msg':sitename}
,{'url':/^http:\/\/(\w+\.)?yahoo\.com/,      'msg':sitename}
,{'url':/^http:\/\/(\w+\.)?msn\.com/,      'msg':sitename}
,{'url':/^http:\/\/(\w+\.)?search.live\.com/,      'msg':sitename}
,{'url':/^http:\/\/(\w+\.)?ask\.com/,      'msg':sitename}
,{'url':/^http:\/\/(\w+\.)?aol\.com/,      'msg':sitename}
];

function DetectReferrer(){            
   var div = $('#WelcomePlaceHolder');
   //if Div was not placed means , not to show message
   if (!div.length) return;
   var ref = document.referrer.toLowerCase();
   var msg = findMatch(ref);
   // if not null msg found
   if(msg) {
      //Add Close Button and Show up message
      div.html('<div style="background:#FFFF99;margin-bottom:15px;"><a style="position:absolute;top:16px;right:20px;font-weight:bold;text-decoration:none;color:white;" href="javascript:void(0)" class="CloseButton">X</a><div style="padding:10px;font-size:14px;line-height:18px"><h1 style="text-transform:uppercase;font-weight:bold;font-size:13px;margin-bottom:2px">Welcome, friend!</h1>' + msg + '</div>').show('slow',function(){
         //Hide On click close Button
         $('.CloseButton',div).click(function(){ div.hide() })
      });
   }
}
function findMatch(ref) {
   for(var i=0; i<msgs.length; i++)
      if( ( ref=='' && msgs[i].url==null) || (ref>'' && ref.match(msgs[i].url) ) )
         return msgs[i].msg;
   return null;
}
