(function($){
	
	//clearing default input values on focus
	
	$.fn.clearInputs = function(){
		
		return this.each(function(){
			
			var val = $(this).val();
			
			$(this).focus(function(){
				if($(this).val() == val) $(this).val("");
			})
			.focusout(function(){
				if($(this).val() == "") $(this).val(val);
			});
			$("#searchform").submit(function(){
				if($(".text-search").val() == val || $(".text-search").val() == ""){
					return false;
				}
			});
			
		});
		
	};
	
	//latest tweets
	
	$.fn.latestTweets = function(o){
		var def ={
			uname: 'CrossFit516',
			count: 3
		}
		
		if(o) $.extend(def,o);
		
		$.fn.extend({
			linkUrl: function(){
				
				var returning = [];
				var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))/gi;
				
				this.each(function(){
				returning.push(this.replace(regexp,
					function(match){
						
						var url = (/^[a-z]+:/i).test(match) ? match : "http://"+match;
						return "<a href=\""+url+"\">"+match+"</a>";
						
					}));
				});
				return $(returning);
			},
			linkUser: function(){
				
				var returning = [];
				var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
				
				this.each(function(){
					
					returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>"));});
					
				return $(returning);
			},
			linkHash: function(){
				
				var returning = [];
				var regexp = /(?:^| )[\#]+([A-Za-z0-9-_]+)/gi;
				
				this.each(function(){
					
					returning.push(this.replace(regexp, " <a href='http://twitter.com/search?q=&tag=$1&lang=all&from=" + def.uname + "'>#$1</a>"));
					
				});
				return $(returning);
			}
		})
		
		function buildUrl(){
			
			var protocol = ("https:" == document.location.protocol ? "https:" : "http:");
			
			return protocol+"//api.twitter.com/1/statuses/user_timeline.json?screen_name=" + 
					def.uname+"&count=" + def.count + "&include_rts=1&callback=?";
		}
		function adjustTime(ceratedAt){
			var date = new Date(ceratedAt.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
			var day = date.getDate();
			var sup ="";
			(day == 1 || day == 21 || day==31) ? sup = "st" :
			(day == 2 || day == 22) ? sup = "nd" :
			(day == 3 || day == 23) ? sup = "rd" : sup = "th";
			
			var hours = date.getHours();
			var minutes = date.getMinutes();
			var ampm = hours < 12 ? " AM" : " PM";
			if (hours > 12) hours -= 12;
			if (hours == 0) hours = 12;
			if (hours < 10) hours = "0" + hours.toString();
			if (minutes < 10) minutes = "0" + minutes.toString();

			time = hours + ":" + minutes + " " + ampm + " " + date.toString().substr(4,3) + " " + day + sup;
			return time;
		}
		return this.each(function(i, widget){
			
			var tList = $("<ul class='tweets' />").appendTo(widget);
			
			$(widget).bind("load", function(){
				
				$.getJSON(buildUrl(), function(data){
					
					var tweets = (data.results || data);
					
					$.each(tweets, function(i,item){
						tweetText = "<p>" + $([item.text]).linkUrl().linkUser().linkHash()[0] + "</p>";
						addInfo = "<span>" + adjustTime(item.created_at) + " via " + item.source + "</span>";
						tList.append("<li>" + tweetText + addInfo + "</li>");
					});
					
				});
			}).trigger("load");;
		});
	}
	
})(jQuery);

// popup

function showPopup(popupObj,show){
	if(show){
		popup = popupObj;
		$(document).scrollTop(0);
		if(!$(".overlay").length){
			overlay = $("<div class='overlay' />")
			.appendTo(document.body).height($(document).height())
			.css({
				background: "#555",
				opacity: 0
			})
		}
		popup.fadeIn(400);
		overlay.fadeTo(400, 0.4);
	}
	else{
		popup.fadeOut(400);
		overlay.remove();
		popup.find("input[type=text]").val();
		if($(".popup .wpcf7-response-output").length){
			$(".popup .wpcf7-response-output, .popup .ajax-loader").hide();
		}
		if($(".popup .wpcf7-not-valid-tip").length){
			$(".popup .wpcf7-not-valid-tip, .popup .ajax-loader").hide();
		}
	}
}

	
//slider on the home page

function crossFitSlider(){
	
	slider = $("#gallery");
	elWidth = slider.width();
	sliderSize = $("ul > li",slider).length;
	slideList = slider.find("ul");
	transitionSpeed = 500;
	duration = 10000;
	curr = 1;
	
	clearInt = setInterval(function(){anim('next');}, duration);
	
	$('li:last', slideList).prependTo($('ul', slider));
	$('ul', slider).css({'left': -elWidth});

	$("#gallery-next").click(function(){
		anim('next');
		return false;
	});
	
	$("#gallery-prev").click(function(){
		anim('prev');
		return false;
	});
	$(".paging").text(curr + "/" + sliderSize);
}

function anim(direction){
	
	clearInterval(clearInt);
	
	if(direction == "next"){
		
		clearTimeout(clearInt);
		
		// Copy leftmost (first) li and insert it after the last li
		$('li:first', slider).clone().insertAfter($('li:last', slider));
		// Update width and left position of ul and animate ul to the left
		$('ul', slider).animate(
			{left: -elWidth * 2 },
			transitionSpeed,
			function(){
				$('li:first', slider).remove();
				$('ul', slider).css({'left': -elWidth});
				if(curr < sliderSize){
					curr ++;
				}
				else{
					curr = 1;
				}
				$(".paging").text(curr + "/" + sliderSize);
			}
		);
	}
	
	if(direction == "prev"){

		// Copy rightmost (last) li and insert it after the first li
		$('li:last', slider).clone().insertBefore($('li:first', slider));
		// Update width and left position of ul and animate ul to the right
		$('ul', slider)
			.css({'left': -elWidth * 2})
			.animate(
				{left:-elWidth},
				transitionSpeed,function(){
					$('li:last', slider).remove();
					if(curr > 1){
						curr --;
					}
					else{
						curr = sliderSize;
					}
					$(".paging").text(curr + "/" + sliderSize);
				}
		);
	}
	
	clearInt = setInterval(function(){anim('next');}, duration);
}

jQuery.ajax = (function(_ajax){
	
	var protocol = location.protocol,
		hostname = location.hostname,
		exRegex = RegExp(protocol + '//' + hostname),
		YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
		query = 'select * from html where url="{URL}" and xpath="//div[@id=\'content\']/div[2]/div[1]/div[1]"';
	
	function isExternal(url) {
		return !exRegex.test(url) && /:\/\//.test(url);
	}
	
	return function(o) {
		
		var url = o.url;
		
		if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
			
			// Manipulate options so that JSONP-x request is made to YQL
			
			o.url = YQL;
			o.dataType = 'json';
			
			o.data = {
				q: query.replace(
					'{URL}',
					url + (o.data ?
						(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
					: '')
				),
				format: 'xml'
			};
			
			// Since it's a JSONP request
			// complete === success
			if (!o.success && o.complete) {
				o.success = o.complete;
				delete o.complete;
			}
			
			o.success = (function(_success){
				return function(data) {
					
					if (_success) {
						// Fake XHR callback.
						_success.call(this, {
							responseText: data.results[0]
								// YQL screws with <script>s
								// Get rid of them
								.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
						}, 'success');
					}
					
				};
			})(o.success);
			
		}
		
		return _ajax.apply(this, arguments);
		
	};
	
})(jQuery.ajax);

(function($) {
	$.fn.textShadow = function(option) {
		if (!$.browser.msie) return;
		var IE6 = $.browser.version < 7;
		return this.each(function() {
			var el = $(this);
			var shadow = el.textShadowParse(this.currentStyle["text-shadow"]);
			shadow = $.extend(shadow, option);

			el.textShadowRemove();

			if (shadow.x == 0 && shadow.y == 0 && shadow.radius == 0) return;

			if (el.css("position")=="static") {
				el.css({position:"relative"});
			}
			el.css({zIndex:"0"});
			if (IE6) {
				el.css({zoom:"1"});
			}
			
			var span=document.createElement("span");
			$(span).addClass("jQueryTextShadow");
			$(span).html(el.html());
			$(span).css({
				padding:		this.currentStyle["padding"],	
				width:		el.width(),
				position:	"absolute",
				zIndex:		"-1",
				color:		shadow.color!=null?shadow.color:el.css("color"),
				left:			(-parseInt(shadow.radius)+parseInt(shadow.x))+"px",
				top:			(-parseInt(shadow.radius)+parseInt(shadow.y))+"px"
			});
			
			if (shadow.radius != 0) {
				if (shadow.opacity != null) {
					$(span).css("filter", "progid:DXImageTransform.Microsoft.Blur(pixelradius="+parseInt(shadow.radius)+", enabled='true', makeShadow='true', ShadowOpacity="+shadow.opacity+")");
				} else {
					$(span).css("filter", "progid:DXImageTransform.Microsoft.Blur(pixelradius="+parseInt(shadow.radius)+", enabled='true')");
				}
			}
			el.append(span);
		
	  });
	};
	
	$.fn.textShadowParse = function(value) 
	{
		value = String(value)
			.replace(/^\s+|\s+$/gi, '')
			.replace(/\s*!\s*important/i, '')
			.replace(/\(\s*([^,\)]+)\s*,\s*([^,\)]+)\s*,\s*([^,\)]+)\s*,\s*([^\)]+)\s*\)/g, '($1/$2/$3/$4)')
			.replace(/\(\s*([^,\)]+)\s*,\s*([^,\)]+)\s*,\s*([^\)]+)\s*\)/g, '($1/$2/$3)')
	
		var shadow = {
			x      : 0,
			y      : 0,
			radius : 0,
			color  : null
		};

		if (value.length > 1 || value[0].toLowerCase() != 'none') {
			value = value.replace(/\//g, ',');
			var color;
			if ( value.match(/(\#[0-9a-f]{6}|\#[0-9a-f]{3}|(rgb|hsb)a?\([^\)]*\)|\b[a-z]+\b)/i) && (color = RegExp.$1) ) {
				shadow.color = color.replace(/^\s+/, '');
				value = value.replace(shadow.color, '');
			}

			value = value
				.replace(/^\s+|\s+$/g, '')
				.split(/\s+/)
				.map(function(item) {
						return (item || '').replace(/^0[a-z]*$/, '') ? item : 0 ;
					});

			switch (value.length)
			{
				case 1:
					shadow.x = shadow.y = value[0];
					break;
				case 2:
					shadow.x = value[0];
					shadow.y = value[1];
					break;
				case 3:
					shadow.x = value[0];
					shadow.y = value[1];
					shadow.radius = value[2];
					break;
			}
			if ((!shadow.x && !shadow.y && !shadow.radius) || shadow.color == 'transparent') {
				shadow.x = shadow.y = shadow.radius = 0;
				shadow.color = null;
			}
		}

		return shadow;
	};

	$.fn.textShadowRemove = function() {
		if (!$.browser.msie) return;
		return this.each(function() {
			$(this).children("span.jQueryTextShadow").remove();
		});
	};
})(jQuery);

if(typeof Array.prototype.map == 'undefined') {
	Array.prototype.map = function(fnc) {
		var a = new Array(this.length);
		for (var i = 0; i < this.length; i++) {
			a[i] = fnc(this[i]);
		}
		return a;
	}
}

function getMealOfTheDay(){
	if($(".widget_mealoftheday").length){
		var mealContainer = $(".widget_mealoftheday");
		
		$.ajax({
			url: 'http://www.thefoodee.com/blog/category/uncategorized/meal-of-the-day',
			type: 'GET',
			success: function(res) {
				mealContainer.append("<img src=\"" + $(res.responseText).find("img:eq(0)").attr("src") + "\" alt='' />"+
				"<span class=\"mealtitle\">" + $(res.responseText).find(".recipe a").text() + "</span>").wrapInner("<a target='_blank' href='" +  $(res.responseText).find(".recipe a").attr("href") + "' />");
				$(".widget_mealoftheday span, .widget_mealoftheday strong").textShadow();
			}
		});
	}
}

$(function(){
	
	getMealOfTheDay();
	
	$("input[type=text]").clearInputs();
	
	crossFitSlider();
	
	$(".freetrial-popup").click(function(){
		showPopup($("#freetrialpopup"),true);
		return false;
	});
	
	$(".close-popup").click(function(){
		showPopup($(".popup"),false);
		return false;
	});
	
	$("#twitter").latestTweets();
	
	if(typeof google != "undefined"){
		initialize();
	}
	
})
