var $j = jQuery.noConflict();

$j.expr[':'].loaded = function(obj) {
	if($j(obj).attr("data-loaded") == "true")
		return true;
		
	return false;
}; // loaded

jQuery.fn.exists = function() {
	return $j(this).length > 0;
}

function swapImages(img_element) {
	var img = $j(img_element);
	var left = parseFloat(img.css('left'));
	var width = img.width();
	
	var new_position = 0;
	
	//if at the end...
	if((left - 115) <= (0 - width)) {
		new_position = 0;
	}
	else {
		//move back another 100 pixels...
		new_position = left - 115;
	}

	img.css({left: new_position+ "px"});    
} // swapImages

$j(document).ready(function() {
	initLazyLoading();
	initPlaceholder();
	
	var stickHeaderFooter = function() {
		fixStickLeft("div#header", 0);
		fixStickLeft("div#footer", 0);
	}
	
	stickHeaderFooter();
	$j(window).scroll(stickHeaderFooter);
	$j(window).resize(stickHeaderFooter);

	$j('#logo a').hover(function(){
		$j(this).bgFade('fadeIn',
		{
			fadeSpeed: 350
		}); // bgFade
	}, function() {
		$j(this).bgFade('fadeOut',
		{
			fadeSpeed: 350
		}); // bgFade
	}); // hover

	$j("#secondary-one ul.sub-menu, #secondary-two ul.sub-menu").each(function() {
		var ul = $j(this);
		ul.parent().hoverIntent({
			over: function() {
				ul.slideDown({duration: 'fast'});
			},
			out: function() {
				ul.slideUp({duration: 'fast'});
			},
			timeout: 5
		}); // hoverIntent
	}); // each

	$j("#secondary-one #menu-top-left-menu a").click(function() {
		return getProjects(getTag(this.href));
	}); // click
}); // ready

var getTag = function(url) {
	tag = "";

	if(url.search('#') != -1) {
		tag = url.split('#')[1];
	}

	return tag;
} // getTag

var initLazyLoading = function() {
	$j("img").load(function() {
		if($j(this).attr("src") == $j(this).attr("original"))
		{
			$j(this).attr("data-loaded", "true");
			$j(this).removeClass("loading");
		}
	});
	
	$j("img").not(":loaded").not(".no_lazy_load").lazyload({
		placeholder : "/wordpress/wp-content/themes/roanne/images/blank.gif",
		effect : "fadeIn",
		threshold: 800
	});  // lazyload
}; // initLazyLoading

var doStick = function(selects, absolute, topPadding, topPadding2, bottomPadding) {
	$j(selects).each(function(index) {
		var top = $j(this).parent().offset().top - $j(window).scrollTop();
		var height = $j(this).parent().height() - $j(this).height() - topPadding;
		if(top <= topPadding)
			if(top <= -height)
				$j(this).css(
					{
						position: (absolute) ? "absolute" : "relative",
						top: "auto",
						bottom: bottomPadding + "px"
					});     // css
			else
				$j(this).css(
					{
						position: "fixed",
						top: topPadding + "px",
						bottom: "auto"
					}); // css
			// if
		else
			$j(this).css(
				{
					position: (absolute) ? "absolute" : "relative",
					top: topPadding2 + "px",
					bottom: "auto"
				}); // css
			// if
	}); // each
};
	
var fixStickLeft = function(selectors, leftPadding) {
	var minWidth = parseFloat($j("#wrapper").css("min-width"));
	$j(selectors).each(function() {
		if($j(window).width() < minWidth)
		{	       
			if($j(this).css("position") == "fixed")
				$j(this).css("left", -($j(window).scrollLeft() - leftPadding));
			else
				$j(this).css("left", leftPadding);
		}
		else
			$j(this).css("left", leftPadding);
	});     // each
}; // fixStickLeft

var fixStickRight = function(selectors, rightPadding) {
	var minWidth = parseFloat($j("#wrapper").css("min-width"));
	
		$j(selectors).each(function() {
			if($j(window).width() < minWidth + rightPadding)
			{
				if($j(this).css("position") == "fixed")
					$j(this).css({left: minWidth - $j(window).scrollLeft() - $j(this).width() - 1, right: "auto"});
				else
					$j(this).css({left: "auto", right: rightPadding});
			}
			else
				$j(this).css({left: "auto", right: rightPadding});
		});      // each
}; // fixStickRight

var initInfiniteScroll = function(width) {
	$j('#communications, #collaborators, #category').infinitescroll({
		navSelector  : "div.navigation",
		nextSelector : "div.navigation a:first",    
		itemSelector : "div.post",
		loadingImg   : "/wordpress/wp-content/themes/roanne/images/loading.png",
		loadingText  : "",
		donetext     : "",
		bufferPx	 : 800 
	}, function() {
		if(width != undefined) {
			infiniteScrollExecuted(width);
		} else {
			infiniteScrollExecuted();
		}
	}); // infinitescroll
}; // initInfiniteScroll

var infiniteScrollExecuted = function(width) {
	initLazyLoading();
	postsMinHeight();
	calcImageHeight(null, width);
	calcVideoHeight(null, width);
	fixVideoZIndex();
}; // infiniteScrollExecuted

/* var appendBackToIndex = function() {
	$j("ul#menu-top-left-menu").append('<li><a href="#">Back to Index</a></li>').click(function() {
		$j.scrollTo({top: 0, left: 0}, 500);
	});
} */

var initProjectsPage = function() {
	initShare();

	var stick = function() {
	 //doStick("div.content", true, 131, 0, 0);
	 //fixStickRight("div.content", 25);
	};

	// $j(window).scroll(function() {
	// 	 stick();
	// }); // scroll
	
	$j(window).resize(function() {
		calcImageHeight(".project");
		calcVideoHeight(".project");
	}); //resize
	
	getProjects(getTag(window.location.href));

	calcImageHeight(".project");
	calcVideoHeight(".project");
	fixVideoZIndex();
}; // initProjectsPage


var initProject = function() {
	initShare();

	var stick = function() {
	 //doStick("div.content", true, 131, 0, 0);
	 fixStickRight("div.content", 25);
	 fixStickLeft("#project-right-sidebar", 25);
	};

	$j(window).scroll(function() {
		 stick();
	}); // scroll
	
	$j(window).resize(function() {
		stick();
		calcImageHeight(".project");
		calcVideoHeight(".project");
		stick();
	}); //resize
	
	calcImageHeight(".project");
	calcVideoHeight(".project");
	fixVideoZIndex();	
	stick();

	$j("#project-right-sidebar a.client-anchor").click(function() {
		// if is the current open client list, don't do anything
		if ($j(this).parent().hasClass('current-item')) {
			return false;
		}

		// if has no projects, go to link
		if (!$j(this).next("ul").exists()) {
			return true;
		}

		var that = this;
		$j("#project-right-sidebar li.current-item ul.project-list").slideUp(function() {
			$j(that).next("ul").slideDown();
			$j("#project-right-sidebar li.current-item").removeClass('current-item');
			$j("#project-right-sidebar .client-anchor.current-item").removeClass('current-item');
			$j(that).addClass('current-item');
			$j(that).parent().addClass('current-item');
		});
		
		return false;
	});
	
	$j("#wrapper").css("padding-top", 0);
}

var initShare = function() {
	$j(".share a").click(function() {
		openShareWindow($j(this).attr('href'));
		return false;
	});
}

var initCommunicationsPage = function() {
    initInfiniteScroll(620);
    initShare();

	// $j(".archives ul li:gt(6)").hide();

	// var all_archives = $j('<li></li>')
	// 				.append('+ All archives')
	// 				.addClass('pointer')
	// 				.click(function() {
	// 					$j(this).text('Coming soon.');
	// 				// $j(".archives ul li").show();
	// 				// $j(".archives ul li:last").hide();
	// 				});

	// $j(".archives ul").append(all_archives);

    $j(window).resize(function() {
		calcImageHeight(null, 620);
		calcVideoHeight(null, 620);
    }); //resize

   //  // postsMinHeight();
   calcImageHeight(null, 620);
	calcVideoHeight(null, 620);
    fixVideoZIndex();
}; // initCommunicationsPage

var postsMinHeight = function() {
    $j("#projectsWrap .content, #communications .content, #category .content").each(function() {
	    $j(this).parent().css("min-height", $j(this).height());
	    $j(this).next().css("min-height", $j(this).height());
    }); // each
}; // postsMinHeight

var initCollaborationPostPage = function() {
    var videoW, postH;

	var doResize = function() {
		videoW = $j(".video").width();
		postH = $j(".firstblock .text").height() + 1; // 1px border

		calcVideoHeight(null, videoW);
	    fixVideoZIndex();

		$j(".firstblock .left").height(postH);
	}; // doResize

	doResize();

    $j(window).resize(function() {
		doResize();
    }); //resize

	$j('.thumb .image').hover(function(){
		  $j(this).bgFade('fadeIn');
	}, function() {
		  $j(this).bgFade('fadeOut');
	});
}; // initCollaborationPostPage

var initCollaborationsPage = function() {
	initInfiniteScroll();
	$j("#collaborators .post a").hoverbox();

	$j('.thumb .image').hover(function(){
		  $j(this).bgFade('fadeIn');
	}, function() {
		  $j(this).bgFade('fadeOut');
	});
}; // initCollaborationPostPage

var initBlogArchive = function() {
	$j(".year .table").not(":first").hide();

	$j(".year h4").click(function() {
		$j(this).next('.table').slideToggle();
	});
}

var fixVideoZIndex = function() {
	$j(".video object").append('<param name="wmode" value="opaque" /><param name="type" value="application/x-shockwave-flash">');
	$j(".video embed").attr("wmode","opaque");
}; // fixVideoZIndex

var calcImageHeight = function(selector, width) {
	selector = selector || ".post";
	minWidth = 620; // parseFloat($j("#wrapper").css("min-width")) - parseFloat($j(".project").css("paddingLeft")) - parseFloat($j(".project").css("paddingRight"));

	if(width == undefined)
		width = $j("body").width() - parseFloat($j(selector).css("paddingLeft")) - parseFloat($j(selector).css("paddingRight"));

	width = (width >= minWidth) ? width : minWidth;

	$j(selector + " .images img").each(function() {
		imgWidth = $j(this).attr("data-width");
		imgHeight = $j(this).attr("data-height");

		height = imgHeight * width / imgWidth;
		height = Math.ceil(height);

		/*project = $j(this).parents(".project")[0];
		projectMarginTop = parseFloat($j(project).css("marginTop"));
		projectMarginBottom = parseFloat($j(project).css("marginBottom"));
		projectPaddingBottom = parseFloat($j(project).css("paddingBottom"));
		projectPaddingTop = parseFloat($j(project).css("paddingTop"));

		captionHeight = $j(this).parent().next("p").height();

		projectHeight = height
			+ projectMarginTop + projectMarginTop + projectMarginTop + projectMarginTop
			+ captionHeight;*/

		$j(this).css("height", height);
		// $j(this).parent().css("height", height);
		// $j(this).parent().css("width", width);
		
		//$j(project).css("height", projectHeight);
	}); // each
	
	/*
	$j(selector + ' ul.slideshow').each(function() {
		var slideshow = $j(this);
		var images = slideshow.find('li');
		var imageHeights = images.map(function(x, img){ return $j(img).find('img').attr('data-height'); });
		imageHeights = Array.prototype.slice.call(imageHeights);
		var maxHeight = Math.max.apply(Math, imageHeights);
		var itsWidth = $j('ul.slideshow').find('img[data-height='+ maxHeight +']').attr('data-width');

		maxHeight = maxHeight * width / itsWidth;
		maxHeight = Math.ceil(maxHeight);	
		$j(this).css("height", maxHeight);
	});
	*/
	
	
}; // calcImageHeight

var calcVideoHeight = function(selector, width) {
	$j(".video iframe, .video object, .video embed").each(function() {
		var vidWidth = $j(this).width();
		var vidHeight = $j(this).height();
		minWidth = 620; // parseFloat($j("#wrapper").css("min-width")) - parseFloat($j(".project").css("paddingLeft")) - parseFloat($j(".project").css("paddingRight"));

		selector = selector || ".post";

		if(typeof(width) == 'undefined')
			width = $j("body").width() - parseFloat($j(selector).css("paddingLeft")) - parseFloat($j(selector).css("paddingRight"));

		width = (width > minWidth) ? width : minWidth;
		var newHeight = vidHeight * width / vidWidth;

		$j(this).width(width);
		$j(this).height(newHeight); 

		$j(this).css("min-width", minWidth);
	}); // each
} // calcVideoHeight

var projectCategoriesSetActive = function(active) {
	var tags = new Array();
	var tag_exists = false;

	$j("#secondary-one #menu-top-left-menu a").each(function(i) {
		tags[i] = $j(this).attr("href").split('#')[1];
	});
	
	for(key in tags) {
		if(tags[key] == active) {
			tag_exists = true;

			var menuAnchors = $j('#secondary-one #menu-top-left-menu a');
			var thisAnchor = $j('#secondary-one #menu-top-left-menu a[href="/#' + active + '"]');
		
			menuAnchors.not(thisAnchor).removeClass("active");
			
			if(!thisAnchor.hasClass("active")) {
				thisAnchor.addClass("active");
				thisAnchor.attr("href", "/");
			} else {
				thisAnchor.removeClass("active");
			}
		} // if
	}
} // projectCategoriesSetActive

var firstTimeProjectView = true;
var getProjects = function(tag) {
	var tags = new Array();
	var tag_exists = false;

	var projectsList = $j("#projectsList");
	if(projectsList.is(":animated")) {
		return false;
	}

	$j("#secondary-one #menu-top-left-menu a").each(function(i) {
		tags[i] = $j(this).attr("href").split('#')[1];
	});
	
	for(key in tags) {
		if(tags[key] == tag) {
			tag_exists = true;

			var menuAnchors = $j('#secondary-one #menu-top-left-menu a');
			var thisAnchor = $j('#secondary-one #menu-top-left-menu a[href="/#' + tag + '"]');
		
			menuAnchors.not(thisAnchor).removeClass("active");
			
			if(!thisAnchor.hasClass("active")) {
				thisAnchor.addClass("active");
			} else {
				thisAnchor.removeClass("active");
				tag = "";
			}
		} // if
	}

	if(!tag_exists)
		tag = "";
			
	if(!firstTimeProjectView)
		projectsList.fadeOut();
	else
		firstTimeProjectView = false;

	$j.get('ajax/?p_type=project&p_tag=' + tag, function(data) {
		projectsList.html(data);
		projectsList.fadeIn(function() {
			projectsList.children("li").localScroll({
				queue:false,
				duration:500,
				// hash:true,
				margin:false,
				offset:{top:-124, left:0}
			}); // localScroll

			$j("#projectsListWrap a img").hoverbox();
			
			window.clearInterval();
			$j("#projectsList li a img").each(function(index, img) {
				var interval = (Math.floor(Math.random()*2000)) + 1000;
		
				window.setInterval(function(){
					swapImages(img);
				}, interval);
			}); // each
		}); // fadeIn
	}); // get
} // getProjects

var openShareWindow = function(url) {
	window.open(url, 'share', 'width=630,height=480,resizable=no,scrollbars=no');
} // openShareWindow

var initPlaceholder = function() {
	// placeholder
	// source: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
	$j('[placeholder]').focus(function() {
	  var input = $j(this);
	  if (input.val() == input.attr('placeholder')) {
	    input.val('');
	    input.removeClass('placeholder');
	  }
	}).blur(function() {
	  var input = $j(this);
	  if (input.val() == '' || input.val() == input.attr('placeholder')) {
	    input.addClass('placeholder');
	    input.val(input.attr('placeholder'));
	  }
	}).blur();

	$j('[placeholder]').parents('form').submit(function() {
	  $j(this).find('[placeholder]').each(function() {
	    var input = $j(this);
	    if (input.val() == input.attr('placeholder')) {
	      input.val('');
	    }
	  })
	});
}
