// JavaScript Document

// jQuery Preload Images
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

// Background Animation
/**
 * @author Alexander Farkas
 * v. 1.22
 */


(function($) {
	if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
		var oldCurCSS = $.curCSS;
		$.curCSS = function(elem, name, force){
			if(name === 'background-position'){
				name = 'backgroundPosition';
			}
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
	
	var oldAnim = $.fn.animate;
	$.fn.animate = function(prop){
		if('background-position' in prop){
			prop.backgroundPosition = prop['background-position'];
			delete prop['background-position'];
		}
		if('backgroundPosition' in prop){
			prop.backgroundPosition = '('+ prop.backgroundPosition;
		}
		return oldAnim.apply(this, arguments);
	};
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			var start = $.curCSS(fx.elem,'backgroundPosition');
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			fx.start = [start[0],start[2]];
			var end = toArray(fx.end);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		//return;
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);

//Twitter Feed Vars
var curTwitterObj = 1;
var numObj = 0;
var boxSize = 0;

//Progress Bar Vars
var totalProgressHeight = 0;
var curProgressPos = 0;
var sl_totalHeight = null;
var supportPerc = null;

var menuNum = 0;
var curMenu = 1;
var windowHeight = 0;
var bgImgRatio = 0;
var contactSent = false;
var isMobile = false;
var yt_video_loc = "http://www.youtube.com/e/FqUNd0nh6d0";
var ytplayerObj = null;
var supportTimeMod = 100;

jQuery(document).ready(function($) {
	
	isMobile = ($("body").attr('ismobile')  == "true" ? true:false);
	
	
	
	numObj = jQuery('.twitter_update').size();
	boxSize = jQuery('.twitter_update').width();
	setTimeout('rotateTwitterFeed()',10000);
	
	jQuery("#menu a.page_link").hover(
		function() {
			jQuery(this).stop().animate({top: '-27px'},700);
		},
		function() {
			jQuery(this).stop().animate({top: '-40px'},700);
		});
							  
	
	jQuery("#messageBox").toggle(
		function() {
			windowHeight = jQuery(window).height();
			jQuery("#content_wrapper").animate({'margin-top':(windowHeight-270)},800,'easeInOutCirc');
			jQuery(this).html("Hide Background");
		},
		function() {
			jQuery("#content_wrapper").animate({'margin-top':20},500,'easeInOutCirc');
			jQuery(this).html("Show Background");
		});
	jQuery("#mc_update_box").show().animate({'left':'70%'},6000,'easeInOutCirc');
	
	jQuery("#vid_thumbnail").click(function() {	
		
		if (isMobile == true) {
			_gaq.push(['_trackEvent', 'Videos', 'Play']);
			window.location = yt_video_loc;
			return;
			
		} else {
			_gaq.push(['_trackEvent', 'Videos', 'Play']);
			jQuery("#homepage_box").fadeOut(1000,function() { jQuery("#video_player_box").show(); });
			setTimeout("supportVideoMsg()",8000);
		}
		
	});
	
	if (jQuery(".sppt_progress_bar_back").length != 0) {
		// Confirmed support raising level object
		setTimeout('animateProgressBar()',3000);
	}
	
	jQuery(".spage_box").hover(function() {
			jQuery(this).children(".spage_hover").slideDown(300);
		},
		function() {
			jQuery(this).children(".spage_hover").slideUp(150);
		});
	
}); // END dom ready

function supportVideoMsg() {
	
	if (ytplayerObj == null) return;
	
	curTime = ytplayerObj.getCurrentTime();
	if (curTime > 350) {
		jQuery("#support_link_tab").show().animate({ top: -12},800, 'easeOutElastic');
		_gaq.push(['_trackEvent', 'Videos', 'SupportSection']);
		
	} else {
		setTimeout("supportVideoMsg()",4000);
	}
	
} // EOF

function onYouTubePlayerReady(playerId) {
	myytplayer.setPlaybackQuality('large');
	myytplayer.playVideo();
	myytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	
	ytplayerObj = myytplayer;
	
}


function onytplayerStateChange(newState) {
   if (newState == 0) {
	  	window.location = "http://www.soarchrist.com/support";   
   }
}



jQuery(window).load(function() {
	menuNum = jQuery("#menu a").size();
	loadMenu();
		
	if (!jQuery("#content_wrapper").size()) return;
	
	windowHeight = jQuery(window).height();
	jQuery("#content_wrapper").css('margin-top',windowHeight +200);
	jQuery("#content_wrapper").delay(1000).animate({'margin-top':20},2500,'easeOutExpo');

});

function loadMenu() {
	
	jQuery("#menu a:nth-child("+curMenu+")").show().animate({'top':'-40px'},500,'easeOutCirc');
	curMenu++;
	
	if (curMenu <= menuNum) setTimeout("loadMenu()",400);
	
} // EOF loadMenu

function rotateTwitterFeed() {
	
	if (!jQuery(".inside_twitter_feed_box").size()) return;
	
	if (curTwitterObj == numObj) {
		// Last box
		curTwitterObj = 1;
		jQuery('.inside_twitter_feed_box').animate({marginLeft: "0px"}, 1500,'easeInOutElastic');
	} else {
		curTwitterObj++;
		jQuery('.inside_twitter_feed_box').animate({marginLeft: "-="+boxSize}, 2000,'easeInOutElastic');
	}
		
	
	setTimeout('rotateTwitterFeed()',8500);
	
} // EOF rotateTwitterFeed

function animateProgressBar() {
	
	if (supportPerc == null) return;
	
	backPos = "0px "+(sl_totalHeight)+"px";
	
	jQuery(".sppt_progress_bar_back").css("background-position", backPos);
	
	supportTimeMod = 300 - (jQuery(".sppt_progress_bar_back").size() * 100);
	
	jQuery(".sppt_progress_bar_back").each(function() {
		
		sl_totalHeight = jQuery(this).children("div.sppt_progress_bar_front").height();
		
		movementAmt = sl_totalHeight - (Math.round(sl_totalHeight*(supportPerc*.01))) + Math.round(5*(supportPerc*.01) );
		jQuery(this).animate({backgroundPosition: '0px '+movementAmt+'px'},(supportPerc*supportTimeMod),'easeOutQuart'); 
		curProgressPos = 0;
		setProgressBarValue(supportPerc);
		
	});
	/*
	if (sl_totalHeight) {
		movementAmt = sl_totalHeight - (Math.round(sl_totalHeight*(supportPerc*.01))) + Math.round(5*(supportPerc*.01) );
		jQuery(".sppt_progress_bar_back").animate({backgroundPosition: '0px '+movementAmt+'px'},(supportPerc*100)); 
		curProgressPos = 0;
		setProgressBarValue(supportPerc);
	}
	*/	
	
} // EOF animateProgressBar

function setProgressBarValue(perc) {
	
	if (curProgressPos < perc) {
		curProgressPos++;
		jQuery(".support_amt_display").html(curProgressPos+"%");
		setTimeout('setProgressBarValue('+perc+')',80);
	}
	
} // EOF setProgressBarValue

function openContact() {
	
	if (contactSent) {
		alert("You already sent us a message.");
		return;
	}
	
	jQuery("#contactForm").css("background","url(/wp-content/themes/scottstheme/images/contact_form.jpg)");
	jQuery('#contactFormWrapper').slideDown(1000,function(){
		jQuery("#nameField").focus();
	});
}


function submitContact() {
	
	if (prompt("To prove that you're a human, please type the answer to this question: 15 plus 20 = ") != 35) {
		alert("Do you really not know the answer to fifteen plus twenty? Or are you a robot trying to send me spam?");
		return false;
	}
		
	if (jQuery("#nameField").val().length == 0) {
		jQuery("#nameField").focus();
		alert("Oops, you forgot to tell us your name.");
		return false;
	}
	
	email = jQuery("#emailField").val();
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (reg.test(email) == false) {
		jQuery("#emailField").focus();
		alert("Oops, you forgot to give us your valid email.");
		return false;
	}	
	
	if (jQuery("#contentField").val().length == 0) {
		jQuery("#contentField").focus();
		alert("Oops, you forgot to write us a message.");
		return false;
	}
	
	formInfo = jQuery("#contactForm form").serialize();
	jQuery.ajax({
		url: '/wp-content/themes/scottstheme/contact_submit.php',
		cache: false,
		data: formInfo,
		dataType: 'json',
		type: 'post',
		success: function(data) {
			if (data.sent) {
				jQuery('#contactForm').css('background','none').html("<h1 align='center'>Email sent successfully</h1>");
				jQuery('#contactFormWrapper').animate({height: 75},1000).delay(4200).slideUp(300);				
				contactSent = true;
			} else {
				alert("Sorry, but our system isn't working right now.");
			}
		}
		});				
	
	/*jQuery("#contactForm form").attr("action",'/wp-content/themes/scottstheme/contact_submit.php');
	jQuery("#contactForm form").submit();*/
	
} // EOF submitContact
