$(document).ready(function() {

    // Navigation highlights
    // Using the current path (e.g. /Section/Page)
    var path = location.pathname;

    // Handle links to the current path
    if (path) {
        $('a[href$="' + path + '"]').parents().filter('li').addClass('current');
    }
    
    // Handle links to parts of the current path
	var parts = path.split('/')
	for (i = 0; i < parts.length; i++) {
		if (parts[i].length > 0) {
			$('a[href$="/' + parts[i] + '"]').parents().filter('li').addClass('current');
		}
	}
	
	HandleVariableData();

    // Set the thumbnails to dim in and out on hover
    $(".nails a", "#content").css({ opacity: 0.5 }, 250)
	.hover(
		function() {
		    $(this).stop().animate({ opacity: 1.0 }, 250);
		},
		function() {
		    // Only dim it out if isn't currently active (because it was clicked on)
		    if (!$(this).hasClass('active')) {
		        $(this).stop().animate({ opacity: 0.5 }, 250);
		    }
		}
	).click(function() {
	    // Remove the 'active' class from the active thumbnail and fade it out
	    $(".nails a[class='active']", "#content").removeClass('active').stop().animate({ opacity: 0.5 }, 250);
	    // Set this to be the 'active' thumbnail and fade it in
	    $(this).addClass('active').stop().animate({ opacity: 1.0 }, 250);

	    var href = $(this).attr("href");

	    // Fade out the current sample and when finished, proceed
	    $("#sample").stop().animate({ opacity: 0.0 }, 250, 'swing', function() {
	        // Fade the sample back in about 1 second from now - it may not be done, but it gives a consistent feeling to how long it takes the slides to load
	        setTimeout(function() {
	        $("#sample").stop().animate({ opacity: 1.0 }, 250, 'swing', function() {
	            $(this).removeAttr("style");
	        });
	        }, 500);

	        // Retrieve the overview
	        $.ajax({
	            type: "POST",
	            url: "/DocumentProperties.ashx?nodealiaspath=" + href + "&classnames=Zeroin.WorkSample&properties=NodeAliasPath|DocumentName|WorkSampleDescription",
	            data: '',
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function(msg1) {

	                window.output = "<div class='scrollable'><div class='items'>";

	                // Retrieve the slides
	                $.ajax({
	                    type: "POST",
	                    url: "/DocumentProperties.ashx?nodealiaspath=" + href + "/%&classnames=Zeroin.WorkSampleSlide&properties=NodeAliasPath|DocumentName|SlideContent",
	                    data: '',
	                    contentType: "application/json; charset=utf-8",
	                    dataType: "json",
	                    success: function(msg2) {
	                        // Build up an unordered list using the slides

	                        for (var i = 0; i < msg2.length; i++) {
								window.output += '<img src="/getattachment/' + msg2[i]['SlideContent'] + '/' + msg2[i]['DocumentName'] + '" />';
	                        }
	                        window.output += "</div></div>";
	                        
	                        // Build up the sample name and description
							window.output2 = "<div>";	                
							for (var i = 0; i < msg1.length; i++) {
								window.output2 += "<h3>" + msg1[i]['DocumentName'] + "</h3>";
								window.output2 += "<p>" + msg1[i]['WorkSampleDescription'] + "</p>";
							}
							window.output2 += "</div><a class='prevPage browse left'>Prev</a><a class='nextPage browse right'>Next</a>";

							// Clear the sample area and add our new list
							$("#sample").html('').append(window.output).append(window.output2);
							$("div.scrollable").scrollable({size: 1, loop: true});
							if ($("div.items img").length < 2)
							{
								$("a.nextPage").hide();
							}
	                    },
	                    error: function(XMLHttpRequest, textStatus, errorThrown) {
	                        // Do nothing for now
	                    }
	                });
	            },
	            error: function(XMLHttpRequest, textStatus, errorThrown) {
	                $("#sample").html('<h3>There was an error loading the requested sample.</h3>')
	            }
	        });
	    });
	    return false;
	});
	
	$(".nails a:first").click();
	
	initAudioPlayer('div.testimonials div.audio a', '190', '24');
	initAudioPlayer('#test-container li div.audio a', '240', '24');
	
	equalHeight($(".home .c-c"));
	
	$(".list li").click(function(){
		document.location.href = $(this).find("a:first").attr("href");
	});
	
	// run lavaLamp
    navLamp();

});

function HandleVariableData(){
	// Load variable data if it is present
	try {
		window.vardata = $.cookie('campaignUserInfo');
		if (window.vardata != null) {
			cu.userInfo = vardata.split("&");
            cu.firstname = userInfo[0].split("=")[1];
            cu.lastname = userInfo[1].split("=")[1];
            cu.credentials = "";
            if (cu.userInfo.length > 2) {
                cu.credentials = ", " + userInfo[2].split("=")[1];
            }
		}
    }
    catch(err){}
    
    // Variable data may be handled differently on different pages
    var path = location.pathname.toLowerCase();
}

function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
        var thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}


function initAudioPlayer(selector, playerWidth, playerHeight){
	$(selector).each(function() {
		// Grab video ID from the url
		var href = $(this).attr('href');
		var audioID = $(this).attr('id')

		var embedID = "embed-" + audioID;
		$(this).replaceWith("<div id='" + embedID + "'>You need Adobe Flash to listen to this audio.</div>");

		// Setup video paramters
		var params = { allowScriptAccess: 'always' };
		var attrs = { id: embedID };
		var vars = { soundFile: href,
			/*bg: '0xCB0707',
			leftbg: '0xCB0707',
			lefticon: '0xFFFFFF',
			rightbg: '0xCB0707',
			rightbghover: '0xCB0707',
			righticon: '0xFFFFFF',
			righticonhover: '0x1E1D1E',
			text: '0xFFFFFF',
			slider: '0x000000',
			track: '0xFFFFFF',
			border: '0xB3D8E8',
			loader: '0xB3D8E8',*/
		bg: '0xA04235',
		leftbg: '0xA04235',
			lefticon: '0xFFFFFF',
			rightbg: '0xA04235',
			rightbghover: '0xA04235',
			righticon: '0xFFFFFF',
			righticonhover: '0x1E1D1E',
			text: '0xFFFFFF',
			slider: '0x000000',
			track: '0xFFFFFF',
			border: '0xB3D8E8',
			loader: '0xB3D8E8',
			loop: 'no',
			autostart: 'no',
			playerID: audioID
		};

		// Embed the audioplayer
		swfobject.embedSWF('/Media/Flash/player.swf', embedID, playerWidth, playerHeight, '8', null, vars, params, attrs);
	});
}

function navLamp() {
	$("#nav").lavaLamp({
		fx: "easeOutBack",
		speed: 500,
		click: function(event, menuItem) {
			return false;
		}
	});
}
