var friendName;  //used to store the name of the person who asked a question so we can pass it on to the friend in the email

//delay function
jQuery.fn.delay = function(time,func){
	this.each(function(){
		setTimeout(func,time);
	});

	return this;
};

function getUpdates() {
	$("#loading").ajaxStart(function(){
	   $(this).show();
	 });

	// Controls the PREV button
	   $("#prevMonth").click(function() {
			$("#loading").show();
			var month = $(this).parent().parent().prev().attr("id");
	   		var showMonth = $(this).parent().parent().prev();
	
					//show the appropriate html for the data
					$.ajax({
					  url: month,
					  cache: false,
					  success: function(html){
						
						$(".currentMonthUpdates").contents().remove();
						$(showMonth).fadeIn("slow").append(html);
						$("#loading").hide();
						
					  }
					}); //end ajax
			});
			
			// Controls the Next button
		   $("#nextMonth").click(function() {
				$("#loading").show();
				var month = $(this).parent().parent().next().attr("id");
		   		var showMonth = $(this).parent().parent().next();
					//show the appropriate html for the data
					$.ajax({
					  url: month,
					  cache: false,
					  success: function(html){

						$(".currentMonthUpdates").contents().remove();
						$(showMonth).fadeIn("slow").append(html);
						$("#loading").hide();

					  }
					}); //end ajax
			});
	}

	// ajax call for the star people profile pages
	function getStarPeople() {
		
		$(".personProfile #starPeople li a").click(function() {
				
				//need to append this to the url ?alttemplate=peopleprofilecontent				
				
				$("#loading").show();
				$("#starPeople li").removeClass("active");
			
				$(this).parent().addClass("active");

				var personUrl = $(this).attr('href');
				var re = /\s*((\S+\s*)*)/;

				//need to transform the url from /people|light-profiles?id=max to /people-profiles/max
				url = personUrl.split('?');
				newUrl = url[0].replace(re, '$1') + '/' + url[1].split('=')[1];

				var jsPersonUrl;
				//switch id depending on light/people profile
				if (url[0].replace(re, '$1') == '/people-profiles'){
					$(".personProfile").attr("id", "starPersonProfile");
					jsPersonUrl = newUrl + '?alttemplate=peopleprofilecontent';
				}else{
					$(".personProfile").attr("id", "standardPersonProfile");
					jsPersonUrl = newUrl + '?alttemplate=lightprofilecontent';
				}
		   		
						//show the appropriate html for the data
						$.ajax({
						  url: jsPersonUrl,
						  cache: false,
						  success: function(html){

							$("#ourStar").contents().remove();
							$("#ourStar").hide().append(html).fadeIn('fast');
							$("#loading").hide();

						  }
						}); //end ajax
		});
		
	}


	jQuery.fn.liScroll = function(settings) {
		settings = jQuery.extend({
		travelocity: 0.03
		}, settings);		
		return this.each(function(){
				var $strip = jQuery(this);
				$strip.addClass("newsticker")
				var stripWidth = 0;
				var $mask = $strip.wrap("<div class='mask'></div>");
				var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
				var containerWidth = $strip.parent().parent().width();	//a.k.a. 'mask' width 	
				
				var stripWidth = 0;
				
				$('#ttCopy li').each(function() {
				    
					sWidth = $(this).outerWidth();
					
					//console.log(sWidth)
				
					stripWidth += $(this).outerWidth( true );
					
				});
				
				//$('.mask').css({'width' : stripWidth + 5000});
				
				$('#ttCopy').css({'width': stripWidth + 300})
				
				//console.log(stripWidth);
				
				var defTiming = stripWidth/settings.travelocity;
				var totalTravel = stripWidth+containerWidth;								
				function scrollnews(spazio, tempo)	{
					$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
					}
				scrollnews(totalTravel, defTiming);				
				$strip.hover(function(){
					jQuery(this).stop();
					},
				function(){
					var offset = jQuery(this).offset();
					var residualSpace = offset.left + stripWidth;
					var residualTime = residualSpace/settings.travelocity;
					scrollnews(residualSpace, residualTime);
					});			
				});	
			};





	

/*-- main js--*/
$(document).ready(function(){
	
	//main nav sub nav triggers
	$('ul#mainNav li').hover(function () {
		
		if ($(this).hasClass("thePeople")){
		
			$(this).addClass('tpActive');
		}
				
		var subPosition = $(this).position();
			
			//console.log(subPosition.left)
		
			$(this).children('ul').css({'left' : subPosition.left }).show();
			
			
		},
		// on mouse out
		function () {
			$(this).children('ul').hide();
			$(this).removeClass('tpActive');
		});

	// create the hidden overflows on our carousel elements
	// when js is off natural scroll bars will show so still useable.
	$("#friendsInner, #bestBitsFrame, #otherJobsList").css({'overflow' : 'hidden'});
	
	// replace the anchor link for questions and answers
	$("#callQa, #followMyPath").attr({'href' : '#content'});

	//read on and Q&A frames
	//hide everything with js so if no js we can still use it (anchor to content).
	$("#readOnFrame, #qaFrame, #pathFrame").css({
		opacity: "0",
		position: "absolute", 
		display: "none",
		width: "0",
		height: "0"
		});
	
	$("a#callReadOn").click(function() {
		//get the position of friends so we can calculate the height for the overlay	
		rocHeight = $('#friends').position();
		
		//animate the read on overlay in // some maths to positin it correctly
		$("#readOnFrame").animate( { height: rocHeight.top -355 }, { queue:false, duration:400 });
	    	$("#readOnFrame").animate( { width: "752px" } , 650);
		$("#readOnFrame").animate( { opacity: "1" } , { queue:false, duration:300 });
		$('#qaScroller').jScrollPane({showArrows:true});

		});

	$("a#closeReadOn").click(function(){	
		//animate the read on overlay out
		$("#readOnFrame").animate( { height: "0" }, { queue:false, duration:400 });
	    	$("#readOnFrame").animate( { width: "0" } , 650);
		$("#readOnFrame").animate( { opacity: "0" } , { queue:false, duration:300 });
		$("#readOnFrame").fadeOut();	
		});
		
	$("a#callQa").click(function() {
		
		var btm1 = $("#askAboutJob").position();	
		var btm2 = $("#content").height();
		
		//console.log( btm1.top );
		//console.log( btm2 );
		//console.log( btm2 - btm1.top)
		
		qafHeight = $('#friends').position();
		
		$("#qaFrame").css( { bottom: btm2 - btm1.top -32});
		
		if (jQuery.browser.msie) { 
		  if(parseInt(jQuery.browser.version) == 6) { 
		      	$("#qaFrame").css( { bottom: btm2 - btm1.top - 5});
		  } 
		}
		
		//animate the read on overlay in
		$("#qaFrame").animate( { height: qafHeight.top -357 }, { queue:false, duration:400 });
		$("#qaFrame").animate( { width: "752px" } , 650);
		$("#qaFrame").animate( { opacity: "1" } , { queue:false, duration:600 });
		$('#userqaScroller').jScrollPane({showArrows:true});
	});
	
	$("a#closeQa").click(function(){
		
		//animate the read on overlay out
		$("#qaFrame").animate( { height: "0" }, { queue:false, duration:400 });
	    	$("#qaFrame").animate( { width: "0" } , 650);
		$("#qaFrame").animate( { opacity: "0" } , { queue:false, duration:300 });
		$("#qaFrame").fadeOut();
		
		});

	$("a#followMyPath").click(function() {

		var btm1 = $("#askAboutJob").position();	
		var btm2 = $("#content").height();

		qafHeight = $('#friends').position();

		$("#pathFrame").css( { bottom: btm2 - btm1.top -32});

		if (jQuery.browser.msie) { 
		  if(parseInt(jQuery.browser.version) == 6) { 
		      	$("#pathFrame").css( { bottom: btm2 - btm1.top - 5});
		  } 
		}

		//animate the read on overlay in
		$("#pathFrame").animate( { height: qafHeight.top -357 }, { queue:false, duration:400 });
		$("#pathFrame").animate( { width: "752px" } , 650);
		$("#pathFrame").animate( { opacity: "1" } , { queue:false, duration:600 });

	});

	$("a#closePath").click(function(){
		
		//animate the read on overlay out
		$("#pathFrame").animate( { height: "0" }, { queue:false, duration:400 });
	    	$("#pathFrame").animate( { width: "0" } , 650);
		$("#pathFrame").animate( { opacity: "0" } , { queue:false, duration:300 });
		$("#pathFrame").fadeOut();
		
		});

	//call the contact us form
	$("#callContactUs,#callContactUs2").click(function() {
		if ($("#contactUs").size() > 0){
			$("#contactUs").modal();
		}
		$('input').each(function() {
			$(this).watermark($(this).attr('watermark'));
		});
		$('textarea').each(function() {
			$(this).watermark($(this).attr('watermark'));
		});
	});
	//contact us form functionlity
	$("#sendContactUsForm").click(function() {
		var name = $("#yourName").val();
		var email = $("#yourEmail").val();
		var text = $("#yourMessage").val();
		emailRegex = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 

		if (name == '' || name == 'name'){
			$("dd.contactUsError").html('Please enter your name');
			$(".contactUsError").show();
		}else if (email == '' || email == 'email' || !email.match(emailRegex)){
			$("dd.contactUsError").html('Please enter a valid email address');
			$(".contactUsError").show();
		}else if (text == '' || text == 'enter your message'){
			$("dd.contactUsError").html('Please enter a message');
			$(".contactUsError").show();
		}else{
			//send email
			//call ajax function to save message
			$.ajax({
				type: 'POST',
				url: '../umbraco/webservices/sftgservices.asmx/SendEmail',
				data: '{username:"wsUser", password:"Zonepa55", name:"' + name + '", email:"' + email + '", body:"' + text + '"}',
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(msg){
					if (msg == 'success'){
						$("#contactUsForm").html('<span style="font-size:1.6em;font-weight:bold;line-height:1.2em;">Thanks for contacting us, we have received your message and will get back to you shortly. <br /><br />Making the Games Team</span>');
					}else{
						$("#contactUsForm").html('<span style="font-size:1.6em;font-weight:bold;line-height:1.2em;">There was a problem sending your message.</span>');
					}
				},
				error: function(msg){
					$("#contactUsForm").html('<span style="font-size:1.6em;font-weight:bold;line-height:1.2em;">There was a problem sending your message.</span>');
				}
			});
		}
	});

	//calls the thanks for question
	$("#callThanksQuestion").click(function() {
		var question = $("#txtAskAQuestion").val();
		var name = $("#txtAskAQuestionName").val();
		var email = $("#txtAskAQuestionEmail").val();
		var personId = $(this).attr("rel");
		emailRegex = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 

		if (name == '' || name == 'your name*'){
			$("#askAQuestionError").html('<br />Please enter your name');
			$("#askAQuestionError").show();
		}else if (email == '' || email == 'your email*' || !email.match(emailRegex)){
			$("#askAQuestionError").html('<br />Please enter a valid email address');
			$("#askAQuestionError").show();
		}else if (question == '' || question == 'go on...I hope I can answer it!'){
			$("#askAQuestionError").html('<br />Please enter a question');
			$("#askAQuestionError").show();
		}else{
			//call ajax function to save message
			$.ajax({
				type: 'POST',
				url: '../umbraco/webservices/sftgservices.asmx/AddUserQuestion',
				data: '{username:"wsUser", password:"Zonepa55", question:"' + question + '", personId:' + personId + ', name:"' + name + '", email:"' + email + '"}',
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				successs: function(msg){
					//alert(msg);
				},
				error: AJAXError
			});
			$("#thanksQuestion").modal();
			$('input').each(function() {
				$(this).watermark($(this).attr('watermark'));
			});
			$('textarea').each(function() {
				$(this).watermark($(this).attr('watermark'));
			});

			//clear boxes
			$("#txtAskAQuestion").val('go on...I hope I can answer it!');
			$("#txtAskAQuestionName").val('your name*');
			$("#txtAskAQuestionEmail").val('your email*');

			//remember the name for sending an email to a friend
			//$("#hiddenSenderName").val(name);
			friendName = name;
		}
	});
	//send friend form functionlity
	$("#sendFriendsContactUsForm").click(function() {
		var name = $("#tqFriendsName").val();
		var email = $("#tqFriendsEmail").val();
		var text = $("#tqYourMessage").val();
		emailRegex = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 

		if (name == '' || name == 'name'){
			$("dd.friendsContactUsError").html('Please enter your friends name');
			$(".friendsContactUsError").show();
		}else if (email == '' || email == 'email' || !email.match(emailRegex)){
			$("dd.friendsContactUsError").html('Please enter a valid email address');
			$(".friendsContactUsError").show();
		}else if (text == ''){
			$("dd.friendsContactUsError").html('Please enter a message');
			$(".friendsContactUsError").show();
		}else{
			//send email
			//call ajax function to save message
			$.ajax({
				type: 'POST',
				url: '../umbraco/webservices/sftgservices.asmx/SendEmailToFriend',
				data: '{username:"wsUser", password:"Zonepa55", name:"' + name + '", email:"' + email + '", body:"' + text + '", fromName:"' + friendName + '"}',
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(msg){
					if (msg == 'success'){
						$("#friendsContactUsForm").html('<span style="font-size:1.6em;font-weight:bold;line-height:1.2em;">Your message has been sent.</span>');
					}else{
						$("#friendsContactUsForm").html('<span style="font-size:1.6em;font-weight:bold;line-height:1.2em;">There was a problem sending your message.</span>');
					}
				},
				error: function(msg){
					$("#friendsContactUsForm").html('<span style="font-size:1.6em;font-weight:bold;line-height:1.2em;">There was a problem sending your message.</span>');
				}
			});
		}
	});


	//calls the thanks for message
	$("#callThanksMessage").click(function() {$("#thanksMessage").modal();});
	
	//share this slide out
		$("#tyfContent").css({opacity:0});
	
		$("#tellYourFriends").hover(function(){
			
			$(this).animate({'width' : '200px'}, 80);
			
			$(this).delay(80,function(){
			
				$("#tyfContent").animate({opacity:1}, 200);
			});	
		},
		
		function() {
			
			$("#tyfContent").animate({opacity:0}, 200);
			
			$(this).delay(200,function(){
				
				$("#tellYourFriends").animate({'width' : '40px'}, 80);
			
			});
		});
	
		//delivered by edge slide out
		

			$("#deliveredByEdge").hover(function(){

				$(this).animate({'left' : '0'}, 110);

			},

			function() {



				$(this).delay(200,function(){

					$("#deliveredByEdge").animate({'left' : '-354px'}, 110);

				});
			});

	//CLEAR FORMS
	
	//clear our specific inputs with specific copy
	//so we don't clear inputs once the user has entered their own copy
	//$("#tqFriendsName, #tqFriendsEmail, #tmFriendsName, #tmFriendsEmail, #yourName, #yourEmail").click(function () {
	//	if ($(this).val() == 'your name') { $(this).val(''); }
	//	if ($(this).val() == 'your email') { $(this).val(''); }
	//	if ($(this).val() == 'name') { $(this).val(''); }
	//	if ($(this).val() == 'email') { $(this).val(''); }
	//});
	
	$("#tqYourMessage,#tmYourMessage").click(function () {
		if ($(this).text() == 'I saw this site and thought of you, take a peak') { $(this).text(''); }
	});
	
	$("#yourMessage").click(function () {
		if ($(this).text() == 'enter your message') { $(this).text(''); }
	});
	
	//set our lightbox defaults
	$.extend($.modal.defaults, {
		close:true,
		closeHTML: "<a class='modalCloseImg' href='#' title='close'>Close</a>",
		overlayClose: true,
		opacity: 91,
		//animations
		onOpen: function (dialog) {
			dialog.overlay.fadeIn('medium', function () {
				dialog.container.show(); 
				dialog.data.show();
				});
			}
	});


	//add watermark
	$('input').each(function() {
		$(this).watermark($(this).attr('watermark'));
	});
	$('#txtAskAQuestion').val('');
	//$('#txtAskAQuestion').watermark($('#txtAskAQuestion').attr('watermark'));
	$('textarea').each(function() {
		$(this).watermark($(this).attr('watermark'));
	});

	
});

        function AJAXError(XMLHttpRequest, textStatus, errorThrown){
            //alert(textStatus + ": " + errorThrown);
        }

