(function($)
{

$(document).ready(function()
{

	// set cinema booking links to be new window
	$('#post-238 a.external').attr('target', '_blank');

	$('#facebook-like-iframe').each(function(i,e)
	{
		$(e).html('<iframe src="http://www.facebook.com/plugins/like.php?layout=standard&amp;show_faces=true&amp;width=465&amp;height=80&amp;action=recommend&amp;font=verdana&amp;colorscheme=light&amp;ref=post_top&amp;href='+$(e).attr('rel')+'" id="facebook-like-iframe" scrolling="no" frameborder="0" allowTransparency="true" style="float:left; border:none; overflow:hidden; width:465px; height:80px;"></iframe>').removeAttr('rel');
	});

	$('#twitter-share-button-iframe').each(function(i,e)
	{
		$(e).html('<iframe allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" class="twitter-share-button twitter-count-horizontal" src="'+$(e).attr('rel')+'" style="width: 70px; height: 80px; float: left;" title="Twitter For Websites: Tweet Button"></iframe>').removeAttr('rel');
	});

	$('#twitter-follow-button-iframe').each(function(i,e)
	{
		$(e).html('<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/follow_button.html?screen_name=fetchdidsbury" style="width:340px; height:20px; margin-top:10px;"></iframe>');
	});


	$('#facebook-like-box').each(function(i,e)
	{
		$(e).replaceWith('<div style="width:340px;height:172px;overflow:hidden;"><iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2FDidsbury.Manchester&amp;width=347&amp;colorscheme=light&amp;connections=6&amp;stream=false&amp;header=false&amp;height=197" scrolling="no" frameborder="0" style="border:0 none; overflow:hidden; width:340px; height:195px; margin: -2px 0 0 -2px;" allowTransparency="true"></iframe></div>');
	});


	$.getScript('http://platform.twitter.com/anywhere.js?id=aOLPERXvmPz7I2sw8gQyEg&v=1', function()
	{
		// twitter follow button
		twttr.anywhere(function (T)
		{
			if (T.isConnected())
			{
				var currentUser = T.currentUser;
	
				T('#follow_us').followButton("fetchdidsbury"); 
	
				$('#sidebar > ul').prepend('<li id="twitter-user-details"><p>Hi ' + currentUser.data('name') + '!<br />You\'re logged in using Twitter:</p><p><img src="' + currentUser.data('profile_image_url') + '" width="30" height="30" style="vertical-align:middle;" />&nbsp;<a href="http://twitter.com/' + currentUser.data('screen_name') + '" style="font-weight:bold;font-size:14px;">@' + currentUser.data('screen_name') + '</a></p><p>Watch this space for more functionality soon! - <a href="#" onclick="twttr.anywhere.signOut();return false;">logout</a></p></li>');
	
				// tweet box above comments
				if($('#commentform').length)
				{
					var post_id = $('#respond').text('Or post a comment here.').prevAll('.post').attr('id').replace(/post-/, '');
					$('#comment_by_tweet').show();
					T("#comment_by_tweet div").tweetBox({
						height: 100,
						width: 435,
						defaultContent: document.title.replace(/ \| Fetch Didsbury/, '') + ' - http://fetch.it/d/' + post_id + ' via @fetchdidsbury'
					});
				}
	
			}
			else
			{
				T('#follow_us').connectButton();
			}
	
			T.bind("authComplete", function (e, user)
			{
				// triggered when auth completed successfully
				document.location.reload();
			});
	
			T.bind("signOut", function (e)
			{
				// triggered when user logs out
				document.location.reload();
			});
		});
	});


	// sort any fb placeholders
	(function()
	{
		var t = (new Date().getTime());

		$('div.facebook-like-send-placeholder').each(function(i,e)
		{
			var self = $(e), data = self.text().split('::'), href = data.shift(), text = data.join('');
			self.replaceWith('<iframe allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" class="twitter-share-button twitter-count-horizontal" src="http://platform0.twitter.com/widgets/tweet_button.html?_=' + t + '&amp;count=horizontal&amp;lang=en&amp;url=' + encodeURIComponent(href) + '&amp;via=fetchdidsbury&amp;related=fetchdidsbury&amp;text=' + encodeURIComponent(text) + '" style="width: 110px; height: 20px; float: left;" title="Twitter For Websites: Tweet Button"></iframe><fb:like href="' + href + '" send="true" layout="button_count" action="recommend"></fb:like><g:plusone size="medium" href="' + href + '"></g:plusone>');

		}).each(function(i,e)
		{
			$('head').append('<script type="text/javascript" src="https://apis.google.com/js/plusone.js">{lang: \'en-GB\'}</script>');
			return false;
		});
	})()

	// fb like and share
	window.fbAsyncInit = function()
	{
		FB.init({appId: '5064302397', status: true, cookie: true, xfbml: true});

		// comment listener?
		if($('#fb_comments_container').length)
		{
			FB.Event.subscribe('comment.create', function(comment){
				
			});
		}
	};

	(function() {
		var e = document.createElement('script');
		e.async = true;
		e.src = document.location.protocol + '//connect.facebook.net/en_GB/all.js';
		$('#fb-root').append(e);
	}());

	$('a.fancybox').fancybox();

	setTimeout(function()
	{
		// facebook share widget is home page only
		if($('#facebook-share-widget').length)
		{
			$('#facebook-share-widget').html(unescape('%3Cfb:fan profile_id="48375950927" stream="0" connections="6" width="192"%3E%3C/fb:fan%3E'));
			$.getScript('http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php', function(){FB.init("d57fb905885b318d2e0dc7781c35b266");});
		}

	},1000);


	$('#fb_comments_container').each(function(i,e)
	{
		$('head').append('<meta property="fb:app_id" content="5064302397">');

		var self = $(e), href = self.text();
		var comments = $('#fb_comments_total').html('<fb:comments-count href="'+href+'"></fb:comments-count>');
		//var comments = $('#fb_comments_total').html('<div class="fb-comments-count" data-href="'+href+'"></div>');
		//self.html('<fb:comments num_posts="10" width="600" href="'+href+'"></fb:comments>').show();
		self.html('<div class="fb-comments" data-href="'+href+'" data-num-posts="10" data-width="600"></div>').show();

		function poller(){
			if( comments.text().length )
			{
				clearInterval( myPoller );
				if(comments.text() == '0')
				{
					//setTimeout(function(){ self.find('iframe').css('height',165) },2000);
				}
			}
		}
		var myPoller = setInterval(poller, 200);

	});


	// setTimeout holder for the loading dots (...)
	var compLoading;

	$('#answerList form').submit(function()
	{
		var error = '';
		var self = $(this);
		var idForm = self.attr('rel');

		if(!$.trim($('#firstname').val()))
		{
			error += '<li>Please submit at least your first name</li>';
		}

		if($('#emailAddr_'+idForm).val() == '' || !checkEmail($('#emailAddr_'+idForm).val()))
		{
			error += '<li>Email address incorrect</li>';
		}
	
		inpts = self.find('input');
		user_added = false;
		ans = -1;
		theSubmit = false;
		inpts.each(function(i, e)
		{
			cur = $(e);
			if (cur.is(':radio') && cur.is(':checked'))
			{
				ans = cur.val();
			}
	
			if (cur.attr('name') == 'comp_id')
			{
				poll_id = cur.val();
			}
	
			if (cur.attr('name') == 'comp_cookie_days')
				cdays = cur.val();
	
			if (cur.attr('type') == 'submit')
				theSubmit = cur;
	
		});
		
		// they haven't checked a box 
		if (ans == -1 || ans == '')
		{
			error += '<li>You need to choose an answer</li>';
		}
	
		if(error != '')
		{
			$('#errorComp_'+idForm).html('<ul>'+error+'</ul>');
			$('#errorComp_'+idForm).show();
			return false;
		}
		else
		{
			email = $('#emailAddr_'+idForm).val();
		}
	
		//compLoading = setTimeout(comp_loadingDots.bind(theSubmit), 50);
	
		path = self.attr('action');
	
		if(user_added)
		{
			path += "?comp_action=add_answer";
			path += "&comp_new_answer="+encodeURIComponent(ans);
		}
		else
		{
			path += "?comp_action=vote";
			path += "&comp_poll_"+poll_id+"="+ans;
		}
	
		path += '&comp_id='+poll_id + '&comp_ajax=true';
		path += '&emailAddr='+email;
		path += '&firstname='+$('#firstname').val();
		path += '&lastname='+$('#lastname').val();
		path += '&allow_contact_1='+ ($('#allow_contact_1').is(':checked') ? '1' : '0');
		path += '&allow_contact_2='+ ($('#allow_contact_2').is(':checked') ? '1' : '0');
		path += '&allow_contact_3='+ ($('#allow_contact_3').is(':checked') ? '1' : '0');

		$.get(path, function(data){comp_displayVotes(data)});

		return false;

	});


	$.populateManchesterNews = function()
	{
		// [NOTE] - This is a private feed. If you choose to use it you also risk the side effects that may have
		$.getJSON('http://fetch.it/pipe/manchester-news/?_callback=?', function(d)
		{
	
			if(d.value.items.length)
			{
				var loop = 0, html = '';
				while(loop++ < 40)
				{
					var item = d.value.items[loop];
					var date = new Date(item['y:published'].utime*1000);
					var datestr = date.toGMTString().replace(/(\s20[1-9][1-9]|:[0-9][0-9]\sGMT)/g,'');//(date.getHours()-1) + ':' + date.getMinutes() + ' ' + date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
					var source = (item.link.match(/^http:\/\/(www|news)\.bbc\.co\.uk\//) ? 'BBC News' : (item.link.match(/^http:\/\/menmedia.co\.uk\//) ? 'MEN Media' : 'Inside The M60'));
	
					html += '<div class="post snippet"><h2>' + item['y:title'] + '</h2><div class="entry">' + (item.img ? '<p><img src="[img-url]" alt="" title="" width="200" height="159" class="alignright size-medium wp-image-4968"></p>' : '') + '<p>' + item.description.replace(/(\s\[...\]|\.)$/,'...').replace(/<.*?>/g,'') + ' <a href="' + item.link + '" target="_blank" rel="nofollow">[open full story in new window]</a></p></div><p class="postmetadata">Posted ' + datestr + ' by ' + source + '.</p></div>';
	
				}
			}
			else
			{
				html = 'Failed to load Manchester news. Try back shortly.';
			}
	
			$('#content').append(html)
	
		});
	};
});




function comp_addUncheck()
{
	oUL = this.parentNode.parentNode;
	lis = oUL.getElementsByTagName('li');
	
	els = lis[lis.length-1].childNodes;
	
	for (i = els.length-1; i >= 0; i--)
	{
		if (els[i].nodeName.toLowerCase() == 'a')
		{
			els[i].style.display = '';
		}
		else
		{
			els[i].parentNode.removeChild(els[i]);
		}
	}

	Inp = oUL.getElementsByTagName('input');
	for (i = 0; i < Inp.length; i++)
	{
		Inp[i].onclick = function () { return true };
	}

	return true;
}




// very simple ajaxy loading visual
// adds 3 dots to link, then erase and start over
function comp_loadingDots()
{

}



function comp_clearDots()
{
	clearTimeout(compLoading);
}



function comp_getVotes(path, that)
{
	that.blur();
	compLoading = setTimeout(comp_loadingDots.bind(that), 50);

	comp_ajax.open("GET", path, true);
	comp_ajax.onreadystatechange = comp_displayVotes.bind(that.parentNode);
	comp_ajax.send(null);

	return false;
}



function comp_displayVotes (data)
{
	$('#answerList').html(data);
}



function comp_getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}



comp_ajax = new comp_getHTTPObject();


/*  from prototype.js */
Function.prototype.bind = function()
{
	var __method = this, args = $A(arguments), object = args.shift();
	return function()
	{
		return __method.apply(object, args.concat($A(arguments)));
	}
}



var $A = Array.from = function(iterable)
{
	if (!iterable) return [];
	if (iterable.toArray)
	{
		return iterable.toArray();
	}
	else
	{
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}



function checkEmail(email)
{
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
	{
		return true;
	}
	else
	{
		return false;
	}
}


})(jQuery);
