$(document).ready(function() {
	// Set up styles for inner pages
	if (location.pathname != "/") {
		$('body').addClass('inner-page');
	}

	// Set up the quote marks on testimonials
	$("ul.testimonials li div.quote").wrap("<div class='quote-close'></div>").wrap("<div class='quote-open'></div>");

	// Set up the navigation
	initNav();

	// Set up social media links
	socialMediaLinks();

	// Add PNG overlays to featured items in the left column
	if (typeof document.body.style.maxHeight != "undefined") {
		$("#featured li a.icon img").before("<span class='icon-border'></span>");
	}

	// Tabs
	$('#tabs').tabs({
		select: function(event, ui){
			$(".contactflow").each(function(){
				if ($(this).find(".scrollbar").length == 0){
					var contactFlow = new ImageFlow();
					contactFlow.init({ ImageFlowID: $(this).attr("id"), aspectRatio: 1.5, reflections: false, imageCursor: "default", sliderWidth: 22, startAnimation: true });
				}
			});
		}
	});

	// Navigation highlights:

	// Using the current path (e.g. /Section/Page)
	var path = location.pathname;

	// Tooltips

	// Logo
	if (path != "/") {
		$("#wrapper h1.logo").qtip({
			content: "<p style='text-align: center; font-size: 14px; font-weight: bold; color: #054F7C;'>Return to Homepage</p>", show: { delay: 0, effect: { type: 'slide'} }, hide: { effect: { type: 'slide'} }, position: { corner: { tooltip: 'bottomMiddle' }, adjust: { x: -78, y: 54} }, style: { width: 180, border: { width: 6, radius: 5, color: "#054F7C" }, tip: { corner: 'topMiddle', color: '#054F7C'} }
		});
	}

	// Main Image
	//    if ((path == "/") || (path == "/default.aspx")) {
	//        $("#main-image").qtip({
	//            content: "Green", show: { delay: 0, effect: { type: 'slide'} }, hide: { effect: { type: 'slide'} }, position: { corner: { tooltip: 'bottomMiddle' }, adjust: { x: 0, y: 0} }, style: { width: 180, border: { width: 6, radius: 5, color: "#054F7C" }, tip: { corner: 'topMiddle', color: '#054F7C'} }
	//        });
	//    }

	// Handle links to the current path
	if (path) {
		$('a[href$="' + path + '"]').addClass('active').parents().filter('li').addClass('active');

		// Partial Match
		var partial = path.substring(0, path.lastIndexOf('\/'));

		// If not at the root
		if (partial != "") {
			$('a[href$="' + partial + '"]').addClass('active').parents().filter('li').addClass('active');
		}

		// 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] + '"]').addClass('active');
			}
			if (parts[i].toLowerCase().indexOf("green") >= 0) {
				$("#content").addClass("green");
			}
		}
	}

	// Image flow

	// For contacts
	//var contactFlow = new ImageFlow();
	//contactFlow.init({ ImageFlowID: 'contactflow', aspectRatio: 1.5, reflections: false, imageCursor: "default", sliderWidth: 22, startAnimation: true });
	

	// For pages
	//var pageFlow = new ImageFlow();
	//pageFlow.init({ ImageFlowID: 'pageflow', reflections: false, imageCursor: "pointer", sliderWidth: 22, startAnimation: true });

	// For projects
	//var projectFlow = new ImageFlow();
	//projectFlow.init({ ImageFlowID: 'projectflow', reflections: false, imageCursor: "pointer", sliderWidth: 22, startAnimation: true });

	// Gallerific

	var onMouseOutOpacity = 0.67;

	$('#thumbs ul.thumbs li').opacityrollover({
		mouseOutOpacity: onMouseOutOpacity,
		mouseOverOpacity: 1.0,
		fadeSpeed: 'fast',
		exemptionSelector: '.selected'
	});

	try {

		var gallery = $('#thumbs').galleriffic({
			delay: 3000, // in milliseconds
			numThumbs: 10, // The number of thumbnails to show page
			preloadAhead: 2, // Set to -1 to preload all images
			enableTopPager: false,
			enableBottomPager: true,
			maxPagesToShow: 7,  // The maximum number of pages to display in either the top or bottom pager
			imageContainerSel: '#slideshow', // The CSS selector for the element within which the main slideshow image should be rendered
			controlsContainerSel: '#controls', // The CSS selector for the element within which the slideshow controls should be rendered
			captionContainerSel: '#caption', // The CSS selector for the element within which the captions should be rendered
			loadingContainerSel: '#loading', // The CSS selector for the element within which should be shown when an image is loading
			renderSSControls: false, // Specifies whether the slideshow's Play and Pause links should be rendered
			renderNavControls: true, // Specifies whether the slideshow's Next and Previous links should be rendered
			playLinkText: 'Play',
			pauseLinkText: 'Pause',
			prevLinkText: 'Previous',
			nextLinkText: 'Next',
			nextPageLinkText: 'Next &rsaquo;',
			prevPageLinkText: '&lsaquo; Prev',
			enableHistory: false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
			enableKeyboardNavigation: true, // Specifies whether keyboard navigation is enabled
			autoStart: false, // Specifies whether the slideshow should be playing or paused when the page first loads
			syncTransitions: false, // Specifies whether the out and in transitions occur simultaneously or distinctly
			defaultTransitionDuration: 1000, // If using the default transitions, specifies the duration of the transitions
			onSlideChange: function(prevIndex, nextIndex) {
				// 'this' refers to the gallery, which is an extension of $('#thumbs')
				this.find('ul.thumbs').children()
								.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
								.eq(nextIndex).fadeTo('fast', 1.0);
			}, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
			onPageTransitionOut: function(callback) {
				this.fadeTo('fast', 0.0, callback);
			},
			onPageTransitionIn: function() {
				this.fadeTo('fast', 1.0);
			}
		});
	}
	catch (e) { }

	$('#thumbsP ul.thumbs li').opacityrollover({
		mouseOutOpacity: onMouseOutOpacity,
		mouseOverOpacity: 1.0,
		fadeSpeed: 'fast',
		exemptionSelector: '.selected'
	});

	try {

		var galleryP = $('#thumbsP').galleriffic({
			delay: 3000, // in milliseconds
			numThumbs: 10, // The number of thumbnails to show page
			preloadAhead: 2, // Set to -1 to preload all images
			enableTopPager: false,
			enableBottomPager: true,
			maxPagesToShow: 7,  // The maximum number of pages to display in either the top or bottom pager
			imageContainerSel: '#slideshowP', // The CSS selector for the element within which the main slideshow image should be rendered
			controlsContainerSel: '#controlsP', // The CSS selector for the element within which the slideshow controls should be rendered
			captionContainerSel: '#captionP', // The CSS selector for the element within which the captions should be rendered
			loadingContainerSel: '#loadingP', // The CSS selector for the element within which should be shown when an image is loading
			renderSSControls: false, // Specifies whether the slideshow's Play and Pause links should be rendered
			renderNavControls: true, // Specifies whether the slideshow's Next and Previous links should be rendered
			playLinkText: 'Play',
			pauseLinkText: 'Pause',
			prevLinkText: 'Previous',
			nextLinkText: 'Next',
			nextPageLinkText: 'Next &rsaquo;',
			prevPageLinkText: '&lsaquo; Prev',
			enableHistory: false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
			enableKeyboardNavigation: true, // Specifies whether keyboard navigation is enabled
			autoStart: false, // Specifies whether the slideshow should be playing or paused when the page first loads
			syncTransitions: false, // Specifies whether the out and in transitions occur simultaneously or distinctly
			defaultTransitionDuration: 1000, // If using the default transitions, specifies the duration of the transitions
			onSlideChange: function(prevIndex, nextIndex) {
				// 'this' refers to the gallery, which is an extension of $('#thumbs')
				this.find('ul.thumbs').children()
								.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
								.eq(nextIndex).fadeTo('fast', 1.0);
			},
			onPageTransitionOut: function(callback) {
				this.fadeTo('fast', 0.0, callback);
			},
			onPageTransitionIn: function() {
				this.fadeTo('fast', 1.0);
			}
		});
	}
	catch (e) { }

});

function initNav() {
    // Show our navigation
    $("#nav").show();
    $("#nav li ul").wrap("<div class='drop-down'></div>");
    
    var navRoot = document.getElementById("nav");
    if (navRoot == null) {
        return;
    }
	var lis = navRoot.getElementsByTagName("li");
	var _width = 0;
	for (var i=0; i<lis.length; i++) {
		lis[i].onmouseover = function()
		{
			var divs = this.getElementsByTagName("div");
			for (var k=0; k<divs.length; k++) {
				if (divs[k].className.indexOf("dropdown") != -1) {
					var uls = divs[k].getElementsByTagName("li");
					for (var j=0; j<uls.length; j++) {
						if (_width < uls[j].offsetWidth) {
							_width = uls[j].offsetWidth; 
						}
					}
					if (_width > 220) {
						for (var j=0; j<uls.length; j++) {
							uls[j].style.width = _width + "px";
						}
						divs[k].style.width = _width + 5 + "px";
					}
					else {
						for (var j=0; j<uls.length; j++) {
							uls[j].style.width = "220px";
						}
						divs[k].style.width = "225px";
					}
				}
			}
			this.className += " hover";}
		lis[i].onmouseout = function() {
			this.className = this.className.replace("hover","");
		}
	}
}

function socialMediaLinks() {
	// Pull latest Facebook status
	// TOOD: Let's not do this unless the user hovers?
	$(".socialmedia a[href^='http://www.facebook.com']").each(function() {
		var $anchor = $(this);
		$.ajax({
			type: "GET",
			url: "/WebUtilities/Proxy.ashx?url=http://graph.facebook.com/130308153647931/feed",
			data: "limit=1",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {
				$anchor.qtip({ content: "<p><img src='http://graph.facebook.com/130308153647931/picture' align='left' width='50' height='50' style='margin: 0px 8px 4px 0px;' /><strong>Latest from Facebook:</strong> " + msg.data[0].message + "</p><p><a href='" + $anchor.attr("href") + "'>Connect with us on Facebook.</a></p>", api: { onShow: function() { } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true }, position: { adjust: { x: 4, y: 0 }, corner: { target: 'leftBottom', tooltip: 'topRight'} }, style: { width: 400, background: '#FFFFFF', border: { width: 2, radius: 4, color: "#054F7C" }, tip: { corner: 'topRight', color: '#054F7C'}} });
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				window.status = textStatus + ": " + errorThrown;
			}
		});
	});

	// Pull latest tweet
	// TOOD: Let's not do this unless the user hovers?
	$(".socialmedia a[href^='http://twitter.com']").each(function() {
		var $anchor = $(this);
		$.ajax({
			type: "GET",
			url: "/WebUtilities/Proxy.ashx?url=http://api.twitter.com/1/statuses/user_timeline/EDiS_Company.json",
			data: "count=1",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {
				//window.status = msg[0].user.profile_image_url;
				$anchor.qtip({ content: "<p><img src='" + msg[0].user.profile_image_url + "' align='left' width='50' height='50' style='margin: 0px 8px 8px 0px;' /><strong>Latest from Twitter:</strong> " + msg[0].text + "</p><p><a href='" + $anchor.attr("href") + "'>Follow us on Twitter here.</a></p>", api: { onShow: function() { } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true }, position: { adjust: { x: 4, y: 0 }, corner: { target: 'leftBottom', tooltip: 'topRight'} }, style: { width: 400, background: '#FFFFFF', border: { width: 2, radius: 4, color: "#054F7C" }, tip: { corner: 'topRight', color: '#054F7C'}} });
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				window.status = textStatus + ": " + errorThrown;
			}
		});
	});
}

/**
 * jQuery Opacity Rollover plugin
 *
 * Copyright (c) 2009 Trent Foley (http://trentacular.com)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */
;(function($) {
	var defaults = {
		mouseOutOpacity:   0.67,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	};

	$.fn.opacityrollover = function(settings) {
		// Initialize the effect
		$.extend(this, defaults, settings);

		var config = this;

		function fadeTo(element, opacity) {
			var $target = $(element);
			
			if (config.exemptionSelector)
				$target = $target.not(config.exemptionSelector);	
			
			$target.stop().fadeTo(config.fadeSpeed, opacity);
		}

		this.css('opacity', this.mouseOutOpacity)
			.hover(
				function () {
					fadeTo(this, config.mouseOverOpacity);
				},
				function () {
					fadeTo(this, config.mouseOutOpacity);
				});

		return this;
	};
})(jQuery);
