function getLastUrlSegment(url) {
	var lastIndex = url.lastIndexOf("/");
	if(lastIndex == -1)
		return url;
	else
		return url.substring(lastIndex+1, url.length);
}

jQuery(document).ready(function() {

	/*
	This function gets loaded when all the HTML, not including the portlets, is
	loaded.
	*/

    // --- scrolling effect for bank logos ---

	// cached objects/calculations
	var banksContainer;
	var banksScroller;
	var scrollLeftHome;
	var scrollLeftEnd;

	var speed = 35000;

	// initialization
	function scrollingBanksInit() {

		// cache objects/calculations to improve performance
		banksContainer = jQuery("#banks-container");
		// if the banksContainer container does not exist return
		if (banksContainer.html() == null) return;
		
		// replace 'marquee' tag with a div (progressive enhancement)

		jQuery(banksContainer).html(
			jQuery(banksContainer)
				.html()
					.toLowerCase()
					.replace("<marquee>", "<div id=\"banks-scroller\">")
					.replace("</marquee>", "</div>"));
				
		banksScroller = jQuery("#banks-scroller");

		jQuery(banksScroller).width(jQuery(banksScroller).children("ul").width() * 2);
		
		scrollLeftEnd = (jQuery(banksScroller).width() - jQuery(banksContainer).width());
		scrollLeftHome = jQuery(banksScroller).children("ul").width() - jQuery(banksContainer).width();

		// duplicate scroller
		jQuery(banksScroller).append(jQuery(banksScroller).children("ul").clone());

		jQuery(banksContainer).bind("mouseenter", function() {
			//jQuery(banksContainer).find("a").animate({ opacity: 0.5 }, "fast");
			jQuery(banksContainer).stop(false);
		});

		jQuery(banksContainer).bind("mouseleave", function() {
			//jQuery(banksContainer).find("a").animate({ opacity: 1.0 }, "fast");
			//.css("opacity", "1.0");
			startAnimation(true);
		});

		jQuery(banksContainer).find("a").bind("mouseenter", function() {
			//jQuery(this).animate({ opacity: 1.0 }, "fast");
		});

		jQuery(banksContainer).find("a").bind("mouseleave", function() {
			//jQuery(this).animate({ opacity: 0.5 }, "fast");
		});

	};

	// recursive function - represents one cycle of the marquee
	function startAnimation(adjustSpeed) {

		// it's important to adjust the timing after the user mouses in then out
		// as, in that case, it will take less time for the scroller to reach the 
		// end-point
		var adjustedSpeed = speed;
		if(adjustSpeed)
			Math.ceil(
				adjustedSpeed -= 
					(speed / (scrollLeftEnd / 
							  jQuery(banksContainer)[0].scrollLeft)));

		jQuery(banksContainer).animate(
			{ scrollLeft: scrollLeftEnd },
			adjustedSpeed,
			"linear",
			function() {
				jQuery(this)[0].scrollLeft = scrollLeftHome;
				startAnimation();
			}
		);
		
	}

	jQuery(document).ready(function() {
		scrollingBanksInit();
		startAnimation(false);
	});


	
	
	
	
	
	
	
	
	
	
	

    // --- make protected email addresses visible ---

    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function Base64Decode(encoded) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        do {
            enc1 = keyStr.indexOf(encoded.charAt(i++));
            enc2 = keyStr.indexOf(encoded.charAt(i++));
            enc3 = keyStr.indexOf(encoded.charAt(i++));
            enc4 = keyStr.indexOf(encoded.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        } while (i < encoded.length);

        return output;
    }

    jQuery("a[class=protectedEmailLink]").each(function() {
        var querystringParam = "redirectToken=";
        var href = jQuery(this).attr("href");
        var email = Base64Decode(href.substr(href.lastIndexOf(querystringParam) + querystringParam.length, href.length));
        jQuery(this)
            .attr("href", "mailto:" + email)
            .text(email.replace("@", "@"));
    });


    // --- auto-focus default form fields ---

    jQuery("form:first .field.default input:first").focus();
    jQuery("form:first .field:has(span.field-validation-error):first *:input:first").focus();


    //jQuery("form input[type=submit]").click(function() {
    //	jQuery(this).blur().attr("disabled", "disabled");
    //});


    // --- show/hide on frequently asked questions --- //

    jQuery(".main div.answer").css("display", "none");
    jQuery(".main h4.question")
			.each(function() {
			    jQuery(this).html("<a href=\"#\" onclick=\"return false;\">" + jQuery(this).text() + "</a>");
			})
			.prepend("<b>+</b>")
			.css("cursor", "pointer")
			.click(function() {
			    var answerDiv = jQuery(this).next("div.answer");
			    if (jQuery(answerDiv).css("display") == "none") {
			        jQuery(".main div.answer").css("display", "none");
			        jQuery(".main h4 b").text("+");
			        jQuery(answerDiv).css("display", "block");
			        jQuery(this).find("b").text("-");
			    }
			    else {
			        jQuery(answerDiv).css("display", "none");
			        jQuery(this).find("b").text("+");
			    }
			});


    // --- "remove highlight" on search result highlights --- //

    jQuery("a.highlight").click(function() {
        jQuery("a.highlight").each(function() {
            jQuery(this).replaceWith(jQuery(this).text());
        });
        return false;
    });




	// --- homepage blurbs effect --- //

	jQuery(document).ready(function() {


		/* --- Variables --- */

		var currentBlurb = jQuery("div#blurbs div.blurb:first");

		var isMouseOnBlurb = false;

		var blurbsMinHeight = parseInt(jQuery("div#blurbs").css("min-height"));

		var isExpanded = false;

		initBlurbs();
	    jQuery("div#blurbs").css("visibility", "visible");


		/* --- Initialization --- */

		function initBlurbs() {

			// copy the first blurb and put it at the end, so we can simulate a 'continous' effect
			jQuery("div#blurbs").append(jQuery("div#blurbs .blurb:first").clone().addClass("continuation"));

			// re-structure blurbs to allow for effects
			jQuery("div#blurbs").append(jQuery("<div class=\"blurb-container\"></div>").append(jQuery("div#blurbs div.blurb")));
			jQuery("div#blurbs .blurb-container").width(jQuery("div#blurbs").width() * jQuery("div#blurbs div.blurb").length + 100);

			// create containers for blurb inner content (text)
			jQuery("div#blurbs .blurb").each(function() {
				jQuery(this).append(jQuery("<div class=\"text\"></div>").append(jQuery(this).children("h2, p, ul")));
			});

			// add back/more/next controls
			jQuery("div#blurbs")
					.append(jQuery("<a href='#' id='blurb-back' style=\"display:none\" class='blurb-control'>back</a>"))
					.append(jQuery("<a href='#' id='blurb-next' style=\"display:none\" class='blurb-control'>next</a>"));
			jQuery("div#blurbs div.blurb p.intro").each(addMoreButton);

			/*// add photos
			jQuery("div#blurbs div.blurb").each(function() {
			jQuery(this).css(
			"background-image",
			"url(/Content/images/blurbs/" +
			jQuery(this).attr("class").replace("blurb ", "")
			+ ".jpg)");
			});*/

			initIntro();

			startBlurbCarousel();

		}

		function initIntro() {
			// fix oversized intro paragraphs
			jQuery("div#blurbs p.intro").each(function() {
				jQuery(this).attr("originalHtml", jQuery(this).html());

				var minHeight = parseInt(jQuery(this).css("min-height").replace("px", ""));
				if (minHeight == 0) minHeight = 84;

				if (jQuery(this).height() > minHeight) {
					while (jQuery(this).height() > minHeight) {
						// remove words until paragraph is an appropriate height
						jQuery(this).text(removeLastWord(jQuery(this).text()));
					}
					var text = jQuery(this).text();
					text = removeLastWordUntilLengthReached(text, text.length - 8);
					text += "... ";
					jQuery(this).text(text);

					// put back the 'more' button if it was removed
					if (jQuery(this).children("a.blurb-more").length == 0)
						jQuery(this).each(addMoreButton);
				}

				jQuery(this).attr("shortenedHtml", jQuery(this).html());
			});

			showOnlyIntro();
		}


		/* --- Event handling --- */

		jQuery("div#blurbs a.blurb-control").mouseover(function() {
			jQuery(this).fadeTo(150, 1.0);
		});

		jQuery("div#blurbs a.blurb-control").mouseout(function() {
			jQuery(this).fadeTo(150, 0.5);
		});

		jQuery("div#blurbs").bind("mouseenter", function() {
			isMouseOnBlurb = true;

			jQuery(this).stopTime();

			showBackForwardButtons();
		});

		jQuery("div#blurbs").bind("mouseleave", function() {
			isMouseOnBlurb = false;

			//if (isBlurbsExpanded())
			if (isExpanded)
				contractCurrentBlurb();

			startBlurbCarousel();

			jQuery(this).find("a.blurb-control").fadeTo(300, 0);
			jQuery(this).find("a.blurb-more").css("display", "inline-block").blur();
		});

		jQuery("div#blurbs a#blurb-back").click(function() {
			moveBlurbs("backward", 250);
			return false;
		});

		jQuery("div#blurbs a#blurb-next").click(function() {
			moveBlurbs("forward", 250);
			return false;
		});

		jQuery("div#blurbs a.blurb-more").click(function() {
			// expand blurb

			// display previously hidden elements
			jQuery(this).parent().parent().children("h2, p, ul, ol").css("display", "block");

			// restore normal intro text
			var parentNode = jQuery(this).parent();
//			parentNode.shortenedHtml = parentNode.innerHtml;
//			parentNode.innerHtml = parentNode.originalHtml;
			jQuery(parentNode).attr("shortenedHtml", jQuery(parentNode).attr("innerHtml"));
			jQuery(parentNode).attr("innerHtml", jQuery(parentNode).attr("originalHtml"));

			expandCurrentBlurb();

			return false;
		});


		/* --- Moving between blurbs --- */

		function moveBlurbs(direction, speed) {
			if (isExpanded) contractCurrentBlurb();

			if (direction == "forward")
				currentBlurb = jQuery(currentBlurb).nextAll("div.blurb:first");
			else if (direction == "backward")
				currentBlurb = jQuery(currentBlurb).prevAll("div.blurb:first");

			if (currentBlurb.length == 0)
				currentBlurb = jQuery("div#blurbs div.blurb:first");

			jQuery("div#blurbs div.blurb-container").animate(
				{ marginLeft: getMarginLeftOfBlurb(currentBlurb) },
				speed,
				function() {
					// if this is a 'continuation' element, we can seamlessly transition back to the beginning
					if (!isMouseOnBlurb) {
						if (jQuery(currentBlurb).hasClass("continuation")) {
							currentBlurb = jQuery("div#blurbs div.blurb:first");
							jQuery("div#blurbs div.blurb-container").css("margin-left", getMarginLeftOfBlurb(currentBlurb));
						}
					}
					if (isMouseOnBlurb) showBackForwardButtons();
				}
			);
			
		}


		/* --- Expanding/contracting blurbs (more button) --- */

		function expandCurrentBlurb() {
			// determine expanded height
			var expandedHeight = jQuery(currentBlurb).height() + 50;
			if (expandedHeight <= blurbsMinHeight)
				expandedHeight = blurbsMinHeight;

			// expand intro text
			var introElement = jQuery(currentBlurb).find("p.intro")
			jQuery(introElement)
				.html(jQuery(introElement).attr("originalHtml"))
				.attr("originalMinHeight", jQuery(introElement).css("min-height"))
				.css("min-height", "0px");

			// expand container
			jQuery("div#blurbs").animate({ height: expandedHeight }, 300);

			// hide 'more' button
			jQuery("#blurbs a.blurb-more").css("display", "none");

			isExpanded = true;
		}

		function contractCurrentBlurb() {
			// fill in shortened intro text
			var introElement = jQuery(currentBlurb).find("p.intro")
			jQuery(introElement)
				.html(jQuery(introElement).attr("shortenedHtml"))
				.css("min-height", jQuery(introElement).attr("originalMinHeight"));

			// contract container
			jQuery("div#blurbs").animate({ height: blurbsMinHeight }, 300);

			// show 'more' button
			jQuery("#blurbs a.blurb-more").css("display", "inline");

			// hide everything but into text
			showOnlyIntro();

			isExpanded = false;
		}


		/* --- Functions --- */

		function startBlurbCarousel() {
			jQuery("div#blurbs").everyTime(
					3500,
					function(i) {
						moveBlurbs("forward", 700);
					}
				);
		};

		function addMoreButton() {
			jQuery(this).append(jQuery("<a href='#' class='blurb-more'>more</a>"));
		}

		function showBackForwardButtons() {
			jQuery("div#blurbs").find("a.blurb-control").css("display", "none").css("opacity", "0.0");

			if (jQuery(currentBlurb).attr("class") != jQuery("div#blurbs .blurb:first").attr("class"))
				jQuery("div#blurbs").find("a#blurb-back").css("display", "block").fadeTo(300, 0.5);

			if (jQuery(currentBlurb).attr("class") != jQuery("div#blurbs .blurb:not(.continuation):last").attr("class"))
				jQuery("div#blurbs").find("a#blurb-next").css("display", "block").fadeTo(300, 0.5);
		}

		function showOnlyIntro() {
			// only display .intro elements at first
			jQuery("div#blurbs div.blurb div.text").children("*:not(.intro, h2)").filter("p, ul, ol").css("display", "none");
		}

		function getMarginLeftOfBlurb(blurb) {
			return (-jQuery(blurb).prevAll().length * jQuery(blurb).width()) + "px";
		}


		/* --- General functions --- */

		function removeLastWord(source) {
			var lastSpace = source.lastIndexOf(" ");
			return source.substr(0, lastSpace);
		}

		function removeLastWordUntilLengthReached(source, maximumLength) {
			while (source.length > maximumLength)
				source = removeLastWord(source);
			return source;
		}

	});
	
	


    // --- center-align footer --- //
    /* management, objectives, stp, dealertoclient, dealertodealer, charlesriver, dataservices */

    jQuery("div#footer>ul").width(0);
    jQuery("div#footer>ul>li").each(function() {
        jQuery(this).parent().width(
				jQuery(this).parent().width() +
				jQuery(this).width() +
				parseInt(jQuery(this).css("margin-right").replace("px", "")) +
				parseInt(jQuery(this).css("padding-right").replace("px", ""))
        //10 // for the border
			);
    });
});


