/*
@description Add general site-wide js funtionality to the page (e.g. print page button)

@author	Bryan Gullan
@created 2007-08-28

Notes: Uses jQuery; written on v. 1.1.4
			Requires jQuery plugin clickOrEnter: http://jquery.com/plugins/project/clickOrEnter
*/

var newWindow = null;

$(document).ready(function() {
	// deal with search box
	var defaultText = "Enter search term";
	$('#searchinput').val(defaultText).focus(function() {
		if (this.value == defaultText) {
			$(this).val('');
		}
	}).blur(function() {
		if (this.value == '') {
			$('#searchinput').val(defaultText);
		}
	});
	
	// add print page link - since it can only work for JS, only add it for JS users
	$('<li></li>') // create list item
	.addClass('page-print') //add relevant class to it
	.append('<a href="javascript:window.print();">Print this page</a>') //put in the link
	.insertBefore('.page-recommend'); //add before the recommend this page item
	
	//attach js funtionality to post a comment
	$.clickOrEnter('.post-comment a',post_comment);
	//attach js funtionality to video link
	$.clickOrEnterWithElem('a.launch-video',videoconsole);
	
	$.clickOrEnter('a.sitemap',showSiteMap);
	
	//setup email to friend box
	$('#recommend-box').hide();
	$.clickOrEnter('.page-recommend a', openRecommend);
	
	//IE6 hack for nav drop-downs
	$('ul#nav > li').hover(
		function(){
			$(this).addClass('over');
		},
		function(){
			$(this).removeClass('over');
		}	
	);
	
	//attach date widget functionality to date filters
	$('#dsp_filter_date').blur(function(){ dateBlur('filter_date')});
	$('#dsp_filter_date').focus(function(){dateFocus('filter_date')});
	
	//CAF payment form placeholders
	$('.placeholder-caf-cc').each(function(){
		campaignId=$(this).html();
		$(this).html('<form action="https://rsm2.rsmsecure.com/cpterminal/cpweb.php" method="post" target="_blank"><input type="hidden" value="'+campaignId+'" name="campaign" /><input type="image" src="http://www.ctt.org/images/cm_images/donate_online_now_plain.gif" value="One Off Donation" name="submit" /></form>');
	})
	
	$('.placeholder-caf-dd').each(function(){
		campaignId=$(this).html();
		$(this).html('<form action="https://rsm2.rsmsecure.com/directdebit/dd.php" method="post" target="_blank"><input type="hidden" value="'+campaignId+'" name="campaign" /><input type="image" src="http://www.ctt.org/images/cm_images/donate_online_now_plain.gif" value="One Off Donation" name="submit" /></form>');
	})
	
	
	//newsletter signup forms, wherever used
	fieldHint($('#newsletter_forename'));
	fieldHint($('#newsletter_emailaddress'));
	$('.newslettersignup').submit(function(){
		$('.newslettersignup input').each(function(){
			if($(this).val()==$(this).attr("alt")){
				$(this).val('');
			}
		});
		
		if (!(/^([a-zA-Z0-9-_\+]+\.)*[a-zA-Z0-9-_\+]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+$/).test($('#newsletter_emailaddress').val())) {
			alert('Your email address must be valid');
			return false;
		}
		return true;		
	});

	//newsletter signup forms, wherever used
	fieldHint($('#iphonesignup_emailaddress'));
	$('.iphonesignup').submit(function(){
		$('.iphonesignup input').each(function(){
			if($(this).val()==$(this).attr("alt")){
				$(this).val('');
			}
		});
		
		if (!(/^([a-zA-Z0-9-_\+]+\.)*[a-zA-Z0-9-_\+]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+$/).test($('#iphonesignup_emailaddress').val())) {
			alert('Your email address must be valid');
			return false;
		}
		return true;		
	});

	$(".tooltip").tooltip({showURL: false}); 
	
});

/* form field hints*/
function fieldHint(element){
	$(element).focus(function(){
		if($(this).val() == $(this).attr("alt")){
			$(this).val("");
		}
	});
	$(element).blur(function(){
		if($(this).val() == $(this).attr("alt") || !$(this).val().length){
			$(this).val($(this).attr("alt"));
		}
	});
	$(element).blur();
}


// SEND TO FRIEND
function openRecommend() {
	$('#recommend-box').slideDown(500,function(){
		if($('#recommend-box a.closerlink').length ) {
			$('#recommend-box a.closerlink').remove();			
		}

		var closer = $('<a href="#" class="overlayclose closerlink"><img alt="close" src="/display_images/icons/recommend_close.gif" /></a>');
		$.clickOrEnter(closer,function(){
			$('#recommend-box').slideUp(500);
		});
		$('#recommend-box').append(closer);
	});
	
	var senderText = "Your name";
	var SenderEmailText = "Your email";
	var recipientText = "Their name";
	var recipientEmailText = "Their email";
		
	$('#recommend-box #senderName').val(senderText).focus(function() {
		if (this.value == senderText) {
			$(this).val('');
		}
	}).blur(function() {
		if (this.value == '') {
			$('#recommend-box #senderName').val(senderText);
		}
	});
	$('#recommend-box #sender').val(SenderEmailText).focus(function() {
		if (this.value == SenderEmailText) {
			$(this).val('');
		}
	}).blur(function() {
		if (this.value == '') {
			$('#recommend-box #sender').val(SenderEmailText);
		}
	});
	
	$('#recommend-box #recipientName').val(recipientText).focus(function() {
		if (this.value == recipientText) {
			$(this).val('');
		}
	}).blur(function() {
		if (this.value == '') {
			$('#recommend-box #recipientName').val(recipientText);
		}
	});
	$('#recommend-box #recipient').val(recipientEmailText).focus(function() {
		if (this.value == recipientEmailText) {
			$(this).val('');
		}
	}).blur(function() {
		if (this.value == '') {
			$('#recommend-box #recipient').val(recipientEmailText);
		}
	});
	
	var boxTimeOut;
	$('#recommend-box form').submit(function() {
		$.post($('#recommend-box form').attr("action")+'&ajax=true', $(this).find('input').serialize(), function(data) {
			$('#recommend-box div.container').html(data);
			if($('#recommend-box p.thanks').length) {
				boxTimeOut = setTimeout(function(){$('#recommend-box').slideUp(500)},1500);
			}
		});
		
		return false;
	});
	
}

function post_comment() {
	var pageID = $('li.post-comment a').attr('href').replace(/\/applications\/comments\/comments.rm\?article_id=/,""); //get the ID of the page to be commented on
	window.open('/applications/comments/comments.rm?article_id='+pageID,'Comment','width=480,height=590,scrollbars=1');
}

function videoconsole(element) {
	var ids = $(element).attr('href').replace(/\/applications\/mediaplayer\/video.rm\?media_id=/,""); //get the media and page ids
	ids = ids.split("&id="); // split the two ids; they're either side of the '&id='
	window.open('/applications/mediaplayer/video.rm?media_id='+ids[0]+'&id='+ids[1],'Video console','width=450,height=450,scrollbars=1');
}

function closeSitemap() {
	$('#sitemap').remove();
	$('#overlay').remove();
	$('select').show();
	$('img.overlayclose').unbind('click').unbind('keypress');
	$('#overlay').unbind('click').unbind('keypress');
}

function setupSitemap() {
	var sitemapHeight = $('#sitemap-box').height();
	var docHeight = $(document).height();
	
	if (sitemapHeight + 40 > docHeight) {
		$('body').height(sitemapHeight + 60 + 'px');
		docHeight = $(document).height();
		$('#overlay').css({ height: docHeight + 'px' });
	}
	var sitemapTopMargin = docHeight - sitemapHeight - 40;
	//$('#sitemap-box').css({marginTop: sitemapTopMargin + 'px' });  
	$('#sitemap-box').css({marginTop: 40 + 'px' });  
	
	var closer = $('<a href="#"><img alt="close sitemap" class="overlayclose fauxlink" src="/display_images/sitemap_close.gif" /></a>')
	$.clickOrEnter(closer,closeSitemap);
	$('#sitemap-box').append(closer);
	$.clickOrEnter('#overlay',closeSitemap);
	$('select').hide();
	$('#sitemap-box').show();
	//call google analytics tracking for dummy page for this popup
	if (typeof urchinTracker == 'function') {
		urchinTracker('/sitemap/');
	} 
}

function showSiteMap() {
	var docHeight = $(document).height();
	var docWidth = $(document).width();
	
	var sitemapType = $('a.sitemap').attr('title'); //the title attribute is set to be the sitemap type
	
	$('<div id="overlay"></div>').insertAfter('#wrapper');
	$('<div id="sitemap"></div>').insertAfter('#wrapper');
	
	window.scrollTo(0,0);
	
	$('#overlay').css({ height: docHeight + 'px' ,width: docWidth + 'px'  });
	$('#sitemap').load('/applications/sitemap.rm?site=' + sitemapType,setupSitemap)
	;
}

function doPopup(element){
	var wintype = "standard";
	var winwidth = "780";
	var winheight = "580";

	var attribs = $(element).attr("rel").split(" ");
	if (attribs[1]!=null) {wintype = attribs[1].toLowerCase();}
	if (attribs[2]!=null) {winwidth = attribs[2];}
	if (attribs[3]!=null) {winheight = attribs[3];}
	
	if (newWindow != null && !newWindow.closed){
		newWindow.close();
	}
	
	if (wintype == "fullscreen"){
		winwidth = screen.availWidth;
		winheight = screen.availHeight;
	}
	var tools="";
	if (wintype == "standard") tools = "resizable,toolbar=yes,location=yes,scrollbars=yes,menubar=yes,width="+winwidth+",height="+winheight+",top=0,left=0";
	if (wintype == "console" || wintype == "fullscreen") tools = "resizable,toolbar=no,location=no,scrollbars=no,width="+winwidth+",height="+winheight+",left=0,top=0";
	newWindow = window.open($(element).attr("href"), 'newWin', tools);
	newWindow.focus();

	return false;
}

/* function already added, probably by Dave */
$(function () {
	$('.strokedrounded').append('<div class="corner1"></div><div class="corner2"></div><div class="corner3"></div><div class="corner4"></div>');
});


//IE6 hack for teaser hover effect on forms
$(document).ready(function() {
	$('fieldset div.row').bind('mouseover', function(event) {
		$(this).addClass('over');
	});
	$('fieldset div.row').bind('mouseout', function(event) {
		$(this).removeClass('over');
	});
	$('fieldset div.row div').bind('mouseover', function(event) {
		$(this).addClass('over');
	});
	$('fieldset div.row div').bind('mouseout', function(event) {
		$(this).removeClass('over');
	});
	$('fieldset div.row label.inputlabel').bind('mouseover', function(event) {
		$(this).addClass('over');
	});
	$('fieldset div.row label.inputlabel').bind('mouseout', function(event) {
		$(this).removeClass('over');
	});
	$('fieldset div.row p.note').bind('mouseover', function(event) {
		$(this).addClass('over');
	});
	$('fieldset div.row p.note').bind('mouseout', function(event) {
		$(this).removeClass('over');
	});
});
	