$(document).ready(function() {
	(function($) {
    	$.fn.filestyle = function(options) {
			/* TODO: This should not override CSS. */
			var settings = {
				width : 250,
				bind : true
			};
			if(options) {
				$.extend(settings, options);
			};
			return this.each(function() {
				var self = this;
				var relativeWrapper = $("<div>")
								.css({
									"position": "relative",
									"overflow": "hidden"
								});
				var wrapper = $('<div class="fileUploadReplacement">')
								.css({
									"width": settings.imagewidth + "px",
									"height": settings.imageheight + "px",
									"background": "url(" + settings.image + ") 0 0 no-repeat",
									"background-position": "right",
									"display": "inline",
									"position": "absolute",
									"overflow": "hidden"
								});
				var filename = $('<input class="file">')
								 .addClass($(self).attr("class"))
								 .css({
									 "display": "inline",
									 "width": settings.width + "px"
								 });
				$(self).before(filename);
				$(self).wrap(wrapper);
				$(self).wrap(relativeWrapper);
				$(self).css({
							"position": "relative",
							"height": settings.imageheight + "px",
							"width": settings.width + "px",
							"display": "inline",
							"cursor": "pointer",
							"opacity": "0.0"
						});
				if ($.browser.mozilla) {
					if (/Win/.test(navigator.platform)) {
						$(self).css("margin-left", "-142px");                    
					} else {
						$(self).css("margin-left", "-168px");                    
					};
				} else {
					$(self).css("margin-left", settings.imagewidth - settings.width + "px");  
				};
				if (settings.bind) {
				    $(self).bind("change", function() {
						filename.val($(self).val());
					});
				}
			});
		};
	})(jQuery);

	(function($){
		$.fn.fieldtag = function(options){
			var opt = $.extend({
					markedClass: "tagged",
					standardText: false
				}, options);
			$(this)
				.focus(function(){
					if(!this.changed){
						this.clear();
					}
				})
				.blur(function(){
					if(!this.changed){
						this.addTag();
					}
				})
				.keyup(function(){
					this.changed = ($(this).val() && $(this).val() !== $(this).attr('title') ? true : false);
				})
				.each(function(){
					this.title = $(this).attr("title"); // IE6 Bug
					if($(this).val() == $(this).attr("title")){
						this.changed = false;
					}
					this.clear = function(){
						if(!this.changed){
							$(this)
								.val("")
								.removeClass(opt.markedClass);						
						}
					}
					this.addTag = function(){
						$(this)
							.val(opt.standardText === false? this.title : opt.standardText )
							.addClass(opt.markedClass);
					}
					if(this.form){
						this.form.tagFieldsToClear = this.form.tagFieldsToClear || [];
						this.form.tagFieldsToClear.push(this);
					
						if(this.form.tagFieldsAreCleared){ return true; }
						this.form.tagFieldsAreCleared = true;
							
						$(this.form).submit(function(){
							$(this.tagFieldsToClear).each(function(){
								this.clear();
							});
						});	
					}
				})
				.keyup()
				.blur();
			return $(this);
		}
	})(jQuery);
	
	(function($) {
		$.fn.lavaLamp = function(o) {
			o = $.extend({ fx: "linear", speed: 550, click: function(){} }, o || {});
		
			return this.each(function() {
				var me = $(this), noop = function(){},
					$back = $('<li class="back"><div class="left"></div></li>').appendTo(me),
					$li = $("li", this), curr = $("li.navHere", this)[0] || $($li[1]).addClass("navHere")[0];
		
				$li.not(".back").hover(function() {
					move(this);
				}, noop);
		
				$(this).hover(noop, function() {
					move(curr);
				});
		
				setCurr(curr);
		
				function setCurr(el) {
					$back.css({ "left": el.offsetLeft+"px", "width": el.offsetWidth+"px" });
					curr = el;
				};
		
				function move(el) {
					$back.each(function() {
						$(this).dequeue(); }
					).animate({
						width: el.offsetWidth,
						left: el.offsetLeft
					}, o.speed, o.fx);
				};
		
			});
		};
	})(jQuery);

	function crossfade(itemName) {
		$(itemName)
			.wrapInner("<div class=\"hoverarea\"></div>")
			.prepend("<div class=\"hoverimage\"></div>");
		$(itemName + " .hoverimage").css({ opacity: 0 })
		$(itemName + " .hoverarea")
			.mouseover(function(){
				$(this).parent().find("div.hoverimage").stop().animate({ opacity: 1 }, 550);
			})
			.mouseout(function(){
				$(this).parent().find("div.hoverimage").stop().animate({ opacity: 0 }, 350) ;
			})
	}

	function bubbleUp(itemName, topPos, topPosAni) {
		
		var hoverIntent = null;
		$(itemName)
			.wrapInner("<div class=\"hoverText\"></div>")
			.append("<div class=\"hoverImage\"></div>")
			.append("<div class=\"hoverArea\"></div>");
		
		$(itemName + " .hoverImage")
			.css({top: "64px" });
		$(itemName + " .hoverArea")
			.mouseenter(function(e){
				clearTimeout(hoverIntent);
				var el = this;
                	hoverIntent = setTimeout(function () {
						$(el).parent().find("div.hoverImage")
						.hoverFlow(e.type, { top: topPos }, 700);
					}, 100);
			})
			.mouseleave(function(e){
				$(this).parent().find("div.hoverImage").hoverFlow(e.type, { top: topPosAni }, 400);
				clearTimeout(hoverIntent);
			})
	}

	bubbleUp("#nav ul li a", "-20px", "64px");
	
	if ($.browser.msie && parseInt(jQuery.browser.version) == 8) {
		$(".kwickInformation div").css("display", "block");
	} else {
		$(".kwickInformation div").css("opacity", "0.85");	
	}
	
	$(".kwickInformation div p, .kwickInformation div a").css("opacity", "1");
	
	$('ul li:last-child').addClass( 'lastChild' );
	$('ul li:first-child').addClass( 'firstChild' );
	
	if ($("#panelArtefactAssetsControls ul li").length == 6) {
		$("#panelArtefactAssetsControls ul li:last-child a").css({"border" : "none"});
	}

	$('#panelResponses ul li, #artefactResponses ul li').biggerlink({
		biggerclass: 'overRide',
		clickableclass:'clickable',
		hoverclass:'hover'
	});

	$("#homePanel ul.kwicks").kwicks({
        max:77,
        spacing : 6,
		duration : 300,
		sticky : false,
        isVertical : true
    }); 
	$("#landingPanel ul.kwicks").kwicks({
        max:84,
        spacing : 6,
		duration : 300,
		sticky : false,
        isVertical : true,
		rows : 5,
		sticky : false
    }); 
	$("#panelArtefactOverview .viewMore a").each(function() {

		totalHeight = 0;
		firstHeight = 0;
		count = 0;
		
		thisListContainer = $(this).parent().prev(".expandable");
		
		$(thisListContainer).find("dd").each(function(i) {
			count++;
			totalHeight += ($(this).height() + parseInt($(this).css("paddingTop").replace(/px/, '')) + parseInt($(this).css("marginBottom").replace(/px/, '')));
			if (count < 3) {
				firstHeight += ($(this).height() + parseInt($(this).css("paddingTop").replace(/px/, '')) + parseInt($(this).css("marginBottom").replace(/px/, '')));
			}
		});
		if (count > 2) {
			$(this).parent().css("display", "block");
		}
		
		totalHeight += parseInt($(thisListContainer).find("dl").css("paddingTop").replace(/px/, '')) + parseInt($(thisListContainer).find("dl").css("paddingBottom").replace(/px/, ''))
		firstHeight += parseInt($(thisListContainer).find("dl").css("paddingTop").replace(/px/, '')) + parseInt($(thisListContainer).find("dl").css("paddingBottom").replace(/px/, ''))

		$(this).data("fullHeight", totalHeight);
		$(this).data("firstHeight", firstHeight);
		$(this).data("container", thisListContainer);
		
		thisListContainer.css("height", firstHeight);
		
	});
	$("#artefactRateToolTip").css({ opacity: 0, marginTop: 0 });
	$("#artefactRate a").mouseover(function(e){
			$(this).next().hoverFlow(e.type, { opacity: 1, marginTop: '6px' }, 300);
	}).mouseout(function(e){
			$(this).next().hoverFlow(e.type, { opacity: 0,  marginTop: 0 }, 150);
	})
	
	$("#panelArtefactOverview .viewMore a").toggle(function() {
			$(this).data("container").animate({
				height: $(this).data("fullHeight")
			}, 500, "easein");
		}, function() {
			$(this).data("container").animate({
				height: $(this).data("firstHeight")
			}, 500, "easeout");
		return false;
	});
	$(".responseAssetInfoPanel").hide();
	$("#artefactResponseForm .responseAssetInfo a").toggle(function() {
		$(this).parent().next(".responseAssetInfoPanel").animate({
				height: "toggle"
			}, 500, "easeinout");
		}, function() {
			$(this).parent().next(".responseAssetInfoPanel").animate({
				height: "toggle"
			}, 500, "easeinout");
		return false;
	});
	 
	
	$("#panelArtefactAssetsControls ul:first a[rel^='prettyPhoto'], #artefactMainImage[rel^='prettyPhoto'], #artefactResponseImages ol:first a[rel^='prettyPhoto']").prettyPhoto({
				animationSpeed:500,
				showTitle: false,
				flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="{width}" height="{height}" id="ZoomifyViewer"><param name="bgcolor" value="#FFFFFF"> <param name="wmode" value="transparent"> <param name="menu" value="false"> <param name="src" value="{path}"><embed src="{path}" menu="false" wmode="transparent" pluginspage="http://www.adobe.com/go/getflashplayer" bgcolor="#FFFFFF" type="application/x-shockwave-flash" width="{width}" height="{height}" name="ZoomifyViewer"></embed></object>'
	});
	
	$("#panelArtefactImages a.magnifyIcon").click(function(e) {
	   	$(this).prev().trigger('click');
		e.preventDefault();
	});

	$("#panelArtefactConnections a, #footerSplash a, #footer ul#footerSponsors li#textileMuseum a, #panelSocialFabric a").click( function() {
		window.open( $(this).attr('href') );
		return false;
	});
	$(".navHereStates").lavaLamp({ fx: "easeout", speed: 700 });

	$("#artefactResponseForm textarea").css({"maxHeight" : "350px", "maxWidth": "497px"}).elastic();
	//$("#artefactResponseForm input.input, #artefactResponseForm textarea").fieldtag();

	$('#responseImage').MultiFile({ 
		max: 7, 
		accept: 'gif|jpg',
		imageheight : 32,
		imagewidth : 78,
		width : 321
	}); 

	$("input#responseImage").filestyle({ 
		image: "/socialfabric/socialfabric/images/en/btnSelectFile.png",
		imageheight : 32,
		imagewidth : 78,
		width : 321,
		bind : false
	 });

	$("input.responseAudio").filestyle({ 
		image: "/socialfabric/socialfabric/images/en/btnSelectFile.png",
		imageheight : 32,
		imagewidth : 78,
		width : 321,
		bind : true
	 });

	$("span.errMsg").css({
		'-moz-background-clip':'border',
		'-moz-background-inline-policy':'continuous',
		'-moz-background-origin':'padding',
		'-moz-border-radius-bottomleft':'8px',
		'-moz-border-radius-bottomright':'8px',
		'-moz-border-radius-topleft':'8px',
		'-moz-border-radius-topright':'8px',
		color: '#FFF',
		backgroundColor:'#990000',
		padding: '2px 12px 2px 20px',
		marginTop: '10px'
	});
	
	$(".secSilkyShiny #artefactTitle, .secSilkyShiny #footer #footerCredits a, .secSilkyShiny #footer #footerCredits span").css({
		'text-shadow' : '#dc7856 1px 1px 1px'
	});

	$(".secAromaticHeavy #artefactTitle, .secAromaticHeavy #footer #footerCredits a, .secAromaticHeavy #footer #footerCredits span").css({
		'text-shadow' : '#dc9956 1px 1px 1px'
	});

	var bgImageTotal=5;
	var fgImageTotal=4;
	
	var randomBgNumber = Math.round(Math.random()*(bgImageTotal-1)) + 1;
	var randomFgNumber = Math.round(Math.random()*(fgImageTotal-1)) + 1;
	
	var bgImgPath=('/socialfabric/socialfabric/images/imgSplashImage'+randomBgNumber+'.jpg');
	var fgImgPath=('/socialfabric/socialfabric/images/imgSplashBackDrop'+randomFgNumber+'.png');
	
	$('#splashPanel').css('background-image', ('url("'+bgImgPath+'")'));
	$('#splashBackDrop').css('background-image', ('url("'+fgImgPath+'")'));
});
