/*
@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

*/
var totalbrowseableItems = 0;
var currentbrowseableIndex = 0;

$(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);
		}
	});
	
	
	//IE6 hack for resources mouseover
	$('#new-resources li').bind('mouseover', function(event) {
		$(this).addClass('over');
	});
	$('#new-resources li').bind('mouseout', function(event) {
		$(this).removeClass('over');
	});
	
	//make anywhere in the resource box work as a link
	$('#new-resources li .box').click(function(){
		var toload = $(this).children('h3').children('a').attr('href');
		document.location.href=toload;
	}); 
	
	// 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 recommend page
	$('li.page-recommend a').click(function(event){
		email_to_friend(this);
		event.preventDefault();
	});
	
	//attach js funtionality to post a comment
	$('.post-comment a').click(function(event){
		post_comment();
		event.preventDefault();
	});
	//attach js funtionality to video link
	$('a.video-launch').click(function(event){
		videoconsole($(this).attr('href'));
		event.preventDefault();
	});
	
	//javascript to make top menu stay white when we hover over the drop down - has to be done with js because the images are on the a tag not the li
	$('ul#nav li#nav-home ul').bind('mouseover', function(event) {
		$('ul#nav li#nav-home a').addClass('highlight');
	});
	$('ul#nav li#nav-home ul').bind('mouseout', function(event) {
		$('ul#nav li#nav-home a').removeClass('highlight');
	});
	$('ul#nav li#nav-about ul').bind('mouseover', function(event) {
		$('ul#nav li#nav-about a').addClass('highlight');
	});
	$('ul#nav li#nav-about ul').bind('mouseout', function(event) {
		$('ul#nav li#nav-about a').removeClass('highlight');
	});
	$('ul#nav li#nav-schools ul').bind('mouseover', function(event) {
		$('ul#nav li#nav-schools a').addClass('highlight');
	});
	$('ul#nav li#nav-schools ul').bind('mouseout', function(event) {
		$('ul#nav li#nav-schools a').removeClass('highlight');
	});
	$('ul#nav li#nav-resources ul').bind('mouseover', function(event) {
		$('ul#nav li#nav-resources a').addClass('highlight');
	});
	$('ul#nav li#nav-resources ul').bind('mouseout', function(event) {
		$('ul#nav li#nav-resources a').removeClass('highlight');
	});
	$('ul#nav li#nav-curriculum ul').bind('mouseover', function(event) {
		$('ul#nav li#nav-curriculum a').addClass('highlight');
	});
	$('ul#nav li#nav-curriculum ul').bind('mouseout', function(event) {
		$('ul#nav li#nav-curriculum a').removeClass('highlight');
	});
	$('ul#nav li#nav-weneedyou ul').bind('mouseover', function(event) {
		$('ul#nav li#nav-weneedyou a').addClass('highlight');
	});
	$('ul#nav li#nav-weneedyou ul').bind('mouseout', function(event) {
		$('ul#nav li#nav-weneedyou a').removeClass('highlight');
	});
	
	//add spans to h1 and h2 elements needed by sifr
	/*var pageHeading = $('h1').html();
	var newHeading = $('<span></span>').append(pageHeading);
	$('h1').html(newHeading);*/
	//for h2 have to do it for each one. Only do for content block - other h2s may have different sifr styles
	/*$('.content_block h2').each(function(list) {
		var pageHeading = $(this).html();
		var newHeading = $('<span class="sifr"></span>').append(pageHeading);
		$(this).html(newHeading);
	});*/
	
	//height of secondary column image
	var menu = $("#secondary-nav");
	var image = $("#mask-image");
	if(menu.length && image.length){
		if (menu.height() > 200) {
			image.height(menu.height());
		} else {
			var tertiary = $("#tertiary-content");
			if (tertiary.length){
				image.height(tertiary.height());
			}
		}
	}
	
	//For continue reading... stuff
	jQuery('.js_truncated_text_hidden_part').hide();
	jQuery('.js_truncated_text_hidden_part').each(function () {
		var thislink = jQuery(this).parent().append('<a class="js_show_button" href="#">Continue reading...</a>');
		jQuery(thislink).children('.js_show_button').click(function(event){
			expand_readmore(this);
			event.preventDefault();
		});
	});
	
	//For browseable stuff
	jQuery('#secondary-content .browseable').hide();
	jQuery('#secondary-content .browseable:first').show();
	totalbrowseableItems = jQuery('#secondary-content .browseable').length;
	if(totalbrowseableItems > 1){
		jQuery('<p class="browseable-paginator"><span class="browseable-label">More facts</span> <a href="" class="next">&lt;</a><a href="" class="prev">&gt;</a></p>').appendTo(jQuery('#secondary-content .browseable'));
	};
	jQuery('#secondary-content .browseable:first .prev').addClass('prev_grey');
	jQuery('#secondary-content .browseable:last .next').addClass('next_grey');
	jQuery('#secondary-content .browseable .prev').click(function(event){ browseable_browse_prev(); event.preventDefault(); });
	jQuery('#secondary-content .browseable .next').click(function(event){ browseable_browse_next(); event.preventDefault(); });
	jQuery('.testimonial .browseable-label').text('More testimonials');
	
	//page extra stuff hover effect
	jQuery('.page-extras li').hover(
		function () {
		$(this).parents('.page-extras').prepend('<span id="hovered-page-extras">'+$(this).children('a').text()+'</span>');
			}, function () {
		$('#hovered-page-extras').remove();
		} );
	
	//comments stuff
	jQuery('#js-returnlink').hide();
	
	//overcome problems with sifr by setting inline values for bottom bg and image. Becaue of ie6, set them 1px off what they should be - because otherwise you get a white gap on some pages.
	$('.footer-image').css("bottom","36px");
	$('.bottom-bg').css("bottom","-1px");
	
	//shall we show basket?
	showBasket();
	
	//shop form stuff if this is form
	prepare_shop_form_toggle();
	
	//hook onto all popup windows
	jQuery('a.popup').click(function(){popupWindow(jQuery(this));return false;}).keypress(function(){popupWindow(jQuery(this));return false;});
	
}); /* Ends $(document).ready */

function popupWindow(elem){
	//parse width and height from rel attr
	window.open(jQuery(elem).attr("href"),'Popup',jQuery(elem).attr("rel"));
	return false;
}


var store_shop_old_category = "";
function prepare_shop_form_toggle(){
	if(jQuery('#billingform input#work_in_school').length){
		jQuery('#billingform span.school-label').each(function (i) {
			var temp = jQuery(this).text();
			jQuery(this).text(temp.replace('|', ''));
		});
		store_shop_old_category = jQuery('#category').val();
		shop_form_toggle(jQuery('#billingform input#work_in_school:checked').length);
		
		jQuery('#billingform input#work_in_school').change( function() {
			shop_form_toggle(jQuery('#billingform input#work_in_school:checked').length);
		});
		if (jQuery.browser.msie) {
			jQuery('#billingform input#work_in_school').click( function() {
				shop_form_toggle(jQuery('#billingform input#work_in_school:checked').length);
			});
			jQuery('#billingform label#work_in_school_label').click( function() {
				shop_form_toggle(jQuery('#billingform input#work_in_school:checked').length);
			});
		}
	}
}

function shop_form_toggle(is_school){
	if(is_school){
			jQuery('#billingform span.org-label').hide();
			jQuery('#billingform span.school-label').show();
			jQuery('#details-head h2 span').attr('class', 'shop_schooldetails');
			jQuery('#details-head h2 span').text('School details');
			jQuery('#your-details-head').hide();
			jQuery('#school-details-head').show();
			store_shop_old_category = jQuery('#category').val();
			jQuery('#category').val('Education');
			jQuery('#category-wrapper').hide();
		}else{
			jQuery('#billingform span.school-label').hide();
			jQuery('#billingform span.org-label').show();
			jQuery('#details-head h2 span').attr('class', 'shop_yourdetails');
			jQuery('#details-head h2 span').text('Your details');
			jQuery('#school-details-head').hide();
			jQuery('#your-details-head').show();
			jQuery('#category').val(store_shop_old_category);
			jQuery('#category-wrapper').show();
		}
}


// browseable
function browseable_browse_next(){
	var newcurrentbrowseableIndex = currentbrowseableIndex+1; 
	if(newcurrentbrowseableIndex < totalbrowseableItems){
		currentbrowseableIndex = newcurrentbrowseableIndex;
		jQuery('#secondary-content .browseable').hide();
		jQuery('#secondary-content .browseable:eq('+currentbrowseableIndex+')').show();
	};
};

function browseable_browse_prev(){
	var newcurrentbrowseableIndex = currentbrowseableIndex-1; 
	if(newcurrentbrowseableIndex >= 0){
		currentbrowseableIndex = newcurrentbrowseableIndex;
		jQuery('#secondary-content .browseable').hide();
		jQuery('#secondary-content .browseable:eq('+currentbrowseableIndex+')').show();
	};
};

// SEND TO FRIEND (based on Oxford)

function closeRecommend() {
	$('#recommend-box').fadeOut(1200,function(){
		$('#recommend-box').remove();
	});
}

function setupRecommendBox() {
	var recommendLocation = $('.page-recommend').offset();
	if($.browser.msie && $.browser.version <= 6) {
		var docHeight = $(document).height();
	}
	else {
		var docHeight = $(window).height();
	}
	
	//var boxLeft = recommendLocation.left - 230 + $('.page-recommend').width();
	//var boxBottom = docHeight - recommendLocation.top - ( 2* $('.page-recommend').height());
	//$('#recommend-box').css({left: boxLeft + 'px', bottom: boxBottom + 'px'});
		var senderText = "Your name";
		var SenderEmailText = "Your email";
		var recipientText = "Their name";
		var recipientEmailText = "Their email";
		var recipientMessageText = "Write your message here...";
		
		$('#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);
			}
		});
		$('#recommend-box #message').val(recipientMessageText).focus(function() {
			if (this.value == recipientMessageText) {
				$(this).val('');
			}
		}).blur(function() {
			if (this.value == '') {
				$('#recommend-box #message').val(recipientMessageText);
			}
		});
		var boxTimeOut;
		$('#recommend-box form').submit(function() {
			$.post('/applications/send_to_friend/js_send.rm', $(this).find('.formfield').serialize(), function(data) {
				$('#recommend-box').html(data);
				if($('#recommend-box p.thanks').length ) {
					boxTimeOut = setTimeout(closeRecommend,500);
				}
				else {
					setupRecommendBox();
				}
			});
			
			return false;
		});
		
		if($('#recommend-box a.closerlink').length ) {
			$('#recommend-box a.closerlink').remove();			
		}
		if($('#recommend-box img.boxlabel').length ) {
			$('#recommend-box img.boxlabel').remove();			
		}
		$('#recommend-box .header-title').click(closeRecommend);
		
		//var closer = $('<a href="#" class="closerlink"><img alt="close" class="overlayclose fauxlink" src="/display_images/icons/recommend_close.gif" /></a>');
		//var boxlabel = $('<img src="/display_images/icons/footer_recommend_popup.gif" alt="recommend this page" class="boxlabel" />');
		//$(closer).click(closeRecommend);
		//$('#recommend-box').append(closer);
		//$('#recommend-box').append(boxlabel);
		/*$('#recommend-box').blur(function() {
			closeRecommend();
		});*/
	$('#recommend-box').show();
}

function email_to_friend(elem) {
	var pageID = $('li.page-recommend a').attr('href').replace(/\/applications\/send_to_friend\/compose.rm\?id=/,""); //get the ID of the page to be recommended
	if($('#recommend-box').length > 0){
		closeRecommend();
	};
	$('<div id="recommend-box"></div>').insertBefore(jQuery(elem).parents('.page-extras')); //WHERE to insert the popup box?
	$('#recommend-box').hide();
	$('#recommend-box').load('/applications/send_to_friend/form.rm?id=' +pageID, setupRecommendBox);
}

function post_comment() {
	var pageID = $('.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=420,height=540,scrollbars=1,resizable=1');
}

function videoconsole(link) {
	var ids = link.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,resizable=1');
}

function expand_readmore(elem){
	jQuery(elem).prev('.js_truncated_text_hidden_part').show();
	jQuery(elem).hide();
}

function showBasket(){
	var cookieValue = 0;
	//get the cookie
	var cookieName = 'pfeg_show_basket';
	if (document.cookie && document.cookie != '') {
		var cookies = document.cookie.split(';');
		for (var i = 0; i < cookies.length; i++) {
			var cookie = jQuery.trim(cookies[i]);
			if (cookie.substring(0, cookieName.length + 1).toLowerCase() == (cookieName + '=')) {
				cookieValue = decodeURIComponent(cookie.substring(cookieName.length + 1));
				break;
			}
		}
	}

	//show the icon
	if (cookieValue != 0){
		if (cookieValue == 1){ cookieValue = cookieValue + ' item'}
		else{ cookieValue = cookieValue + ' items' };
		jQuery('#header .extra').prepend('<li class="top-basket-icon"><a href="/applications/shop/basket.rm">'+cookieValue + ' in <img src="/display_images/icon_shoppingbasket.gif" width="15" height="11" alt="items in basket"/></a></li>');
	}
}
