var Interprise = {};

Interprise.Images = {};

Interprise.Images.ClickToZoom = (function() {

	return {
		init	: function() {
			$("img.screenShot").click(function() {
						$(this).toggleClass("large");
					});
		}
	}

})();

Interprise.Links = (function() {
	return {
		replaceSearchString	: function(link, searchString) {
			var searchIndex = link.indexOf("?"),
				anchorIndex = link.indexOf("#");
			if (searchIndex !== -1) {
				link = link.replace(/\?[^#]*/, "?" + searchString);
			} else if (anchorIndex !== -1) {
				link =
						link.substring(0, anchorIndex) + "?" + searchString
								+ link.substr(anchorIndex);
			} else {
				link = link + "?" + searchString;
			}
			return link;
		}
	};
})();

Interprise.Links.ReadMore = (function() {

	// constants
	var READ_MORE_LINK_TEXT = "More&nbsp;&raquo;",
		READ_LESS_LINK_TEXT = "&laquo;&nbsp;Less";

	// private vars
	var $readMoreLink =
			$("<a href='#' class='read_more_link'>" + READ_MORE_LINK_TEXT + "</a>")
					.click(readMore),
		$readLessLink =
				$("<a href='#' class='read_less_link'>" + READ_LESS_LINK_TEXT + "</a>")
						.click(readLess);

	// private functions

	function readMore() {
		var $elem = $(this),
			$parentSiblings =
					$elem.parent("p").next(".read_more,.read_more_continued").show();

		$elem.siblings(".read_more,.read_more_continued").show();

		$elem.siblings(".read_less_link").removeClass("hidden");
		$parentSiblings.find(".read_less_link").removeClass("hidden");

		$elem.addClass("hidden");
		return false;
	}

	function readLess() {
		var $elem = $(this);

		$elem.siblings(".read_more").hide().end().siblings(".read_more_link")
				.removeClass("hidden");
		$elem.parent("p").parent(".read_more").hide().prev("p")
				.find(".read_more_link").removeClass("hidden");
		$elem.parent("p").parent(".read_more_continued").hide().prev("p")
				.find(".read_more").hide().siblings(".read_more_link")
				.removeClass("hidden");

		$elem.addClass("hidden");
		return false;
	}

	function createReadMoreLinks() {
		$(".read_more").each(function() {
			var $elemToAttachMoreLinkTo, $elemToAttachLessLinkTo,
				$this = $(this);

			if ($this.parent("p").length == 1) { // attach to parent
				$elemToAttachMoreLinkTo = $this.parent("p");
				if ($this.parent("p").next(".read_more_continued").length == 1) {
					$elemToAttachLessLinkTo =
							$this.parent("p").next(".read_more_continued").children("p:last");
				} else {
					$elemToAttachLessLinkTo = $this.parent("p");
				}
			} else { // attach to previous parent
				$elemToAttachMoreLinkTo = $this.prev("p");
				$elemToAttachLessLinkTo = $this.children("p:last");
			}

			$elemToAttachMoreLinkTo.append("&nbsp;")
					.append($readMoreLink.clone(true));
			$elemToAttachLessLinkTo.append("&nbsp;")
					.append($readLessLink.clone(true));

			$this.hide();
			$this.parent("p").next(".read_more_continued").hide();
		});

		$(".read_less_link").addClass("hidden");

		// creating links and hiding content messes up the location hash
		if (window.location.hash)
			window.location = window.location;
	}

	// return public API
	return {

		init	: createReadMoreLinks

	};
})();

Interprise.Links.AnchorScroll = (function() {

	// private functions
	function filterPath(string) {
		return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/,
				'').replace(/\/$/, '');
	}

	function setupLinks() {
		var locationPath = filterPath(location.pathname);

		$('a').each(function() {
			// setup scrolling for anchor links
			var thisPath = filterPath(this.pathname) || locationPath;
			if (locationPath == thisPath
					&& (location.hostname == this.hostname || !this.hostname)
					&& this.hash.replace(/#/, '')) {
				$(this).click(function(event) {
							var $target = $("a[name*=" + this.hash.replace("#", "") + "]"),
								target = this.hash;

							if (target) {
								var targetOffset = $target.offset().top - 5,
									targetName = $target.attr("name");

								event.preventDefault();
								// temporarily rename hash to prevent the browser from jumping
								// to it
								$target.attr("name", "temp_" + targetName);
								location.hash = targetName;
								$('html,body').animate({
											scrollTop	: targetOffset
										}, 600, function() {
											// reset anchor name to original value
											$target.attr("name", targetName);
										});
							}
						});
			}

			// setup external links and pdfs
			if ((location.hostname != this.hostname)
					|| this.href.toLowerCase().indexOf(".pdf") != -1) {
				this.target = "_blank";
				this.title = "Opens in new window or tab"
			}
		});
	}

	function scrollToAnchorOnLoad() {
		var $target, targetOffset,
			hash = location.hash.replace("#", "");
		if (hash) {
			$target = $("a[name*=scroll_" + hash + "]");
			if ($target.length) {
				targetOffset = $target.offset().top - 5;
				setTimeout(function() {
							$('html,body').animate({
										scrollTop	: targetOffset
									}, 600);
						}, 400);
			}
		}
	}

	// public API
	return {
		init	: function() {
			setupLinks();
			scrollToAnchorOnLoad();
		}
	};

})();

Interprise.SupplyChainBar = (function() {

	// private vars
	var isInternalPage = false,
		$scbar = $("#scbar"),
		// number of images per portal: index 0=headoffice, 1=vendor, 2=retailer,
		// 3=consumer
		portalQuote = [1, 1, 1, 3];

	function changeSlide(slide, changeQuote) {
		// first change the portal
		$scbar.removeClass().addClass("tab_" + slide.portal);
		var $link =
				$scbar.find("a").removeClass("selected").filter("#tab_" + slide.portal)
						.addClass("selected");

		$link.attr("href", Interprise.Links.replaceSearchString($link.attr("href"),
						"quote=" + slide.portalImage));

		// change the quote if not animation or internal page
		if (changeQuote) {
			Interprise.SupplyChainBar.Animation._stopAnimation();

			$("#photo_img").hide().attr("src", slide.photo).css({
						opacity			: "1",
						marginLeft	: ""
					}).show();
			$("#quote_img").hide().attr("src", slide.quote).css({
						opacity			: "1",
						marginLeft	: ""
					}).show();
		}
		return slide;
	}

	function getRandomPortalImage(portal) {
		if (portalQuote[portal - 1] > 1)
			return Math.ceil(Math.random() * portalQuote[portal - 1]);
		else
			return 1;
	}

	function getSlide(portal, portalImage) {
		portalImage =
				(portalImage && portalImage >= 1 && portalImage <= portalQuote[portal
						- 1]) ? portalImage : getRandomPortalImage(portal);
		return {
			portal			: portal,
			portalImage	: portalImage,
			photo				: "resources/img/photo" + portal + "-" + portalImage + ".jpg",
			quote				: "resources/img/quote" + portal + "-" + portalImage + ".png"
		};
	}

	return {
		init					: function(internalPage) {

			$(".sctab").mouseover(function() {
				if ( ! $(this).is(".selected") ) 
					changeSlide(getSlide(parseInt(this.id.replace("tab_", "")), false),
						!internalPage ? true : false);
			});

			$("#quote_img,#photo_img").click(function() {
						location.href = $("#scbar a.selected").attr("href");
					});

			if (internalPage) {
				isInternalPage = true;
				if (typeof Interprise.InternalPage !== "undefined") {

					var slide =
							getSlide(Interprise.InternalPage.portal,
									Interprise.InternalPage.portalImage);

					changeSlide(slide, true);

					$("#quote" + slide.portalImage).show();

					$scbar.mouseleave(function() {
								changeSlide(slide);
							});
				}
			}

			Interprise.SupplyChainBar.Animation.init(internalPage);

		},

		_changeSlide	: changeSlide,

		_getSlide			: getSlide,

		_totalSlides	: portalQuote.length

	};
})();

Interprise.SupplyChainBar.Animation = (function() {
	// constants
	var SLIDESHOW_DURATION = 5000,
		SLIDE_FADE_SPEED = 500;

	// private vars
	var animationTimeout1, animationTimeout2, slideshowTimeout,
		totalSlides = Interprise.SupplyChainBar._totalSlides,
		animateQuoteHideStartParams = {
			opacity			: 1,
			marginLeft	: 0
		},
		animateQuoteHideEndParams = {
			opacity			: 0,
			marginLeft	: 30
		},
		animateQuoteShowStartParams = {
			opacity			: 0,
			marginLeft	: -50
		},
		animateQuoteShowEndParams = {
			opacity			: 1,
			marginLeft	: 0
		},
		animatePhotoHideStartParams = {
			opacity			: 1,
			marginLeft	: 0
		},
		animatePhotoHideEndParams = {
			opacity			: 0,
			marginLeft	: 50
		},
		animatePhotoShowStartParams = {
			opacity			: 0,
			marginLeft	: -50
		},
		animatePhotoShowEndParams = {
			opacity			: 1,
			marginLeft	: 0
		};

	// private functions
	function setSlideshowTimeout() {
		slideshowTimeout = setTimeout(switchImage, SLIDESHOW_DURATION);
	}

	function clearSlideshowTimeout() {
		clearTimeout(slideshowTimeout);
		slideshowTimeout = null;
	}

	function getNextSlideIndex() {
		var currentSlide = $("#scbar").attr("class").replace("tab_", "");
		return (currentSlide % totalSlides) + 1;
	}

	function switchImage() {
		var photoQuoteCheckInterval,
			speed = SLIDE_FADE_SPEED,
			nextSlideIndex = getNextSlideIndex(),
			nextSlide = Interprise.SupplyChainBar._getSlide(nextSlideIndex),
			quoteImg = new Image(),
			photoImg = new Image(),
			quoteImgLoaded = false,
			photoImgLoaded = false,
			animateFunction = function() {

				// fade out prev photo
				$("#photo_img").css(animatePhotoHideStartParams).animate(
						animatePhotoHideEndParams, {
							duration	: speed
						});

				// fade out prev quote
				$("#quote_img").css(animateQuoteHideStartParams).animate(
						animateQuoteHideEndParams, {
							duration	: speed,
							complete	: function() {
								$("#photo_img").attr("src", "");
								$("#quote_img").attr("src", "");
								animationTimeout1 = setTimeout(function() {
											// change selected tab and then fade in new photo
											Interprise.SupplyChainBar._changeSlide(nextSlide, false);

											animationTimeout2 = setTimeout(function() {
														$("#photo_img").attr("src", nextSlide.photo)
																.css(animatePhotoShowStartParams).animate(
																		animatePhotoShowEndParams, {
																			duration	: speed
																		});

														// fade in new quote
														$("#quote_img").attr("src", nextSlide.quote)
																.css(animateQuoteShowStartParams).animate(
																		animateQuoteShowEndParams, {
																			duration	: speed,
																			complete	: function() {
																				setSlideshowTimeout();
																			}
																		});
													}, speed * 1.5);
										}, speed * 1.5);
							}
						});


			};

		quoteImg.onload = function() {
			quoteImgLoaded = true;
		}
		quoteImg.src = nextSlide.quote;

		photoImg.onload = function() {
			photoImgLoaded = true;
		}
		photoImg.src = nextSlide.photo;

		photoQuoteCheckInterval = setInterval(function() {
					if (quoteImgLoaded && photoImgLoaded) {
						clearInterval(photoQuoteCheckInterval);
						animateFunction();
					}
				}, 200);
	}

	// return public API

	return {

		init						: function(internalPage) {
			if (!internalPage) {

				$("#scbar").mouseenter(clearSlideshowTimeout)
						.mouseleave(setSlideshowTimeout);

				// animate first slide
				Interprise.SupplyChainBar._changeSlide(Interprise.SupplyChainBar
						._getSlide(1, false, true));

				$("#photo_img").css(animatePhotoShowStartParams).animate(
						animatePhotoShowEndParams, {
							duration	: SLIDE_FADE_SPEED,
							complete	: function() {
								$("#quote_img").css(animateQuoteShowStartParams).animate(
										animateQuoteShowEndParams, {
											duration	: SLIDE_FADE_SPEED
										});
							}
						});

				setSlideshowTimeout();
			}
		},

		_stopAnimation	: function() {
			clearTimeout(animationTimeout1);
			clearTimeout(animationTimeout2);

			$("#photo_img,#quote_img").stop({
						gotoEnd	: false
					});
		}

	};
})();

Interprise.BlogSidebar = (function() {
	function parseFeed(feed) {
		var html = '', day, month, year;

		for (var i = 0; i < feed.items.length && i < 5; i++) {
			var item = feed.items[i];
			item.updated = item.updated.split(" ");
			day = item.updated[1];
			month = item.updated[2];
			year = item.updated[3];
			html += '<div class="blogpost">';
			html +=
					'<div class="blogupdated">' + month.substring(0, month.length) + " "
							+ day + ", " + year + '</div>';
			html +=
					'<a class="bloglink" href="' + item.link + '">' + item.title + '</a>';
			html += '</div>';
			if ((i + 1) != feed.items.length)
				html += "<hr />";
		}

		return html;
	}

	return {
		init	: function(url) {
			$.getFeed({
						url			: url,
						success	: function(feed) {
							$('#blog .sidebar_middle').append(parseFeed(feed));
						}
					});
		}
	};
})();

Interprise.Page = {};

Interprise.Page.Contact = (function() {
	return {
		sendToChanged	: function() {
			$("#response_form_name")
					.val("http://www.interprisesoftware.com/contact.html#"
							+ $("#sendTo").val());
		}
	};
})();

$(function() {
	/*
	 * use Arial on WinXP in Firefox or IE6 (ClearType not on by default) and
	 * change font size
	 * 
	 */
	if (navigator.userAgent.indexOf("Windows NT 5.1") != -1
			&& (($.browser.mozilla && !TypeHelpers.hasSmoothing()) || $.browser.version == "6.0")) {
		$(document.body).addClass("arial");
	}

	if ($.browser.version == "6.0" && $.browser.msie)
		document.execCommand('BackgroundImageCache', false, true);

	brFindEmails();

	Interprise.Links.ReadMore.init();
	Interprise.Links.AnchorScroll.init();
	Interprise.Images.ClickToZoom.init();


	// Interprise.BlogSidebar.init(); // uncomment to load blog sidebar items

	var internalPage = (document.body.className.indexOf("home") == -1);
	Interprise.SupplyChainBar.init(internalPage);

});

/* old stuff still being used */

function setSubmitCommand(val) {
	document.forms[0].submitCommand.value = val;
}

function verifySubmit() {
	return true;
}

function getElem(id) {
	return document.getElementById(id);
}

function toggleQuotes() {
	var q = getElem("quotes");
	q.style.display = (q.style.display == "block" ? "none" : "block");
	return false;
}

function makeEmail(recipient, domain) {
	if (!domain)
		domain = location.host;
	if (domain.indexOf("www") == 0)
		domain = domain.substring(4);
	return (recipient + "@" + domain);
}

function emailLink(recipient, domain) {
	var addr = makeEmail(recipient, domain);
	return '<a href="mailto:' + addr + '">' + addr + '</a>';
}

function brMail(recipient, domain) {
	document.write(emailLink(recipient, domain));
}

function mail(recipient) {
	document.write(emailLink(recipient));
}

function mail2(recipient) {
	document.write(makeEmail(recipient));
}

function brFindEmails(elem) {
	var i, href, html, x, endChunk, startChunk, addr, fullAddress, recip;
	for (i = 0; i < document.links.length; i++) {
		href = document.links[i].href.toLowerCase();
		if (href.indexOf("ismail:") == 0) {
			document.links[i].href = "mailto:" + convertEmail(href);
		}
	}
	if (!elem)
		elem = document.body;

	do { // keep checking all html until we catch all instances
		html = elem.innerHTML;
		x = html.toLowerCase().indexOf("ismail:");
		if (x != -1) {
			endChunk = html.substring(x + 7);
			startChunk = html.substring(0, x);
			addr = "";
			fullAddress = endChunk.match(/^[\w-_]+%[\w-_]+\.\w+\b/);
			if (fullAddress) {
				addr = fullAddress[0].split("%");
				addr = emailLink(addr[0], addr[1]);
				endChunk = endChunk.substring(fullAddress[0].length);
			} else {
				recip = endChunk.match(/^[\w-_]+\b/);
				if (recip) {
					addr = emailLink(recip[0]);
					endChunk = endChunk.substring(recip[0].length);
				}
			}
			elem.innerHTML = startChunk + addr + endChunk;
		}
	} while (x != -1)

}

function convertEmail(text) {
	var addr = stripSpaces(text.substring(7));
	var fullAddress = addr.match(/^[\w-_]+%[\w-_]+\.\w+\b/);
	if (fullAddress) {
		addr = fullAddress[0].split("%");
		return makeEmail(addr[0], addr[1]);
	}
	if (addr.match(/^[\w-_]+$/)) {
		return makeEmail(addr);
	}
	return "";
}


function PopImg(url, w, h) { // overrides IE6 auto image resizing
	var sizeStr = (w) ? (",width=" + w + ",height=" + h) : "";
	var newWindow =
			window
					.open("", "PopUp", "titlebar,resizable,scrollbars,status" + sizeStr);
	if (newWindow != null) {
		var html = "<html><head><title>Interprise Software</title></head><body>";
		html += '<img src="' + url + '" alt="">';
		html +=
				'<p style="text-align:right"><a href="javascript:self.close()">Close window</a>&nbsp;</p></body></html>';
		newWindow.document.write(html);
		newWindow.document.close();
		newWindow.focus();
	}
}


/*
 * TypeHelpers version 1.0 Zoltan Hawryluk, Nov 24 2009.
 * 
 * Released under the MIT License.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Works for - IE6+ (Windows), - Firefox 3.5+ (Windows, Mac, Linux), - Safari 4+
 * (Windows, Mac OS X), - Chrome 3.0+ (Windows). Opera 10.10 and under reports
 * unknown support for font-smoothing.
 * 
 * 
 * METHODS -------
 * 
 * hasSmoothing() returns: true if font smoothing is enabled false if font
 * smoothing isn't enabled null if it cannot detect if it's on or not.
 * 
 * addClasses() adds the following classes to the html tag:
 * "hasFontSmoothing-true" if font smoothing is enabled "hasFontSmoothing-false"
 * if it isn't "hasFontSmoothing-unknown" if it cannot detect it.
 * 
 */

var TypeHelpers = new function() {
	var me = this;

	me.hasSmoothing = function() {

		// IE has screen.fontSmoothingEnabled - sweet!
		if (typeof(screen.fontSmoothingEnabled) != "undefined") {
			return screen.fontSmoothingEnabled;
		} else {

			try {

				// Create a 35x35 Canvas block.

				// WKR NOTE: changed size and other values to detect non-smoothing for
				// *small* font sizes with Windows XP's "standard" smoothing which only
				// applies to bold and large text
				var i, j, ctx, imageData, alpha,
					canvasNode = document.createElement("canvas");

				canvasNode.width = "20";
				canvasNode.height = "20"

				// We must put this node into the body, otherwise
				// Safari Windows does not report correctly.
				canvasNode.style.display = "none";
				document.body.appendChild(canvasNode);
				ctx = canvasNode.getContext("2d");

				// draw a black letter "O", 32px Arial.
				ctx.textBaseline = "top";
				ctx.font = "14px Arial";
				ctx.fillStyle = "black";
				ctx.strokeStyle = "black";

				ctx.fillText("O", 0, 0);

				// start at (8,1) and search the canvas from left to right,
				// top to bottom to see if we can find a non-black pixel. If
				// so we return true.
				for (j = 1; j <= 15; j++) {
					for (i = 1; i <= 15; i++) {

						imageData = ctx.getImageData(i, j, 1, 1).data;
						alpha = imageData[3];

						if (alpha != 255 && alpha != 0) {
							return true; // font-smoothing must be on.
						}
					}
				}
				// didn't find any non-black pixels - return false.
				return false;
			} catch (ex) {
				// Something went wrong (for example, Opera cannot use the
				// canvas fillText() method. Return null (unknown).
				return null;
			}
		}
	}
		/*
		 * me.insertClasses = function() { var result = me.hasSmoothing(); var
		 * htmlNode = document.getElementsByTagName("html")[0]; if (result == true) {
		 * htmlNode.className += " hasFontSmoothing-true"; } else if (result ==
		 * false) { htmlNode.className += " hasFontSmoothing-false"; } else { //
		 * result == null htmlNode.className += " hasFontSmoothing-unknown"; } }
		 */
	}


/*
 * if EventHelpers.js is included, insert the hasFontSmoothing CSS classes if
 * (window.EventHelpers) {
 * EventHelpers.addPageLoadEvent("TypeHelpers.insertClasses") }
 * 
 */

