﻿/// <reference path="jquery-1.3.2-vsdoc.js" />
var divElem = 'AlertDiv';
var messageElem = 'AlertMessage';
var bodyTag = 'bodytag';

function ClearErrorState() {
	$.unblockUI();
}

function EndRequestHandler(sender, args) {
	if (args.get_error() != undefined) {
		var errorMessage;
		if (args.get_response().get_statusCode() == '200') {
			errorMessage = args.get_error().message;
		}
		else {
			// Error occurred somewhere other than the server page.
			errorMessage = 'An unspecified error occurred. ';
		}
		args.set_errorHandled(true);
		$get(messageElem).innerHTML = errorMessage;
		$.blockUI({ message: $get(divElem) });
	}
}


/*
*   Custom Site Scripts
*	@author mjjames
*	@requires jquery
*/

var mjjames = window.mjjames || {};
mjjames.data = window.mjjames.data || {};

mjjames.helpers = window.mjjames.helpers || {};
mjjames.controls = window.mjjames.controls || {};
mjjames.timeouts = window.mjjames.timeouts || {};

mjjames.controls.callbackForm = function () {
	var validateForm = function (e) {
		var valid = true;

		$("div.callbackForm input.txtInput").each(function () {
			valid = String(this.value).length > 0;
		});

		if (!valid) {
			alert("Please Ensure You Have Filled Out All The Fields Before Clicking Call Me");
		}
		return valid;
	};

	return {
		init: function () {
			$("div.callbackForm input.submit").click(mjjames.controls.callbackForm.validate);
		},
		validate: function () {
			return validateForm();
		}
	};
} ();


mjjames.controls.navigationSlider = function () {
    ///<summary>Creates a "Slidable" navigation with optional overlays</summary>

    var _container, _moveLeft, _moveRight, _moveLeftHover, _moveRightHover, _viewer, _scrollAmount, _mouseoverImageContainer, _mouseoverTextContainer, _tickerInterval;
    var _ticker, _totalItems, _itemCounter = 0;

    var setupNavigation = function () {
        ///<summary> Sets up the Navigation</summary>
        var $container = $(_container);
        var $moveLeft = $container.find(_moveLeft);
        var $moveRight = $container.find(_moveRight);

        var $elements = $container.find("li");

        if (typeof (_mouseoverImageContainer) !== "undefined" || typeof (_mouseoverTextContainer) !== "undefined") {
            $elements.mouseover(mouseOver);
        }

        var elementSize = Number(String($elements.css("width")).replace("px", "")) * $elements.length + 25;

        $.scrollTo.defaults.axis = 'x';

        _totalItems = $container
    	        .find(_viewer)
    	        .css("overflow", "hidden")
    	        .scrollTo(0)
    	        .find("ul")
    	        .css("width", elementSize)
    	        .find("li").length;

        $moveLeft
			.css("cursor", "pointer")
			.mouseover(function () {
			    var $img = $(this);
			    var originalImage = $img.attr("src");
			    $img.attr("src", _moveLeftHover);
			    $img.mouseleave(function () {
			        $(this).attr("src", originalImage);
			    });
			    _itemCounter--;
			})
		.click(function () {
		    $(_container).find(_viewer).stop().scrollTo('-=' + _scrollAmount, 800);
		    resetTimer();
		});

        $moveRight
			.css("cursor", "pointer")
			.mouseover(function () {
			    var $img = $(this);
			    var originalImage = $img.attr("src");
			    $img.attr("src", _moveRightHover);
			    $img.mouseleave(function () {
			        $(this).attr("src", originalImage);
			    });
			    _itemCounter++;
			})
		.click(function () {
		    $(_container).find(_viewer).stop().scrollTo('+=' + _scrollAmount, 800);
		    resetTimer();
		});
        resetTimer();
    };

    var resetTimer = function () {
        if (_tickerInterval === 0) {
            return;
        }
        clearInterval(_ticker);
        _ticker = setInterval(tick, _tickerInterval * 1000);
    };

    var mouseOver = function () {
        ///<summary>On Mouse Over swaps an image and text for the navigational items image and text</summary>
        var $this = $(this);

        if (typeof (_mouseoverImageContainer) !== "undefined") {
            var $imageContainer = $(_mouseoverImageContainer);
            var $image = $this.find("a.thumb img");

            var originalAlt = $imageContainer.attr("alt");
            var originalSrc = $imageContainer.attr("src");

            var oldImage = originalSrc.split("&");
            var newImage = String($image.attr("src")).split("&");

            newImage[1] = oldImage[1];
            newImage[2] = oldImage[2];
            newImage[3] = oldImage[3];

            $imageContainer.attr("alt", $image.attr("alt"));
            $imageContainer.attr("src", newImage.join("&"));

            $this.bind("mouseout", { alt: originalAlt, src: originalSrc }, function (event) {
                $(_mouseoverImageContainer).attr("alt", event.data.alt).attr("src", event.data.src);
            });
        }

        if (typeof (_mouseoverTextContainer) !== "undefined") {
            var $textContainer = $(_mouseoverTextContainer);
            var $text = $this.find("a:not(.thumb)");

            var originalTitle = $textContainer.find("h1").text();
            var originalDesc = $textContainer.find("p.desc").text();

            $textContainer.find("h1").text($text.text());
            $textContainer.find("p.desc").text($text.attr("title"));

            $this.bind("mouseout", { title: originalTitle, desc: originalDesc }, function (event) {
                $(_mouseoverTextContainer).find("h1").text(event.data.title).end().find("p.desc").text(event.data.desc);
            });


        }
    };

    var tick = function () {
        //todo: implement tick code
        if (_itemCounter < _totalItems - 1) {
            var $moveright = $(_container).find(_moveRight);
            $moveright.click();
            _itemCounter++;
        }
        else {
            $(_container).find(_viewer).scrollTo(0);
            _itemCounter = 0;
        }
    };

    //    return {
    this.init = function (params) {
        ///<summary> Initialises the JS </summary>
        //<param name="params">Object containing all our properties</param>
        _container = params.container || "";
        _moveLeft = params.moveleft || "";
        _moveRight = params.moveright || "";
        _moveLeftHover = params.movelefthover || "";
        _moveRightHover = params.moverighthover || "";
        _viewer = params.viewer || "";
        _scrollAmount = params.scrollamount || "100px";
        _mouseoverImageContainer = params.mouseoverImageContainer;
        _mouseoverTextContainer = params.mouseoverTextContainer;
        _tickerInterval = params.tickerInterval || 0;


        if ($.scrollTo !== undefined) {
            setupNavigation();
        }
    };
};
//}();

mjjames.controls.articleGrouping = function () {
	var _container, _showhideelement, _showhidecontainer;
	var setup = function () {
		var $container = $(_container);
		$container
			.find(_showhideelement)
			.css("cursor", "pointer")
			.click(function () {
				var $this = $(this);
				$this.next().toggle();
				//$this.parent().parent().height($this.parent().height());
				if (typeof (curvyCorners) !== "undefined") {
					//curvyCorners.redraw();
				}
			})
			.end()
			.find(_showhidecontainer)
			.not(":first")
			.hide();

	};

	return {
		init: function (params) {
			_container = params.container || "";
			_showhidecontainer = params.showhidecontainer || "";
			_showhideelement = params.showhideelement || "";
			setup();
		}
	};
} ();

mjjames.helpers.columnfixer = function () {
	var _column1, _column2;

	var resizeColumn = function () {
		var minheight = $(_column1).height();
		$(_column2).css("min-height", minheight);
	};

	return {
		init: function (params) {
			_column1 = params.column1 || "";
			_column2 = params.column2 || "";
			resizeColumn();
		}
	};
} ();

/// <reference path="jquery-1.3.2-vsdoc.js" />

/*
*   Auto Content Slider
*	@author mjjames
*	@requires jquery
*/



mjjames.controls.Banners = function () {
	//private
	var _$container;
	var _iTimer;
	var _galleryData;
	var _iBannerKey;
	var _iTotalBanners;

	var setupBanners = function () {
		if (_$container.length > 0 && _galleryData !== undefined) {
			_iTotalBanners = _galleryData.length;
			_iBannerKey = 0;
			if (_iTotalBanners > 1) {
				mjjames.timeouts.bannerRotator = setInterval(mjjames.controls.Banners.rotateBanner, _iTimer);
				_$container.mouseenter(function () {
					window.clearInterval(mjjames.timeouts.bannerRotator);
				}).mouseleave(function () {
					mjjames.timeouts.bannerRotator = setInterval(mjjames.controls.Banners.rotateBanner, _iTimer);
				});
			}
			else {
				rotateBanner();
			}

		}
	};

	var rotateBanner = function () {
		if (!_$container.is(":visible")) {
			return;
		}
		_iBannerKey = _iBannerKey + 1;
		if (_iBannerKey >= _iTotalBanners) {
			_iBannerKey = 0;
		}
		var data = _galleryData[_iBannerKey];
		var img = _$container.find("div.image");
		var text = _$container.find("div.text");
		text.html("<h2>" + data.BannerTitle + "</h2><p>" + data.BannerDescription + "</p>");
		img
			.find("a")
			.attr("title", data.BannerTitle)
			.attr("href", data.BannerLink)
			.find("object:visible, img:visible")
			.fadeOut(function () {
				var $parent = $(this).parent();
				var $img = $parent.find("img");
				
				if (data.BannerPath.indexOf("youtube.com") > -1 || data.BannerPath.indexOf("vimeo.com") > -1 || data.BannerPath.indexOf("flickr.com") > -1) {

					var selector = "object";
					//					if (!$.browser.msie) {
					//						selector = "embed";
					//					}
					var $object = $parent.find(selector);
					if ($object.length === 0) {
						var $newObject = $("<object width=\"" + _videoWidth + "\" height=\"" + _videoHeight + "\"><param name=\"movie\" value=\"" + data.BannerPath + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><param name=\"wmode\" value=\"Opaque\"></param><embed src=\"" + data.BannerPath + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" + _videoWidth + "\" height=\"" + _videoHeight + "\" wmode=\"opaque\"></embed></object>");
						$parent.append($newObject);
						$object = $parent.find(selector);

						$object.click(function () {
							return false;
						});
						_$container.mouseenter(function () { //.click(function (e) {
							var $this = $(this);
							if ($this.find("object:visible").length > 0) {
								$this.closest("div").find("div.text").hide();
							}
						}).mouseleave(function () {
							var $this = $(this);
							if ($this.find("object:visible").length > 0) {
								$this.closest("div").find("div.text").show();
							}
						});

					}
					else {
						$object
							.find("param[name='movie']")
							.attr("value", data.BannerPath)
							.end()
							.find("embed")
							.attr("src", data.BannerPath)
							.parents("homeBanners")
							.find("div.text")
							.hide();
					}

					$object.fadeIn();

				}
				else {
					$img
						.attr("title", data.BannerTitle)
						.attr("alt", data.BannerTitle)
						.attr("src", data.BannerPath)
						.fadeIn()
						.closest("div.homeBanners")
						.find("div.text:hidden")
						.show();

				}

			});
	};

	return {
		init: function (params) {
			_$container = $(params.container);
			_iTimer = params.timeout * 1000 || 5000;
			_galleryData = params.data;
			_videoHeight = params.videoHeight || 250;
			_videoWidth = params.videoWidth || 552;
			setupBanners();
		},
		rotateBanner: function () {
			rotateBanner();
		}
	};
} ();

/*
*   Auto Content Slider
*	@author mjjames
*	@requires jquery
*/

var mjjames = window.mjjames || {};
mjjames.controls = window.mjjames.controls || {};
mjjames.timeouts = window.mjjames.timeouts || {};
mjjames.data = window.mjjames.data || {};

mjjames.controls.slider = function () {
	//private stuff
	var _contents1, _contents2, _showhide, _iTimer, _cookieName;

	var setupSlider = function () {
		//if we have no banners don't animate
		if ($(_contents2).find("div.image a").is(":empty")) {
			return;
		}
		$('<a href="#" title="Show / Hide Contents" class="showhide">+/-</a>')
			.appendTo($(_showhide))
			.click(toggleSlider); //setup the show hide link

		if (getCookie()) {
			toggleSlider();
		}
		else { //if we dont have a cookie set default to normal behaviour
			mjjames.timeouts.contentSlider = window.setTimeout(toggleSlider, _iTimer); //setup default content hide
		}
		//if a user mouses over the text area stop the banners from showing until they have stopped looking at it
		$(_contents1).mouseenter(function () {
			window.clearTimeout(mjjames.timeouts.contentSlider);
		}).mouseleave(function () {
			mjjames.timeouts.contentSlider = window.setTimeout(toggleSlider, _iTimer); //setup default content hide
		});

	};

	var toggleSlider = function () {
		window.clearTimeout(mjjames.timeouts.contentSlider);

		$(_contents1).unbind("mouseenter").unbind("mouseleave").slideToggle("slow");
		$(_contents2).slideToggle("slow", function () {
			$(this).trigger('isVisible');
		});

		$.cookie(_cookieName, { content: "hidden" }); //set the cookie
		return false;
	};

	var getCookie = function () {
		var showContent = false;
		var cookie = $.cookie(_cookieName);
		if (cookie !== null) {
			if (cookie.content === "hidden") {
				showContent = true;
			}
		}
		return showContent;
	};

	//public
	return {
		init: function (params) {
			_contents1 = params.contents1 || "";
			_contents2 = params.contents2 || "";
			_showhide = params.showhide || "";
			_iTimer = params.timeOut * 1000 || 10000;
			_cookieName = params.cookieName || "contentSlider";

			setupSlider();
		}
	};
} ();

/*
IE Rounded Corners
*/
mjjames.controls.roundedCorners = function () {

	var cornersHTML = '<span class="tl corner">&nbsp;</span> <span class="tr corner">&nbsp;</span> <span class="bl corner">&nbsp;</span> <span class="br corner">&nbsp;</span>';

	var setupCorners = function (container) {
		$(container).append(cornersHTML);
	};

	return {
		init: function (container) {
			setupCorners(container);
		}
	};
} ();


/* error handling */

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

$(function () {
	var resizeParams = {
		column1: "div.left",
		column2: "div.main"
	};
	mjjames.helpers.columnfixer.init(resizeParams);

	mjjames.controls.callbackForm.init();
});


/* Have to load this on load due to the CurvyCorners in IE messing around with everything */
$(window).load(function () {
    var articleParams = {
        container: "div.articles",
        showhideelement: "h3.year",
        showhidecontainer: "ul.sideListing"
    };

    mjjames.controls.articleGrouping.init(articleParams);

    var resizeParams = {
        column1: "div.left",
        column2: "div.main"
    };
    mjjames.helpers.columnfixer.init(resizeParams);

    mjjames.controls.callbackForm.init();
});
/* error handling */

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

