$(document).ready(function() {
	//cookieExists();
	
	$('#navbar li.drawer a.d-trigger').click(function(event) {
		event.preventDefault();
	});
	
	$('#navbar li.drawer').hover(function(event) {
		$('#sections-nav').css({'display' : 'block', 'visibility' : 'visible'});
	},
	function(event) {
		$('#sections-nav').css({'display' : 'none', 'visibility' : 'hidden'});
	});
	
	// Header subscribe zipcode functionality
	$('#header-newsletter input[name=zipcode]').focus(function(event) {
		$(this).val('').css('color', '#333');
	});
	$('#header-newsletter input[name=zipcode]').blur(function(event) {
		if ( $(this).val() === '' ) {
			$(this).css('color', '#bbb').val('optional');
		}
	});

	// $('#header #login-form').load('/inc/login-form' + window.location.pathname);
// 	
// 	$('#header #login-links').load('/inc/login-links/', function(text, status, req) {
// 		$('#sign-in').bind('click', showLoginForm);
// 	});
	
	// $("#resize a").click(function(event) {
// 		event.preventDefault();
// 		var clss = this.id;
// 		$(this).parents('p').children('a').removeClass("current");
// 		$(this).addClass("current");
// 		swapSheet( this.id );
// 	});
	
	$('a.tipline').click(function(event) {
		event.preventDefault();
		window.open(this.href, "pop", "width=450,height=600,menubar=no,status=no,toolbar=no,scrollbars=yes");
	});
	
	// ARTICLE TOOLS ------------------------------------//
	
	$('a.favorite_article').click(function(event) {
		event.preventDefault();
		favorite( this );
	});
	
	$('a.share_article').click(function(event) {
		event.preventDefault();
		if ($(this).text() == 'Share') {
			$(this).text('Close');
		} else {
			$(this).text('Share');
		}
		$(this).toggleClass('disabled');

		if ( document.all && window.XMLHttpRequest && !window.opera ) {
			var off = findPosition(this);
			var x	= off[0] - 140;
			var y	= off[1] + 23;
			$('#share-box').css({left:x,top:y}).toggle();
		} else {
			$('#share-box').css({left:this.offsetLeft}).toggle();
		}
		
	});
	
	$('a.share_article2').click(function(event) {
		event.preventDefault();
		if ($(this).text() == 'Share') {
			$(this).text('Close');
		} else {
			$(this).text('Share');
		}
		$(this).toggleClass('disabled');
		if ( document.all && window.XMLHttpRequest && !window.opera ) {
			var off = findPosition(this);
			var x	= off[0] - 140;
			var y	= off[1] + 23;
			$('#share-box2').css({left:x,top:y}).toggle();
		} else {
			$('#share-box2').css({left:this.offsetLeft}).toggle();
		}
	});
	
	$('a.email_article').click(function(event) {
		event.preventDefault();
		window.open(this.href, "pop", "width=450,height=600,menubar=no,status=no,toolbar=no");
	});
	
	$('a.print_article').click(function(event) {
		event.preventDefault();
		pageTracker._trackPageview('/print/'+window.location.href);
		window.print();
	});
	
	$("a.close").click(function(event) {
		event.preventDefault();
		window.close();
	});
	
	// ARTICLE IMAGE CAPTIONS ---------------------------//
	
	$('div.article p img').each(function(i) {
		var flow	= '';
		var style 	= '';
		var clss 	= '';
		var width	= '';
		var aWidth	= $(this).attr('width');
		
		if (aWidth === undefined || aWidth == 0 || aWidth === '') {
			var newImg 	= new Image();
			newImg.src 	= $(this).attr('src');
			width 	= (newImg.width == 0) ? '250' : newImg.width;
		} else {
			width 	= aWidth;
		}
		
		if (width > 350) {
			flow = ' static';
		}
		
		if ($(this).attr('style') !== '' || $(this).attr('style') !== undefined) {
			style = ' ' + $(this).attr('style');
			$(this).removeAttr('style');
		}
		
		if ($(this).attr('class') !== '' || $(this).attr('class') !== undefined) {
			clss = ' ' + $(this).attr('class');
			$(this).removeClass();
		}
		
		if (this.alt !== '' && this.alt != 'image') {
			$(this).wrap('<div class="article-photo'+flow+''+clss+'" style="width:'+width+'px;'+style+'"></div>').after('<br /><span>' + this.alt + '</span>');
		}
	});
	
	// SHOW/HIDE ----------------------------------------//
	
	$('a.showhide').click(function(event) {
		event.preventDefault();
		$('#'+this.rel).toggle();
	});
	
	// EXTERNAL LINK ------------------------------------//
	
	$("a.external").click(function(event) {
		event.preventDefault();
		pageTracker._trackPageview('/outgoing/'+$(this).attr("href").substr(7));
		window.open(this.href);
	});
	
	// NEWSLETTER BOX -----------------------------------//
	
	$('#mailinglist_form a').click(function(event) {
		event.preventDefault();
		$('#mailinglist_form').submit();
	});
	
	// COMMENTS -----------------------------------------//
	
	$('div.comment a.reply').click(function(event) {
		event.preventDefault();
		$('textarea.input').focus();
	});
	
	// POPULAR ARTICLES BOX -----------------------------//
	
	$('#popular_tabs li a').click(function(event) {
		event.preventDefault();
		$('#popular_tabs li a').removeClass('current');
		$(this).addClass('current');
		$('#popular div').hide();
		$('#most_'+this.id).toggle();
	});
	
	// LOGIN FORM ---------------------------------------//
	
	function showLoginForm(event) {
		event.preventDefault();
		var html = $('#login-form').html();
		$('#simplesearch').fadeOut('fast', function() {
			$(this).empty().html(html).css('bottom','20px').fadeIn('fast');
			
			$('#signin-but a').bind('click', function(event) {
				event.preventDefault();
				$('#simplesearch form').submit();
			});
		});
	}
	
	// BOTW PULLDOWN ------------------------------------//
	
	$('#botw-cats').change(function() {
		if ($(this).val() != '--') {
			window.location = 'http://www.propublica.org/breaking/' + $(this).val() + '/';
		}
	});
	
	// SITE SEARCH --------------------------------------//
	
	// $('#btnG').click(function(event) {
// 		event.preventDefault();
// 		$('#search_form').submit();
// 	});
	
	$('a.search-again').click(function(event) {
		event.preventDefault();
		$('#keywords').val($(this).attr('href'));
		$('#search_form').submit();
	});
	
	// SIGN UP ------------------------------------------//

	$('body#signin #screen_name').focus(function() {
		var name = $('#first_name').val()+' '+$('#last_name').val();
		$(this).val(name);
	});
	
	// FAKE GOOGLE ANALYTICS CLICKS ---------------------//
	
	$('a[href]').each(function() {
		if ($(this).attr('class') == "print_article" || $(this).attr('class') == "email_article") {
			$(this).click( function() {
				var prefix = ($(this).attr('class') == "print_article") ? "/print/" : "/email/";
				var msg = $(this).attr("href");
				re = /^(\w+):\/\//;
				tracking_url = msg.replace(re,"$1/");
				pageTracker._trackPageview(prefix + tracking_url);
			});
		}
	});
	
	// AJAXified MOST READ ------------------------------//
	
	$('#most_read').load('/static/chartbeat.html ol');
});

function findPosition( oElement ) {
	if( typeof( oElement.offsetParent ) != 'undefined' ) {
		for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
			posX += oElement.offsetLeft;
			posY += oElement.offsetTop;
		}
		return [ posX, posY ];
	} else {
		return [ oElement.x, oElement.y ];
	}
}

function favorite( button ) {
	var old_url = $(button).attr('href');
	var remove	= $(button).hasClass('remove');
	
	if ( remove ) {
		new_url	= old_url.replace(/delete/g, '');
		txt		= 'Save as Favorite';
		act		= 'save';
		img		= '/images/design/article-tools/favorite.gif';
	} else {
		new_url	= old_url + 'delete';
		txt		= 'Remove as Favorite';
		act		= 'delete';
		img		= '/images/design/article-tools/favorite-.gif';
	}
	
	$(button).addClass('disabled');
	
	$.post(old_url, function(text, status) {
		if ( status == 'success') {
			if ( text.indexOf('successfully') != -1 ) {
				$('div.msg').remove();
				$(button).removeClass('disabled').toggleClass('remove').empty().text(txt).attr('href', new_url);
				
				if ($('body').attr('id') == 'favorites') {
					$(button).parent().parent('div.article').remove();
				} else {
					msg = $('<div class="msg success">'+text+'<a href="/site/favorites/" title="View your favorites">View my favorites</a></div>').fadeOut(8000);
					//$(button).css('backgroundImage', img);
					$(button).after(msg);
				}
				
				return;
			}
		}
		
		$(button).removeClass('disabled').empty().text('Error').after('<div class="msg error">'+text+'</div>');
		
	});
}

function footNotes() {
	var links 	= [];
	var list	= document.createElement("ul");
	var num		= 1;
	
	$("div.article p a[href], div.article ul:not([id],[class]) a[href]").each(function(i,n) {
		span		= document.createElement("span");
		$(span).attr("class", "printOnly");
		j			= inArray(links, n.href);
		
		if ( j === 0 ) { // Unique
			links.push(n.href);
			span.appendChild(document.createTextNode(" [" + (num++) + "]"));
		} else { // Duplicate
			span.appendChild(document.createTextNode(" [" + j + "]"));
		}
		
		$(n).after(span);
	});
	
	$(links).each(function(i,n) {
		listitem	= document.createElement("li");
		$(listitem).attr("id", "link-"+(i+1));
		listitem.appendChild(document.createTextNode((i+1) + ". " + n));
		list.appendChild(listitem);
	});
	
	$("div.printOnly").append(list);
}

function inArray(array, value) {
    array = getArray(array);
	value = value || 0;

    for (var i = 0, len = array.length; i < len; ++i) {
    	if (array[i] == value) {
        	return i+1;
    	}
	}

	return 0;
}

function getArray(array) {
   if ( ! (array instanceof Array)) {
       array = [];
   }
   
   return array;
}

// cookie functions http://www.quirksmode.org/js/cookies.html

function createCookie( name, value, days ) {
	if ( days ) {
		var date = new Date();
		date.setTime( date.getTime()+( days*24*60*60*1000 ) );
		var expires = "; expires="+date.toGMTString();
	} else {
		var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) { createCookie(name,"",-1); }

// Append inline alternate stylesheets to DOM

function swapSheet(id) {
	 $("link[@rel*=alternate style]").each(function(i) {
		this.disabled = true;
		if (this.getAttribute('title') == id) this.disabled = false;
	});
	createCookie('style', id, 365);
}

// Find cookie and envoke correct stylesheet if set

function cookieExists() {
	var c = readCookie('style');
	$('#resize a').removeClass("current");
	if (c) { swapSheet(c); $("a#" + c).addClass("current");
	} else { $("a#small").addClass("selected"); }
}
