 $(document).ready(function() {
   // do stuff when DOM is ready
	 
	 //comment box auto resizing
	 $('.autoresize').autoResize({
		    // On resize:
		    onResize : function() {
		        $(this).css({opacity:0.8});
		    },
		    // After resize:
		    animateCallback : function() {
		        $(this).css({opacity:1});
		    },
		    // Quite slow animation:
		    animateDuration : 300,
		    // More extra space:
		    extraSpace : 0
		});
	 
	 //superfish menu
    $('ul#nav').superfish({
        delay:       800,
		speed:       'fast',
		dropShadows: false,
		autoArrows:  false
    });
    
    //fancybox
    //$("a#display").fancybox();
    //$("a#profile").fancybox();
    //$("#resource_pack_images > li > a").fancybox();
    //$(".fancybox").fancybox();
    
    //uploadify
    $('#shared_resource_file').uploadify({
	    'uploader'  : '/uploadify/uploadify.swf',
	    'script'    : '/uploadify/uploadify.php',
	    'cancelImg' : '/uploadify/cancel.png',
	    'auto'      : true,
	    'removeCompleted' : false,
	    'fileExt'   : '*.doc;*.docx;*.pub;*.pubx;*.pdf;*.ppt;*.pptx',
	    'buttonText': 'Choose a file',
		'onComplete': function(event,queueID,fileObj,response,data)
		{
			$('#filename').val(response);
		}
	    
 	});
 	
 	//download selector
 	$('#actual_downloads > li.alt').css({display: 'none'});

	//country / county fields
	if($('#country').val() != 225)
	{
		$('#county_field').css({display: 'none'});
		$('#county > option').removeAttr('selected');
	}
	
	$('#country').change(function(){
		if($('#country').val() == 225)
		{
			$('#county_field').slideDown('fast');
			$('#nus_number_wrapper').slideDown('fast');					
		}
		else
		{			
			$('#county_field').slideUp('fast', function(){
				
				$('#county > option').removeAttr('selected');
								
			});
			
			$('#nus_number_wrapper').slideUp('fast', function(){
				
				$('#nus_number').val('');
								
			});							
		}
	});
		
	//sign up validation
	$('#email_address').bind('keyup change', function(){
		checkIfEmailExists();
	});
	
	$('#username').bind('keyup change', function(){
		checkIfUsernameExists();
	});
	
	//sign up & details 'other' fields
	if($('#workplace_type').val() != 0 || $('#workplace_type').val() == "")
	{
		$('#workplacetype_other_field').css({display: 'none'});
	}
	
	$('#workplace_type').bind('change', function(){
		if($('#workplace_type').val() == 0)
		{		
			$('#workplacetype_other_field').slideDown('fast');
		}	
		else
		{
			$('#workplacetype_other').val("");
			$('#workplacetype_other_field').slideUp('fast');			
		}
	});
		
	if( $('#career').val() != 0 || $('#career').val() == "" )
	{
		$('#career_other_field').css({display: 'none'});
	}
	
	$('#career').bind('change', function(){
		if($('#career').val() == 0)
		{		
			$('#career_other_field').slideDown('fast');
		}	
		else
		{
			$('#career_other').val("");
			$('#career_other_field').slideUp('fast');			
		}
	});	
	
	//contact form
	$('#contact_form').css({display: 'none'});
	
	//basket buttons
	basket_count = $('#basket_contents > li').length;
	
	if(basket_count > 2)
	{
		$('#basket_up').fadeTo('slow', 0.5, 'easeOutExpo');
		$('#basket_down').fadeTo('slow', 1, 'easeOutExpo');
	}
	else
	{
		$('#basket_up').fadeTo('slow', 0.5, 'easeOutExpo');
		$('#basket_down').fadeTo('slow', 0.5, 'easeOutExpo');
	}
	
	if(basket_count == 1)
	{
		$('#basket_contents').height('104px');
	}
	
	//checkout qty
	$('.checkout_qty > input').live('change', function(){
			
		ids = $(this).attr('name');
		
		ids = ids.split("-");
		
		type_id = ids[0];
		item_id = ids[1];
		
		qty = $(this).val();
					
		url = '../php/ajax/changeCheckoutQuantity.php' +
			  '?type_id=' + type_id +
			  '&item_id=' + item_id +
			  '&qty=' + qty;
		  
		url = encodeURI(url);
			
		$('#checkout_wrapper').load(url);

	});
	
	//print terms
	$('#paynow_wrapper').hide();
	
	$('#agree_print_terms').change(function()
	{
		if($('#agree_print_terms').attr('checked'))
		{
			$('#paynow_wrapper').slideDown('fast');
		}
		else
		{
			$('#paynow_wrapper').slideUp('fast');
		}
	});
		 
		 
	//calendar
	$('.event_past').hide();
	
	//overlay
	$('#overlay').click(function(){
		
		closeDashyExtra();
		
	});
	
	$('#premium_country').hide();
	
	$('#premium_agree > #agree_terms').change(function(){			
		
		if($('#premium_agree > #agree_terms').attr('checked'))
		{
			$('#premium_country').slideDown('fast');			
		}
		else
		{
			$('#premium_country').slideUp('fast');
		}
	});	
	
	$('#premium_country > #country').change(function(){			
		
		if($('#premium_country > #country').val())
		{			
			url = "https://www.twinkl.co.uk/php/ajax/saveUserCountry.php?country_id=" + $('#country').val();
			url = encodeURI(url);
						
			$.post(url, function(data){
				
				$('#premium_pay').slideDown('fast');		
				
			});
					
		}
		else
		{
			$('#premium_pay').slideUp('fast');
		}
	});	
	
	
	$('#copy_linkage').zclip({
        path:'js/ZeroClipboard.swf',
        copy:$('#linkage').text(),
        afterCopy:function(){
            apprise("Copied!");
        }
    });
	
	$('.mailing_pref_checkbox').live('click change', function(){
		
		 $('.mailing_pref_checkbox').attr('disabled', true);
		
		 $(this).replaceWith('<img src="/images/loading_small.gif" alt="Loading" />');
		
		 checkbox_id = $(this).attr('id');
		 
		 checkbox_id = checkbox_id.replace("mailing_pref_checkbox_", "");
		 
		 if( $(this).attr('checked') == "checked" )
		 {
		 	checkbox_checked = true;
		 }
		 else
		 {
		 	checkbox_checked = false;
		 }
		 
		 url = "../php/ajax/setMailingPref.php" +
		 	   "?group_id=" + checkbox_id +
		 	   "&subscribe=" + checkbox_checked;
		 	   
		 url = encodeURI(url);
		 
		 $('#mailing_prefs_wrapper').load(url);
		 		
	});

	$('.more_reward_actions').hide();

 });
 
function showMoreRewardActions()
{
	
	$('.more_reward_actions').slideDown();
	$('.rewards_button').fadeOut('fast');
		
}
 
function showPastEvents()
{
		
				
	$('.event_past').show(function(){
		
		$('.event_past').css('opacity','0');
				
				
		
	});
	
	$('html').animate({scrollTop: $(".event_past:eq(0)").offset().top}, 1500, 'easeOutExpo', function(){
			
			$('.event_past').animate({opacity: 1}, 1500);
						
		});
	
	
}
 
function CreateBookmarkLink() {

 title = "Twinkl"; 

 url = "http://www.twinkl.co.uk";

	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; }
}
 
 
function showContactForm()
{
	$('#contact_form').slideDown('fast');
	
	$('html, body').animate({scrollTop: $("#contact_form").offset().top}, 1500);
}
 
 function showTerms()
 {
 	$('#terms').slideToggle('fast');
 }

function showDownload(element_id)
{	
	$('#actual_downloads > li').hide();
	$('#' + element_id).delay(250).show();
	
	$('#download_selector > li').removeClass('selected');
	$('#select_' + element_id).addClass('selected');		
}

var xmlHttp;
var Effect;

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

function validate_contact_form()
{
    
	msg = "";
    valid = true;

    if ( document.contact_form.message.value == "" )
    {
		msg = msg + "You must enter a message.\n";
        valid = false;
    }   
	
    if ( document.contact_form.contact_name.value == "" )
    {
		msg = msg + "You must enter your name.\n";
        valid = false;
    }   	
	
    if ( document.contact_form.captcha_code.value == "" )
    {
		msg = msg + "You must enter the security code.\n";		
        valid = false;
    }   	
	
    if ( document.contact_form.contact_email.value == "" )
    {
		msg = msg + "You must enter your email address.\n";		
        valid = false;
    }   		

	
	if (document.contact_form.contact_email.value != "")
	{
	
		apos = document.contact_form.contact_email.value.indexOf("@");
		dotpos = document.contact_form.contact_email.value.lastIndexOf(".");
		
		if (apos < 1 || dotpos - apos < 2)
		{
			msg = msg + "The email address entered is not valid.\n";		
			valid = false;
		}
		
	}
	
/*
	if(document.contact_form.email.value == "" && document.contact_form.tel.value == "")
    {
		msg = msg + "You must enter either your telephone number or email address.\n";		
        valid = false;
    }   	

*/
	if(valid == false)       
	{
        apprise (msg);		
	}
	   

    return valid;
	
}

function isEmailValid(email)
{
	valid = true;
	
	apos = email.indexOf("@");
	dotpos = email.lastIndexOf(".");
	
	if (apos<1||dotpos-apos<2) 
	{
        valid = false;		
	}		
	
	return valid;
		
}


function sendRequestForm()
{

	var msg = "";
	var valid = true;
	
	if( !$('#name').val() )
	{
		valid = false;
		msg += "<li>Please fill in your name.</li>\n";
	}
	
	if( !$('#request').val() )
	{
		valid = false;
		msg += "<li>Please tell us what resource you'd like to suggest.</li>\n";
	}	
	
	if( $('#emailme').attr('checked') )
	{
		if(!$('#request_email').val())
		{
			valid = false;
			msg += "<li>Please enter your email address.</li>\n";
		}	
		
		if( !isEmailValid($('#request_email').val()) )
		{
			valid = false;
			msg += "<li>Please make sure your email address is correct.</li>\n";
		}
	}

	if(!valid)
	{
		msg = "<ul>" +
			  	msg +
			  "</ul>";
			  
		apprise(msg);
	}
	else
	{
		
		var name = $('#name').val();
		
		var user_id = $('#user_id').val();			
		
		if($('#emailme').attr('checked'))
		{
			var email = $('#request_email').val();			
		}
		else
		{
			var email = "Not specified";
		}		

		var request = $('#request').val();
		
		$('#send_request').html('Sending...');
		
		xmlHttp = GetXmlHttpObject()
	
		if (xmlHttp==null)
		{
			apprise ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "https://www.twinkl.co.uk/php/ajax/sendRequestForm.php?name=" + name;
		url = url + "&email=" + email;
		url = url + "&request=" + request;
		url = url + "&user_id=" + user_id;						
		url = url + "&sid=" + Math.random();
		xmlHttp.onreadystatechange = requestSent;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);

	
	}	

}



function requestSent() 
{ 
	if (xmlHttp.readyState==4)
	{ 
		document.getElementById("request_form").innerHTML=xmlHttp.responseText;
	}
}


function sendBookForm()
{

	if(  document.request_form.name.value == "" ||  document.request_form.request.value == "")
	{
		apprise("Please make sure all fields are complete.");
	}
/*	else if(document.request_form.emailme.checked == 1 && (document.request_form.email.value == "" || !isEmailValid(document.request_form.email.value)))
	{
		apprise("Please make sure the provided email address is valid."); 
	}*/
	else
	{
		
		var name = document.request_form.name.value;
		var topics = document.request_form.topics.value;	
		
/*		if(document.request_form.emailme.checked == 1)
		{
			var email = document.request_form.email.value;			
			document.getElementById("email").disabled = "disabled";
		}
		else
		{
			var email = "Not specified";
		}	*/	

		var request = document.request_form.request.value;
		
		document.getElementById("name").disabled = "disabled";
		document.getElementById("topics").disabled = "disabled";
		document.getElementById("request").disabled = "disabled";
		$('#send_request').html('Sending...');
		

		xmlHttp = GetXmlHttpObject()
	
		if (xmlHttp==null)
		{
			apprise ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "../php/ajax/sendBookForm.php?name=" + name;
		url = url + "&topics=" + topics;
		url = url + "&request=" + request;				
		url = url + "&sid=" + Math.random();
		xmlHttp.onreadystatechange = requestSent;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);

	
	}	
}






function validate_search_form()
{
    

    valid = true;

    if ( document.search_form.lijit_q.value == "" || document.search_form.lijit_q.value == "Search free resources..." )
    {
        valid = false;
    }   
	
    
	if(valid == false)       
	{
        apprise ("You didn't tell us what you're looking for...");		
	}
	   

    return valid;
	
}


function validate_signup_form()
{
    
    
    agree_terms = $('#agree_terms').is(':checked');    
    email = $('#email_address').val();
    email2 = $('#email_address2').val();
    username = $('#username').val();
    password1 = $('#password1').val();
    password2 = $('#password2').val();
    
    var msg = '';
    var valid = true; 
    
    if($('#username_response').html() != "")
    {
    	valid = false;
    	msg += "<li>Please choose a different username.</li>";    	
    }
    
    if($('#email_response').html() != "")
    {
    	valid = false;
    	msg += "<li>Please supply a different email address.</li>";    	
    }    
            			
    //check all requiredness is there
    if(!email)
    {
    	valid = false;
    	msg += "<li>Your email is missing.</li>";    	
    }
    else
    {
    	//check email valid
	    if(!isEmailValid(email))
	    {
	    	valid = false;
	    	msg += "<li>The email you entered doesn't appear to be correct.</li>";
	    }
    }
    
    if(!email2)
    {
    	valid = false;
    	msg += "<li>You didn't repeat your email address.</li>";    	
    }
    else
    {
    	//check email valid
	    if(!isEmailValid(email2))
	    {
	    	valid = false;
	    	msg += "<li>The email you repeated doesn't appear to be correct.</li>";
	    }
    }    
    
    
    if(!username)
    {
    	valid = false;
    	msg += "<li>You didn't enter a username.</li>";    	
    }    
    else
    {
    	
		//is username longer than 6 characters
	    if(username.length < 6)
	    {
	    	valid = false;
	    	msg += "<li>Your username must be at least 6 characters long.</li>";    	
	    }
	    
	    //and doesn't contain any funky characters
	    var funky_characters = new Array(" ", '"', "!", "£", "$", "%", "^", "&", "*", "(", ")", "+", "=", "{", "}", "[", "]", ":", ";", "@", "'", "#", "~", "?", "/", "\\", "|", "¬", "`", "<", ">", ",");
	    var char_valid = true;
	    for(x in funky_characters)
	    {
	    	character = funky_characters[x];
	    	
	    	if(username.indexOf(character) >= 0)
	    	{
	    		char_valid = false;
	    	}
	    	
	    }
	           
	    if( char_valid == false )
	    {
	    	valid = false;
	    	msg += "<li>Your username must not contain any special characters, apart from . - or _</li>";    	
	    }    	
    	
    }
    
    if(!password1)
    {
    	valid = false;
    	msg += "<li>You didn't enter a password.</li>";    	
    }
    else
    {
		//check password between 6
	    if(password1.length < 6)
	    {
	    	valid = false;
	    	msg += "<li>Your password must be at least 6 characters long.</li>";    	
	    }
	    
	    //and 25 characters
	    if(password1.length > 24)
	    {
	    	valid = false;
	    	msg += "<li>Easy tiger. Your password must be less than 25 characters long.</li>";    	
	    }       	
    }
    
    if(!password2)
    {
    	valid = false;
    	msg += "<li>You didn't repeat your password.</li>";    	
    }       
              
    if(password1 && password2)
    {
	    // and that they match
	    if(password1 != password2)
	    {
	    	valid = false;
	    	msg += "<li>Oh no, your passwords don't match.</li>";    	
	    }      	
    }
    
    if(email && email2)
    {
	    // and that they match
	    if(email != email2)
	    {
	    	valid = false;
	    	msg += "<li>Oh no, your emails don't match.</li>";    	
	    }      	
    }    
              
    if(!agree_terms)
    {	    
    	valid = false;
    	msg += "<li>You must agree to our terms and conditions.</li>";    		          	
    }    
    
    if(valid == false)
    {
    	msg = "<h1>Uh oh!</h1>" +
    		  "<p>There were a few problems with your entries...</p>" +
    		  "<ul>" +
    		  	msg +
    		  "</ul>";
    		  
    	apprise(msg);
    }

    return valid;
	
}

function scrollToElement(element_id, highlight)
{
	new Effect.ScrollTo(element_id);	
	
	if(highlight == 1)	
	{
		//document.getElementById(element_id).style.border = "2px solid blue";
		Effect.Shake(element_id);
	}

	
}

function subscribeToMailingList()
{
	email_address = $('#mailing_list_email').val();
	
	if(email_address == "")
	{
		apprise("Please fill in your email addresss!");
		return false;
	}
	else if(!isEmailValid(email_address))
	{
		apprise("Sorry, but that doesn't appear to be a valid email address.");
		return false;		
	}
	else
	{
		$('#mailing_list').html('<br /><br /><br /><img src="/images/loading_green.gif" alt="Please wait..." />');
		
		url = "https://www.twinkl.co.uk/php/ajax/subscribeToMailingList.php?email=" + email_address;
		url = encodeURI(url);

		$('#mailing_list').load(url, function(data){
			
			$('#mailing_list').html("<p>You've been added to our lovely mailing list. Thank you!</p>" + data);
			
		});
	
		return true;
	}
}

function subscribeToMailing()
{

	if(document.mailing_list_form.subscribe_email.value == "" || !isEmailValid(document.mailing_list_form.subscribe_email.value))
	{
		apprise("Please make sure you provide a valid email address."); 
	}
	else
	{

		var email = document.mailing_list_form.subscribe_email.value;			
		document.getElementById("subscribe_email").disabled = "disabled";

		document.getElementById("subscribe").style.backgroundImage = "url('../images/button_sending.gif')";
		

		xmlHttp = GetXmlHttpObject()
	
		if (xmlHttp==null)
		{
			apprise ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "../php/ajax/subscribeToMailing.php?email=" + email;						
		url = url + "&sid=" + Math.random();
		xmlHttp.onreadystatechange = subscribedToMailing;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);

	
	}	
}



function subscribedToMailing() 
{ 
	if (xmlHttp.readyState==4)
	{ 
		document.getElementById("mailing_list").innerHTML=xmlHttp.responseText;
	}
}


function validate_photo_form()
{
    

    valid = true;

    if ( !$('#imagefile').val() || $("#category_id").attr("selectedIndex")==0 )
    {
        valid = false;
    }   
	
    
	if(valid == false)       
	{
        apprise ("Please make sure you've filled in every field.");		
	}
	   

    return valid;
	
}

function IsToolbarVisible()
{
/*	var resultDiv = document.getElementById('result');
	
	resultDiv.innerHTML = "";*/
	
	var oToolbar = new TPI.Toolbar("CT2676929");
	
	var oReturn = oToolbar.IsVisible();
	
	select_resource_id = document.getElementById('resource_id').value;
	
	if(oReturn.returnValue)
	{
		//resultDiv.innerHTML = "The Toolbar identified as twinkl is installed and visible<br/>";
/*		apprise("YES toolbar");
*/		xmlHttp = GetXmlHttpObject()
		
		if (xmlHttp==null)
		{
			apprise ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "../php/ajax/getSelectResource.php?id=" + select_resource_id;				
		url = url + "&sid=" + Math.random();
		xmlHttp.onreadystatechange = getSelectResource;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);	
		
	}
	else
	{
		/*apprise("NO toolbar");*/
		
		var html = '<a href="#" id="conduit_download">' +
						'<p>' +
							'This free resource is select - that means it\'s only available to download if you are using our helpful toolbar. Download it for free to grab this wonderful teaching resource.' +
						'</p>' +
				   '</a>';
		
		document.getElementById('resource_info_conduit').innerHTML = html;
		
		document.getElementById('resource_info_area').setAttribute("class", "select_unavailable");
		//resultDiv.innerHTML = "The Toolbar identified as twinkl is not installed or not visible, Error Code: " + oReturn.errorCode + "<br/>";
	}

}


function getSelectResource()
{ 
	if (xmlHttp.readyState==4)
	{ 
		document.getElementById("download_result").innerHTML=xmlHttp.responseText;
	}
	
}



function IsToolbarVisible_session()
{
	var oToolbar = new TPI.Toolbar("CT2676929");
	
	var oReturn = oToolbar.IsVisible();
	
	if(oReturn.returnValue)
	{
			
		xmlHttp = GetXmlHttpObject()
		
		if (xmlHttp==null)
		{
			apprise ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "../php/ajax/setToolbarSession.php";				
		url = url + "?sid=" + Math.random();
		xmlHttp.onreadystatechange = sessionSet;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);			
	}
	else
	{
	
		xmlHttp = GetXmlHttpObject()
		
		if (xmlHttp==null)
		{
			apprise ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "../php/ajax/unsetToolbarSession.php";				
		url = url + "?sid=" + Math.random();
		xmlHttp.onreadystatechange = sessionSet;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);	
	}

}

function sessionSet()
{
	if (xmlHttp.readyState==4)
	{ 
		//apprise(xmlHttp.responseText);
		history.go(0);
	}
}

function recommendBook(category_id, book_id)
{
	xmlHttp = GetXmlHttpObject()
	
	if (xmlHttp==null)
	{
		apprise ("Your browser does not support AJAX!");
		return;
	} 
	
	var url = "../php/ajax/recommendBook.php";
	url = url + "?category_id=" + category_id;
	url = url + "&book_id=" + book_id;
	url = url + "&sid=" + Math.random();
	xmlHttp.onreadystatechange = bookRecommended;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function bookRecommended()
{ 
	if (xmlHttp.readyState==4)
	{ 		
		element = xmlHttp.responseText;
		
		document.getElementById(element).style.background = "url('../images/recommended_book.gif') no-repeat";		
	}
	
}


function showSignIn()
{
	document.getElementById("signin").style.display = "block";
}

function hideSignIn()
{
	document.getElementById("signin").style.display = "none";
}

function validate_signin_form()
{
    

    valid = true;

    if ( document.signin_form.username.value == "" || document.signin_form.password.value == "" )
    {
        valid = false;
    }   
	
    
	if(valid == false)       
	{
        apprise ("Please make sure you've filled in both your username and password!");		
	}
	   

    return valid;
	
}



function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function validate_stockavatar_form()
{
	
	radvalue = getCheckedValue(document.forms['stockavatar_form'].elements['stock_avatar']);
    
	valid = true;

    if ( radvalue == "")
    {
        valid = false;
    }   
	
    
	if(valid == false)       
	{
        apprise("<h2>Erm...</h2>Did you forget to select which picture you'd like?");		
	}
	   

    return valid;
    
}

function validate_avatar_form()
{
	   
	valid = true;

    if ( document.getElementById("imagefile").value == "" )
    {
        valid = false;
    }   
	
    
	if(valid == false)       
	{
        apprise("<h2>Oh dear...</h2>Did you forget to choose a picture by using the 'browse' button?");		
	}
	   

    return valid;
    
}

function submitComment()
{
	 
	
	if(!$('textarea#comment').val() || $('textarea#comment').val() == " " || $('textarea#comment').val() == "Comment on this resource..." || $('textarea#comment').val() == "Comment on this book..." || $('textarea#comment').val() == "Comment on this event..." || $('textarea#comment').val() == "Comment on this display..." || $('textarea#comment').val() == "Comment on this news..." || $('textarea#comment').val() == "Comment on this user..." || $('textarea#comment').val() == "Comment on this shared resource..." || $('textarea#comment').val() == "Comment on this resource pack...")
	{
		apprise("<h2>Uh oh!</h2>You didn't enter a comment!");
	}
	else	
	{
		var_comment = $('textarea#comment').val();
				
		var_comment = var_comment.replace(new RegExp( "\\n", "g" ), "<br />");
		
		limit = $("#comments > li").size();
		
		xmlHttp = GetXmlHttpObject()
		
		if (xmlHttp==null)
		{
			apprise ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "../php/ajax/submitComment.php?comment=" + var_comment;
		url = url + "&limit=" + limit;
		url = url + "&type=" + $('input#comment_type').val();
		url = url + "&item_id=" + $('input#comment_item_id').val();
		url = url + "&sid=" + Math.random();
		xmlHttp.onreadystatechange = commentSubmit;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}
}

function commentSubmit()
{ 
	if (xmlHttp.readyState==4)
	{ 		
		response = xmlHttp.responseText;
		
		document.getElementById("comments_container").innerHTML = response;		
		
		$('#first_comment').css('display', 'none');
		$('#first_comment').slideDown('slow');
	}	
}

function moreComments()
{
	limit = $("#comments > li").size();
	limit = limit + 5;
	
	xmlHttp = GetXmlHttpObject()
	
	if (xmlHttp==null)
	{
		apprise ("Your browser does not support AJAX!");
		return;
	} 
	
	var url = "../php/ajax/moreComments.php?limit=" + limit;
	url = url + "&type=" + $('input#comment_type').val();
	url = url + "&item_id=" + $('input#comment_item_id').val();
	url = url + "&sid=" + Math.random();
	xmlHttp.onreadystatechange = commentsMorededed;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);	
}

function commentsMorededed()
{ 
	if (xmlHttp.readyState==4)
	{ 		
		response = xmlHttp.responseText;
		
		document.getElementById("comments_container").innerHTML = response;		
		
		$('html, body').animate({scrollTop: $("#scroll_comment").offset().top}, 1500);
		
	}	
}


function reportComment(id)
{	 		
	xmlHttp = GetXmlHttpObject()
	
	if (xmlHttp==null)
	{
		apprise ("Your browser does not support AJAX!");
		return;
	} 
	
	limit = $("#comments > li").size();
	
	var url = "../php/ajax/reportComment.php?comment_id=" + id;
	url = url + "&type=" + $('input#comment_type').val();
	url = url + "&item_id=" + $('input#comment_item_id').val();
	url = url + "&limit=" + limit;
	url = url + "&sid=" + Math.random();
	xmlHttp.onreadystatechange = commentReported;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);

}

function commentReported()
{ 
	if (xmlHttp.readyState==4)
	{ 		
		response = xmlHttp.responseText;
		
		document.getElementById("comments_container").innerHTML = response;		

	}	
}


function like(type, id, mini)
{
	element_id = "#like_" + type + "_" + id;
	
	load_url = "../php/ajax/like.php?type=" + type + "&id=" + id + "&mini=" + mini;

	$(element_id).load(load_url);		

}


function unlike(type, id, mini)
{
	element_id = "#like_" + type + "_" + id;
	
	load_url = "../php/ajax/unlike.php?type=" + type + "&id=" + id + "&mini=" + mini;

	$(element_id).load(load_url);		

}

function moreLikers(type, id)
{
	element_id = "#more_likers_" + type + "_" + id;
	element_id2 = "#show_more_likers_" + type + "_" + id;
	
	$(element_id2).hide();	
	$(element_id).fadeIn();
}

function validate_event_form()
{
	valid = true;
	msg = "";
	
	if( !$('#title').val() )
	{
		valid = false;
		msg += "<li>The title of the event</li>";
	}
	
	if( $("#month").attr("selectedIndex") == 0 )
	{
		valid = false;
		msg += "<li>Month of the event</li>";
	}
	
	if( !$('#description').val() )
	{
		valid = false;
		msg += "<li>A brief description of the event</li>";
	}
	
	if(valid == false)
	{
		msg = "<p>You forgot to fill in some fields...</p>\n" +
				"<ul>" +
					msg +
				"</ul>";
				
		apprise(msg);
	}
	
	return valid;		
	
}


function addFriend(user_id)
{

	load_url = "../php/ajax/addFriend.php?user_id=" + user_id;

	$('#friend_status').load(load_url);		

}

function unFriend(user_id)
{

	load_url = "../php/ajax/unFriend.php?user_id=" + user_id;

	$('#friend_status').load(load_url);		

}

function showMoreFriends()
{		
	$('#friends_more').hide();	
	$('.hide').fadeIn();
}


function validate_shared_form()
{
	valid = true;
	msg = "";
	
	
	var ext = $('#resource_file').val().split('.').pop().toLowerCase();
	
	if($.inArray(ext, ['doc','docx','pub','pubx', 'pdf', 'ppt', 'pptx']) == -1) {
		valid = false;
		msg += "<li>The file must be a Word document, Powerpoint presentation, Publisher document, or a PDF</li>";
	}
	
	
	if( !$('#resource_file').val() )
	{
		valid = false;
		msg += "<li>The file to upload</li>";
	}

	if( !$('#title').val() )
	{
		valid = false;
		msg += "<li>Title of the resource</li>";
	}	

	if( !$('#description').val() )
	{
		valid = false;
		msg += "<li>A brief description of the resource</li>";
	}
	
	if( !$('#useful_for').val() )
	{
		valid = false;
		msg += "<li>What your resource is useful for</li>";
	}			
	
	if( $("#category_id").attr("selectedIndex") == 0 )
	{
		valid = false;
		msg += "<li>Resource category</li>";
	}
	
	
	if(valid == false)
	{
		msg = "<p>You didn't fill in some fields correctly...</p>\n" +
				"<ul>" +
					msg +
				"</ul>";
				
		apprise(msg);
	}
	
	return valid;		
	
}

function insertSharedResource()
{
	valid = true;
	msg = '';
	
	if(!$('#filename').val())
	{
		valid = false;
		msg += '<li>The file to upload</li>';
	}
	
	if(!$('#title').val())
	{
		valid = false;
		msg += '<li>Title of your resource</li>';
	}
	
	if(!$('#description').val())
	{
		valid = false;
		msg += '<li>A brief description</li>';
	}
	
	if(!$('#useful_for').val())
	{
		valid = false;
		msg += '<li>What the resource is useful for</li>';
	}
	
	if( $("#category_id").attr("selectedIndex") == 0 )
	{
		valid = false;
		msg += "<li>Resource category</li>";
	}
	
	if(!valid)
	{
		msg = 'You forgot to fill in some important bits...' +
				'<ul>' +
					msg +
				'</ul>';
				
		apprise(msg);
	}
	else
	{
		url = '../php/ajax/insertSharedResource.php' +
			  '?filename=' + $('#filename').val() +
			  '&title=' + $('#title').val() +
			  '&description=' + $('#description').val() +
			  '&useful_for=' + $('#useful_for').val() +
			  '&category_id=' + $('#category_id').val();
		
		url = encodeURI(url);
		
		$('#submit_shared').load(url);
	}
	
	return valid;
}

function insertSharedResource_new()
{
	valid = true;
	msg = '';
	
	if(!$('#filename').val())
	{
		valid = false;
		msg += '<li>The file to upload</li>';
	}
	
	if(!$('#title').val())
	{
		valid = false;
		msg += '<li>Title of your resource</li>';
	}
	
	if(!$('#description').val())
	{
		valid = false;
		msg += '<li>A brief description</li>';
	}
	
	if(!$('#useful_for').val())
	{
		valid = false;
		msg += '<li>What the resource is useful for</li>';
	}
	
	if( $("#category_id").attr("selectedIndex") == 0 )
	{
		valid = false;
		msg += "<li>Resource category</li>";
	}
	
	if(!valid)
	{
		msg = 'You forgot to fill in some important bits...' +
				'<ul>' +
					msg +
				'</ul>';
				
		apprise(msg);
	}
	else
	{
		url = '../php/ajax/insertSharedResource_new.php' +
			  '?filename=' + $('#filename').val() +
			  '&title=' + $('#title').val() +
			  '&description=' + $('#description').val() +
			  '&useful_for=' + $('#useful_for').val() +
			  '&category_id=' + $('#category_id').val();
		
		url = encodeURI(url);
		
		$('#submit_shared').load(url);
	}
	
	return valid;
}

function checkIfUsernameExists()
{
   	username = $('#username').val();
   	
  	var url = "https://www.twinkl.co.uk/php/ajax/checkIfUsernameExists.php?username=" + username;
  	url = encodeURI(url);
  	
  	$('#username_response').load(url, function(data){
		 
		if(data != "")
		{
			$('#username_response').slideDown('fast');
		}
		else
		{
			$('#username_response').slideUp('fast');
		}
		
  	})	
}

function checkIfEmailExists()
{
   	email = $('#email_address').val();
   	
  	var url = "https://www.twinkl.co.uk/php/ajax/checkIfEmailExists.php?email=" + email;
  	url = encodeURI(url);
  	
  	$('#email_response').load(url, function(data){
		 
		if(data != "")
		{
			$('#email_response').slideDown('fast');
		}
		else
		{
			$('#email_response').slideUp('fast');
		}
		
  	})
  		
}

function validate_details_form()
{
	email = $('#email_address').val();
    
    var msg = '';
    var valid = true; 
        			
    //check all requiredness is there
    if(!email)
    {
    	valid = false;
    	msg += "<li>Your email is missing.</li>";    	
    }
    else
    {
    	//check email valid
	    if(!isEmailValid(email))
	    {
	    	valid = false;
	    	msg += "<li>The email you entered doesn't appear to be correct.</li>";
	    }
    }	
    
    if(valid == false)
    {
    	msg = "<h1>Uh oh!</h1>" +
    		  "<p>There was a problem...</p>" +
    		  "<ul>" +
    		  	msg +
    		  "</ul>";
    		  
    	apprise(msg);
    }    
    
    return valid;
}


function validate_password_retrieval_form()
{
	valid = true;
	
	if( !$('#email_address').val() || !isEmailValid($('#email_address').val()))
	{
		valid = false;
	}
	
	if(!valid)
	{
		apprise('Please enter a valid email address. Thanks!');
	}
	
	return valid;
}

function validate_book_form()
{	
	request = $('#request').val();
	author = $('#author').val();
    
    var msg = '';
    var valid = true; 
        			
    if($("#book_category_id").attr("selectedIndex") == 0)
    {
    	valid = false;
    	msg += "<li>Please choose a category for the book.</li>";
    }
    
    if(!request)
    {
    	valid = false;
    	msg += "<li>You didn't tell us which book you'd like to suggest.</li>";    	
    }
    
    if(!author)
    {
    	valid = false;
    	msg += "<li>You didn't tell us who the author is.</li>";    	
    }            
    
    if(valid == false)
    {
    	msg = "<h1>Uh oh!</h1>" +
    		  "<p>There was a problem...</p>" +
    		  "<ul>" +
    		  	msg +
    		  "</ul>";
    		  
    	apprise(msg);
    }    
    
    return valid;
}


function validate_password_form()
{
    
    password1 = $('#password1').val();
    password2 = $('#password2').val();
    old_password = $('#old_password').val();
    
    var msg = '';
    var valid = true; 
        
    if(!password1)
    {
    	valid = false;
    	msg += "<li>You didn't enter a new password.</li>";    	
    }
    else
    {
		//check password between 6
	    if(password1.length < 6)
	    {
	    	valid = false;
	    	msg += "<li>Your new password must be at least 6 characters long.</li>";    	
	    }
	    
	    //and 25 characters
	    if(password1.length > 24)
	    {
	    	valid = false;
	    	msg += "<li>Easy tiger. Your new password must be less than 25 characters long.</li>";    	
	    }       	
    }
    
    if(!password2)
    {
    	valid = false;
    	msg += "<li>You didn't repeat your new password.</li>";    	
    }       
              
    if(password1 && password2)
    {
	    // and that they match
	    if(password1 != password2)
	    {
	    	valid = false;
	    	msg += "<li>Oh no, your passwords don't match.</li>";    	
	    }      	
    }
    
    if(!old_password)
    {
    	valid = false;
    	msg += "<li>You didn't enter your current password.</li>";    	
    }        
    
    if(valid == false)
    {
    	msg = "<h1>Uh oh!</h1>" +
    		  "<p>There were a few problems with your entries...</p>" +
    		  "<ul>" +
    		  	msg +
    		  "</ul>";
    		  
    	apprise(msg);
    }

    return valid;
	
}


function addToBasket(resource_id, alt_id, pack_id, action)
{
	//$('#basket_contents').slideUp('fast', function(){
		$('#basket_wrapper > h2').css("background-image", "url('../images/basket_loader.gif')");  
		
		url = '../php/ajax/addToBasket.php' +
			  '?resource_id=' + resource_id +
			  '&alt_id=' + alt_id +
			  '&pack_id=' + pack_id +
			  '&action=' + action;
		
		url = encodeURI(url);
		
		if(resource_id != 0)
		{
			item_id = resource_id;
			type_id = 1;  
		}
		else if(alt_id != 0)
		{
			item_id = alt_id;
			type_id = 2;			
		}
		else if(pack_id != 0)
		{
			item_id = pack_id;
			type_id = 3;			
		}
		
		$('#basket_contents_wrapper').load(url, function(){
			
			$('#basket_wrapper > h2').css("background-image", "url('../images/basket_icon.gif')");

			target_index = $("#basket_" + type_id + "_" + item_id).index();							
			scroll_top =  $('#basket_contents').scrollTop();				
			target_top = target_index * 95;
			scroll_bottom = scroll_top + 190;

			if( !(target_top > scroll_top && target_top < scroll_bottom) )
			{
				target = $("#basket_contents > li").eq(target_index);
				scrollBasket(target);
			}
			
			basket_count = $('#basket_contents > li').length;

			if(basket_count > 2)
			{
				$('#basket_up').fadeTo('slow', 0.5, 'easeOutExpo');
				$('#basket_down').fadeTo('slow', 1, 'easeOutExpo');
			}
			else
			{
				$('#basket_up').fadeTo('slow', 0.5, 'easeOutExpo');
				$('#basket_down').fadeTo('slow', 0.5, 'easeOutExpo');		
			}
			
			if(basket_count == 1)
			{
				//$('#basket_contents').animate({height: '104px'});	
				$('#basket_contents').height('104px');
			}
			
		});
		
	//});
}

function scrollBasket(direction)
{
		
	if(direction == 'down')
	{
		target = '+=190px';
		duration = 1200;
	}
	else if(direction == 'up')
	{
		target = '-=190px';
		duration = 1200;
	}
	else
	{
		target = direction;
		duration = 0;
	}
	
	$('#basket_contents').scrollTo(target, duration, {axis:'y', easing: 'easeInOutExpo', onAfter:function(){
		
		scroll_top =  $('#basket_contents').scrollTop();
		
		if(scroll_top == 0)
		{
			$('#basket_up').fadeTo('slow', 0.5, 'easeOutExpo');
		}
		else
		{
			$('#basket_up').fadeTo('slow', 1, 'easeInExpo');
		}
		
		basket_count = $('#basket_contents > li').length;
		bottom = (basket_count - 2) * 95;
				
		if(scroll_top >= bottom)
		{
			$('#basket_down').fadeTo('slow', 0.5, 'easeOutExpo');
		}
		else
		{
			$('#basket_down').fadeTo('slow', 1, 'easeInExpo');
		}
		
	} });
}


function addToBasket_checkout(resource_id, alt_id, pack_id, action)
{
			
	url = '../php/ajax/addToBasket_checkout.php' +
		  '?resource_id=' + resource_id +
		  '&alt_id=' + alt_id +
		  '&pack_id=' + pack_id +
		  '&action=' + action;
	
	url = encodeURI(url);
	
	$('#checkout_wrapper').load(url, function(){
		
		//
				
	});
	
}

function checkout()
{
	document.checkout_form.submit();
	$('#checkout_wrapper').fadeTo('slow', 0.2);
}

function showDashyExtra(target)
{
	$('#overlay').fadeTo(500, 0.7);
	
	$('.dashy_extra').hide();
	$('#' + target).slideDown();
	
	$('html, body').animate({scrollTop: $("#" + target).offset().top}, 1500, 'easeOutExpo');
}

function closeDashyExtra()
{
	$('#overlay').fadeOut(500, function(){
		
		$('.dashy_extra').slideUp();
			
	});
	
}

function moreDashy()
{
	$('#dashy > li').removeClass('new');
	
	size = $('#dashy > li').size();
	
	url = '../php/ajax/moreDashy.php?count=' + size;
	
	url = encodeURI(url);
	
	$.get(url, function(data){
		
		$('#dashy').append(data);
			
		$('html, body').animate({scrollTop: $(".new").offset().top}, 1500, 'easeOutExpo');
				
	});
	
}

function validate_mailing_form()
{
    
    valid = true;
    
    email = $('#ymlp_email').val();

    if ( !email || !isEmailValid(email) )
    {
        valid = false;
    }   
	
    
	if(valid == false)       
	{
        apprise ("Please make sure you've filled in your email address correctly.");		
	}
	else
	{
		url = '../php/ajax/mailingListReward.php';	
		url = encodeURI(url);		
		$.post(url);	
	}
	   

    return valid;
	
}

function getFacebookReward()
{
	url = '../php/ajax/facebookReward.php';	
	url = encodeURI(url);		
	$.post(url);		
}

function getTwitterReward()
{
	url = '../php/ajax/twitterReward.php';	
	url = encodeURI(url);		
	$.post(url);		
}

function sendInviteEmails()
{
	var emails = new Array();
	valid = true;
	msg = "";
	
	$('#invite_emails > input').each(function(){
		
		email = false;
		email = $(this).val();
		
		if(email)
		{
			if(isEmailValid(email))
			{
				emails.push(email);
			}
		}		
				
	});
	
	if(emails.length == 0)
	{
		valid = false;
		msg += "You didn't enter any valid emails!<br />";
	}
	
	if(!valid)
	{
		apprise(msg);
	}
	else
	{
		$('#invite_emails').html('<img src="/images/loading_small.gif" alt="Loading" />');
		
		url = 'https://www.twinkl.co.uk/php/ajax/sendEmailInvites.php?emails=';
		//url = '../php/ajax/sendEmailInvites.php?emails=';
		
		for(x in emails)
		{			
			url += emails[x] + '!';
		}				
		
		url = url.slice(0, - 1);
		
		$('#invite_emails').load(url);
	}
	
}

function studentSignUp()
{	
	valid = true;
		
	first_name = $('#student_first_name').val();
	last_name = $('#student_last_name').val();
	place_of_study = $('#place_of_study').val();
	tutor_name = $('#tutor_name').val();
	tutor_email = $('#tutor_email').val();
	tutor_tel = $('#tutor_tel').val();
	country = $('#country').val();			
	nus_number = $('#nus_number').val();	
	
	if(!first_name || !last_name || !place_of_study || !tutor_name || !tutor_email || !tutor_tel || !country)
	{
		valid = false;
	}	
	
	if(country == 225 && !nus_number)
	{
		valid = false;		
	}				
	
	if(!valid)
	{
		apprise("Please make sure all fields are complete.");
	}
	else if(!isEmailValid(tutor_email))
	{
		apprise("Please make sure the email address entered is correct.");
	}	
	else
	{		
		url = 'https://www.twinkl.co.uk/php/ajax/studentSignUp.php?' +
			  'first_name=' + first_name + '&' +
			  'last_name=' + last_name + '&' +
			  'place_of_study=' + place_of_study + '&' +
			  'tutor_name=' + tutor_name + '&' +
			  'tutor_email=' + tutor_email + '&' +
			  'tutor_tel=' + tutor_tel + '&' +
			  'country=' + country + '&' +
			  'nus_number=' + nus_number;
		
		url = encodeURI(url);
		
		$('#student_form').load(url);
	}	
	
}
	
