/*!
 * theRedspace UI 1.0
 *
 */
 
$(document).ready( function() {

	$('.collapsible').children("span").text("[+]");
	
	var $subClass;
//	$subClass = $('.sub-menu ul li a.active');
	//alert($subClass);
	//if($subClass == 'active'){
		if($('li.sub-menu a.active')){
		
		$('li.sub-menu a.active div.this_active').css({float:'right',padding:'0 10px 0 0', width:'170px'});
		$('li.sub-menu a.active').append('<div style="float:left; padding: 0 0px 3px 0; margin-bottom:5px"><img src="http://www.theredspace.com/wp-content/themes/theredspace/images/logo_small.png"></div>');
		}
	//}}
	
	
	/* portfolio tabs*/
		//When page loads...
	$(".tab_content").hide(); //Hide all content
	var value = window.location.hash;
	
	if(value == '#tech'){
		$("ul.tabs li:nth-child(2)").addClass("active").show(); //Activate second tab	
		$(".tab_content:nth-child(2)").show(); //Show second tab content
	}else{
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content
	}
	
	//On Click Event
	$("ul.tabs li").click(function() {

		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});
	
	
	
	
	var refreshIntervalId;
	var navPositions = new Array();
	var currentBar = null;
		
	/* Gallery */	
	function getClosestBar() {
		var closest = null;	
		var newdistance = null;					
		var distance = 10000;

		// Get closest bar:
		$( ".carousel-nav-button" ).each( function(index, value) {
			newdistance = Math.abs($(value).offset().left - $("#carousel-slide-bar").offset().left);
			if(newdistance < distance) {
				distance = newdistance;
				closest = $(value);
			}				
		});
		return closest;	
	}

	function getNextBar() {
		var first = null;
		var next = null;
		
		var distance = 10000;
		var farleft = 10000;
				
		var newdistance = null;

		
		// Get closest bar:
		$( ".carousel-nav-button" ).each( function(index, value) {
			newdistance = $(value).position().left - $("#carousel-slide-bar").position().left;			
			
			// Get the far left.
			if(first == null || farleft > $(value).position().left) {
				farleft = newdistance;
				first = $(value);
			}		

			if(newdistance > 0 && newdistance < distance) {
				distance = newdistance;
				next = $(value);		
			}
			
		});	


		if(next == null) return first;

		return next;	
	}
	
	function getPanelForBar(bar) {
		var id = $(bar).attr("id");
		panel_id = "#" + id.replace("carousel-nav", "carousel-panel");

		return $(panel_id);
	}
	
	function updateCarosel(toUpdate) {		
		var newPanelLeft = ($(getPanelForBar(toUpdate)).position().left * -1) + 10;
		
		if(!animating) {
			animating = true;
			$("#carousel").animate(
				{ 
					left: newPanelLeft 
				},
				{
					duration: 1000,
					complete: function() {
						animating = false;
					}
				}
			);
		}		
	}
	
	function pulsate(el, times, callback) {
		$(el).animate({"background-color": "#EE0000"}, 300, function() {
			$(this).animate({"background-color": "#92080C"}, 800, function() {
				if (!(--times)) {
				  callback();
				} else {
				  pulsate(this, times, callback);
				}
			});
		});
	}
	
	function animateBarAndUpdateCarosel(toUpdate, timer) {
		var newBarLeft = $(toUpdate).position().left;		
		var moved = false;
		currentBar = toUpdate;	

		$("#carousel-slide-bar").animate(
		  {
			left: newBarLeft
		  }, 
		  {
			duration: 1000,
			step: function(now, fx) {	
				if(!moved) {
					updateCarosel(toUpdate);
					moved = true;
				}
				clearInterval(refreshIntervalId);
				refreshIntervalId = window.setInterval(tick,timer);
			}
		  }
		);
	}

	function stopAnimation() {
		$("#carousel").stop();
		$("#carousel-slide-bar").stop();		
		$(".carousel-nav-button").stop();
		$(".carousel-nav-button").css("background-color", "#92080c");
		animating = false;
	}

	$( "#carousel-slide-bar" ).draggable({ 
		axis: "x", 
		containment: "parent",
		start: function() {
			stopAnimation();
			clearInterval(refreshIntervalId);			
		},
		drag: function() {

			var position = $("#carousel-slide-bar").offset().left - sliderLeft;
			var perc = position / $("#carousel-controller").width();
			
			var panelLeft = startingOffset + ((perc * ($("#carousel").width() + (3 * panels))) * -1);			
			$("#carousel").offset({ left: panelLeft });
		},
		stop: function() {			
			var closest = getClosestBar();
			animateBarAndUpdateCarosel(closest, 30000);
		}
		
	}).touch({
		animate: false,
		sticky: false,
		dragx: true,
		dragy: false,
		rotate: false,
		resort: true,
		scale: false
	});
	
	$( ".carousel-nav-button a" ).click( function () {
		var navli = $(this).parent();		
		stopAnimation();
		
		pulsate(navli,1, $.noop);		
		
		animateBarAndUpdateCarosel(navli, 30000);
		return false;
	});

	function tick() {
		var next = getNextBar();
		pulsate(next, 3,
		  function() {		
			animateBarAndUpdateCarosel(next, 10000);
		  }
		);		
	}
	
	function setupNavArray() {
		$(".carousel-nav-button").each( function() {
			navPositions["#" + $(this).attr("id")] = $(this).position().left;
		});
	}
	
	if($("#carousel").length) {
		setupNavArray();
		
		var width = 736;
        var count = $(".carousel-nav-button").length;
		var carousel_nav_width;
		if(count > 0) {
			// the width of the panel divided into the number of divs, minus 2 for padding on each.
	    	carousel_nav_width = Math.floor(width / count) - 2; 
		}

		$("#carousel").width(748 * count);
		$("li.carousel-nav-button, #carousel-slide-bar, li.carousel-nav-button a").width(carousel_nav_width);
		$("#carousel-controller ul").width((carousel_nav_width + 2) * count);
	
		$("#carousel-slide-bar").css("display", "block");
		$("#carousel-slide-bar").css("left", ($("#carousel-nav-1").position().left));
		currentBar = $("#carousel-nav-1");
		var panels = $(".carousel-panel").length;
		var sliderLeft = $("#carousel-slide-bar").offset().left;
		var startingOffset = $("#carousel").offset().left;
		var animating = false;
		
		var selectedNav = $("#carousel-nav-1");	
		refreshIntervalId = window.setInterval(tick,10000);			
	}

	/********************************************************
	 *
	 * Background cloud animation
	 * 	 
	 ********************************************************/
	var cloudVelocity = -2;	 
	var leftV = 1;	
	
	var l1 = parseFloat($('body,html').scrollTop());
	var t1 = new Date().getTime();
	
	function cloudTick() {
		
		l2 = parseFloat($('body,html').scrollTop());
		t2 = new Date().getTime();
		
		v = (l2 - l1)/(t2 - t1);
		if(v != 0) {
			cloudVelocity += v;
		}
		if(cloudVelocity > -2) {
			cloudVelocity -= 0.1;
		} else if(cloudVelocity < -2) {
			cloudVelocity += 0.1;			
		}
		l1 = l2;
		t1 = t2;
		
		var position = $("#clouds").css("backgroundPosition");
		var posA;
		var leftPos;
		var topPos;		
		
		if(position != null && position != 'undefined') {
			posA = position.split(" ");
			leftPos = parseFloat(posA[0].replace("px", ""));
			topPos = parseFloat(posA[1].replace("px", ""));
			$("#clouds").css({backgroundPosition: (leftPos + leftV) + "px " + (topPos + cloudVelocity) + "px"});					
		} else {
	        leftPos = parseFloat($("#clouds").css("background-position-x").replace("px", "")); // *sighe*
	        topPos = parseFloat($("#clouds").css("background-position-y").replace("px", "")); // *sighe*
			$("#clouds").css("background-position-x", (leftPos + leftV) + "px ");
			$("#clouds").css("background-position-y", (topPos + cloudVelocity) + "px");			
		}
		
	}
	
	if( !navigator.userAgent.match(/Android/i) &&
		 !navigator.userAgent.match(/webOS/i) &&
		 !navigator.userAgent.match(/iPhone/i) &&
		 !navigator.userAgent.match(/iPod/i)){
		$("#clouds").css({backgroundPosition: "0px 0px"});
		var refreshInterval2Id = window.setInterval(cloudTick, 100);
	}

	function repositionCarouselScrollBar() {
		if(currentBar != null && $("#carousel-slide-bar").length != 0) {
			var newBarLeft = $(currentBar).position().left;			
			$("#carousel-slide-bar").css( "left", newBarLeft);
		}
	}
	repositionCarouselScrollBar();

	function resizeBumpers() {
		//	var centerWidth = $('header .nav').width();
		/* Hack for IE - would like to use nav width in case we change it, but just won't work in IE7 injected headers */
		var centerWidth = 750;
		var pageWidth = $('header').width();
		var bumperWidth = Math.floor((pageWidth - centerWidth)/2);
		if(bumperWidth > 0) {
			$(".bumper").width(bumperWidth);
			$(".bumper").offset({ top: 0 });	/* Hack for IE7, the offset breaks for no reason */
		}	
		$("header .nav ul li a").not(".submenu li a").last().css("padding-right", "12px");	
		
		// If this adds in a scroll bar on the side, we need to compensate in the carousel.
		repositionCarouselScrollBar();
	}
	
	function maybe_fix_ie_styles() {
		if(typeof fix_ie_styles == 'function') {
			fix_ie_styles();
		}
	}

	function inject_headers_footers() {
		if($("#primary-nav").length == 0) {
			$.get(baseDir + "/inject-header.php?post_id=" + currentPost, function(data) {
				$('header').html(data);
				maybe_fix_ie_styles();
				resizeBumpers();	
				$("#project-navigation li a").each( function() {
					if(!$(this).parent().hasClass('sub-menu')) {					
						var contents = $(this).html();
						var divided = contents.split(" ");
						for(var i = 0; i < divided.length; i++) {
							if(i % 2 == 1) {
								divided[i] = "<span class=\"colorize\">" + divided[i] + "</span>";
							}
						}
						contents = divided.join(" ");
						$(this).html(contents);
					}
				});
			});
		} else {
			maybe_fix_ie_styles();			
			resizeBumpers();						
		}
		
		if($("#secondary-nav").length == 0) {
			$.get(baseDir + "/inject-footer.php?post_id=" + currentPost, function(data) {
				$('footer').html(data);
				
				$("#menu-secondary-navigation li a").not(".sub-menu li a").each( function() {
					var contents = $(this).html();
					contents = contents.replace("r", "<span class=\"red\">r</span>");
					$(this).html(contents);
				});	
				maybe_fix_ie_styles();		
				resizeBumpers();							
			});	
		} else {
			$("#menu-secondary-navigation li a").not(".sub-menu li a").each( function() {
				var contents = $(this).html();
				contents = contents.replace("r", "<span class=\"red\">r</span>");
				$(this).html(contents);
			});	
			maybe_fix_ie_styles();			
			resizeBumpers();									
		}		
	}
	inject_headers_footers();
	
	
	$(window).bind("resize", function() {
		resizeBumpers();
	});
	
	var slideShowTimer = null;
	/* Adapted from slideViewer 1.2 code - only clicks the next button */
	function slideViewerTick() {
		if(jQuery(".stripViewer").length != 0) {
			var pictWidth = jQuery(".stripViewer").find("img").width();
			var pictHeight = jQuery(".stripViewer").find("img").height();
			var pictEls = jQuery(".stripViewer").find("li").size();
			var stripViewerWidth = pictWidth*pictEls;
			
			var ui = jQuery(".stripViewer").next().find("a.current");
					
			var bTotal = parseFloat(jQuery(".stripViewer").css('borderLeftWidth').replace("px", "")) +  parseFloat(jQuery(".stripViewer").css('borderRightWidth').replace("px", ""));
			var dOs = jQuery(".stripViewer").offset();
	 
			var uinext = ui.parent().next().find("a");
			(jQuery(uinext).length != 0)? uinext.trigger("click") : ui.parent().parent().find("a:first").trigger("click");
			if(slideShowTimer != null) {
				clearInterval(slideShowTimer);
			}
			slideShowTimer = window.setInterval(slideViewerTick, 4000);
		}
	}
	
	$(window).bind("load", function() {		
		
		$("#slide-wrapper.svw").slideView({
			easeFunc: "easeInOutBack",
			easeTime: 1200
			});
		$("#slide-wrapper.svw").slideDown();
		
		$(".stripTransmitter a").click( function() {
			if(slideShowTimer != null) {
				clearInterval(slideShowTimer);
			}
			slideShowTimer = window.setInterval(slideViewerTick, 8000);			
		});			
		slideShowTimer = window.setInterval(slideViewerTick, 4000);	
	});

	$("#project-navigation ul li").click( function() {
		if(!$(this).parent().hasClass('sub-menu')) {
			var sub_menu_class = $(this).attr('id');
			
			// Dirty IE workaround. This shouldn't be getting called, but it is in IE; just catch the exception and move on.
			try {
				$("." + sub_menu_class).slideToggle();
				return false;
			} catch(e) {
				
			}
		}
	});
	
	if(navigator.userAgent.indexOf("MSIE") == -1) {
		$("input[type=file]").filestyle({
			image: baseDir + "/images/file-input.png",
			imagewidth: 	82,
			imageheight: 	23,
			width: 			150
		});
	}
	
	$(".wpcf7-file").css({
		"background-color": "#D60D14",
		"color": "#FFFFFF",
		"padding": "2px",
		"border": "none"
	});

	$(".wpcf7-file").next("div").css({
		'position': "absolute",
		'left': "155px"
	});
	
	$(".collapsible").click( function() {
		$(this).next("div .collapsibleChild").slideToggle("fast",resizeBumpers);
	})
	.toggle( function() {
    $(this).children("span").text("[-]");
}, function() {
    $(this).children("span").text("[+]");


	});

});
