﻿/*  ==  MODEL  ==============================================================  */

/**
* Runs after all synchronous JavaScript in the common has run
*/
function ewAfterCommon() {
	padThumbnailImages();
	removeHeightsFromSubPageBriefs();
	matchSubPagesTitleHeights();
}


/**
* Adds padding to thumbnail images
*/
function padThumbnailImages() {
	// Find the maximum image height
	var maxHeight = 0;
	$('.ProductList .listItem img').each(function () {
		if ($(this).height() > maxHeight) {
			maxHeight = $(this).height();
		}
	});

	// Loop through all images, and pad any smaller than the max
	$('.ProductList .listItem img').each(function () {
		var height = $(this).height();
		if (height < maxHeight) {
			var difference = maxHeight - height;
			var paddingTop = Math.round(difference / 2);
			var paddingBottom = difference - paddingTop;
			$(this).css({ paddingTop: paddingTop, paddingBottom: paddingBottom });
		}
	});
}

/**
* Removes height set on subpage briefs
*/
function removeHeightsFromSubPageBriefs() {
	$('.SubPages .listItem, .SubPages .lIinner').css({ height: 'auto' });
}

/**
* Adds padding to subpage brief titles
*/
function matchSubPagesTitleHeights() {
	if ($('.SubPages .listItem .title').exists()) {
		// Find the maximum title height
		var maxHeight = 0;
		$('.SubPages .listItem .title').each(function () {
			var titleHeight = $(this).height();
			if (titleHeight > maxHeight) {
				maxHeight = titleHeight;
			}
		});

		$('.SubPages .listItem .title').each(function () {
			var title = $(this);
			var titleHeight = title.height();

			if (titleHeight < maxHeight) {
				var difference = maxHeight - titleHeight;
				var paddingTop = Math.round(difference / 2);
				var paddingBottom = difference - paddingTop;
				title.css({
					paddingTop: parseInt(title.css('paddingTop')) + paddingTop,
					paddingBottom: parseInt(title.css('paddingBottom')) + paddingBottom
				});
			};
		});
	}
}

$(document).ready(function () {

	if ($('#mainAdminMenu').exists() == false) {
		$('body').addClass('js');

		galleryThumbList();
	}

	// initialise homepage promotion gallery
	promotionList();

	if ($('#ReviewForm').find('.alert').exists() || $('#ReviewForm .sentMessage').exists()) {
		openModal('#ReviewForm');
	}


	$('a[href="#ReviewForm"]').addClass('modalLink');
	//$('.modalContent h2').addClass('modal');\


	/*
	* SimpleModal Basic Modal Dialog
	* http://www.ericmmartin.com/projects/simplemodal/
	* http://code.google.com/p/simplemodal/
	*
	* Copyright (c) 2010 Eric Martin - http://ericmmartin.com
	*
	* Licensed under the MIT license:
	*   http://www.opensource.org/licenses/mit-license.php
	*
	* Revision: $Id: basic.js 243 2010-03-15 14:23:14Z emartin24 $
	*
	*/

	$('.modalLink').click(function (e) {
		e.preventDefault();

		// open relevant content in basic modal window
		openModal($(this).attr('href'));
		//_gaq.push(['_trackPageview', '/ReviewForm']);
		//return false;

	});

	reviewToggle();

});


function galleryThumbList() {
	// Can't kill this function just yet :(
	//return;

	// setup for .GalleryImageList
	if ($('.thumbList').exists() == true) {

		// link hover hide and show
		$('.GalleryImageList .active').css('display', 'block');
		var gallery = $('.GalleryImageList');
		var imgLarge = $('.lightbox.active');

		centreItem(gallery, imgLarge);

		//        add indicator arrow graphic
		//        $('<span id="linkArrow"></span>').appendTo('#linkNav');
		//        linkArrowPos();

		// Create and setup background images for fade in and out
		/*$('.thumbList a').each(function () {

		var itemId = $(this).attr('id').replace(/tn/g, 'det');
		var itemImgName = $(this).attr('rel');

		//            $('<div id="homeBg' + itemId + '" class="homeBg"></div>').appendTo('#main');
		//            $('#homeBg' + itemId).css('background-image', 'url(' + itemImgName + ')');
		//            $('.homeBg:first').show();
		});*/

		/*
		$('.thumbList a').click(function (e) {
			e.preventDefault();
			var gallery = $(this).parents('.GalleryImageList');
			var imgLarge = gallery.find('.lightbox');
			var itemId = $(this).attr('id').replace(/tn/g, 'det');
			//          var linkOffset = $(this).offset().left;
			//          var linkWidth = ($(this).width() + 10) / 2;

			if (!$('#' + itemId).is(':visible')) {
				// fade all large images out
				imgLarge.each(function () {
					$(this).fadeOut().removeClass('active');
				});
				//                $('.homeBg').each(function () {
				//                    $(this).fadeOut()
				//                });

				// locate the relevant large image and show
				$('#' + itemId).addClass('active').fadeIn();

				//              $('#homeBg' + itemId).fadeIn();

				//              linkArrowPos(linkOffset, linkWidth);

				//centre the large image in the gallery space
				centreItem(gallery, $('#' + itemId));
			}
		});
		*/

		// set link href to use the title attribute
		//        $('#linkNav a').each(function () {
		//            $(this).attr('href', $(this).attr('title'));
		//        });
	}
}

function centreItem(container, item) {

	var containerWidth = container.width();

	item.each(function () {
		var itemWidth = $(this).width();
		var offset = (containerWidth - itemWidth) / 2;

		item.css('left', offset + 'px');
	});
}

function linkArrowPos(offset, width) {

	var navOffset = $('#linkNav').offset().left;
	var linkNavOffset = offset;
	var linkNavWidth = width;
	var arrowWidth = $('#linkArrow').width() / 2;

	if (linkNavOffset == null) {
		linkNavOffset = $('#linkNav a:first').offset().left;
	}
	if (linkNavWidth == null) {
		linkNavWidth = ($('#linkNav a:first').width() + 10) / 2;
	}

	$('#linkArrow').animate({ left: linkNavOffset - navOffset - arrowWidth + linkNavWidth }, 200);
}

function menuPos(menu, position) {

	var parentWidth = $(menu).parent().width();
	var menuWidth = $(menu).width();

	if (position == 'right') {
		var pos = '1';
	} else if (position == 'centre') {
		var pos = '2';
	}
	$(menu).css('padding-left', (parentWidth - menuWidth) / pos)
}

function openModal(content) {
	$(content).modal({
		maxWidth: 460,
		minWidth: 230,
		maxHeight: 420,
		minHeight: 250,
		onClose: function (dialog) {
			dialog.data.fadeOut('400', function () {
				dialog.container.slideUp('400', function () {
					dialog.overlay.fadeOut('400', function () {
						$.modal.close(); // must call this!
					});
				});
			});
		},
		onOpen: function (dialog) {
			dialog.overlay.fadeIn('400', function () {
				dialog.container.slideDown('400', function () {
					dialog.data.fadeIn('400');
				});
			});
		},
		opacity: 80,
		overlayCss: { backgroundColor: "#fff" },
		overlayClose: true
	});
}

function promotionList() {
	// setup ad gallery
	if ($('.ad-gallery').exists()) {

		var galleries = $('.ad-gallery').adGallery();
		$('#switch-effect').change(
        function () {
        	galleries[0].settings.effect = $(this).val();
        	return false;
        });

		$('#toggle-slideshow').click(function () {
			galleries[0].slideshow.toggle();
			return false;
		});
	}
}

function reviewToggle() {

	// target all review lists marked with a group class of 'reviews'
	var reviews = $('.contentInner.reviews');
	var review = $('.hreview');
	var count = $('.hreview').length;

	// add hide/show button below review list
	if (count > 0) {
		$('<a href="#" class="principle">Show all reviews</a>').appendTo(reviews);
	}

	var toggleButton = $('.reviews .principle');

	// add a class to differentiate the first item in the list
	$('.hreview:first').addClass('first');

	toggleButton.click(function (e) {
		e.preventDefault();
		var button = $(this);
		var countVisible = $('.hreview:visible').length;

		if (countVisible < 2) {
			review.slideDown(function () {
				button.html('Hide all reviews');
			});
		} else {
			review.not('.first').slideUp(function () {
				button.html('Show all reviews');
			});
		}
	});
}

/*
* 
* ImageScroller - a Image Horizental Scroll Viewer 
* Version 0.1
* @requires jQuery v1.2.1
* 
* Copyright (c) 2007 Luan
* Email verycss-ok@yahoo.com.cn 
* 
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* 
* Example:
*   #viewer {height:100px; width:300px; clear:both; overflow:hidden; border:3px solid #e5e5e5;}
*   #viewerFrame {width:505px; clear:both; padding:0;}
*   #viewer img {width:90px; height:90px; margin:5px; display:inline; border:0;}
*   #viewer a {display:block; float:left; width:100px; height:100px;}
*   <script type="text/javascript">
*   $(function(){
*   	$("#viewer").imageScroller({
*   	next:"btn1",
*   	prev:"btn2",
*   	frame:"viewerFrame",
*   	width:100, 
*   	child:"a",
*   	auto:true
*   	});	 
*   });
*   </script>
*   <div id="viewer"><div id="viewerFrame">
*   <a href=""><img src="pre1.jpg"></a>
*   <a href=""><img src="pre2.jpg"></a>
*   <a href=""><img src="pre3.jpg"></a>
*   <a href=""><img src="pre4.jpg"></a>
*   <a href=""><img src="pre5.jpg"></a>
*   </div></div>
*   <span id="btn1">prev</span><br/><span id="btn2">next</span>   
*/

$.fn.imageScroller = function (params) {
	var p = params || {
		next: "buttonNext",
		prev: "buttonPrev",
		frame: "viewerFrame",
		width: 100,
		child: "a",
		auto: false
	};
	var _btnNext = $("#" + p.next);
	var _btnPrev = $("#" + p.prev);
	var _imgFrame = $("#" + p.frame);
	var _width = p.width;
	var _child = p.child;
	var _auto = p.auto;
	var _itv;

	var turnLeft = function () {
		_btnPrev.unbind("click", turnLeft);
		if (_auto) autoStop();
		_imgFrame.animate({ marginLeft: -_width }, 'fast', '', function () {
			_imgFrame.find(_child + ":first").appendTo(_imgFrame);
			_imgFrame.css("marginLeft", 0);
			_btnPrev.bind("click", turnLeft);
			if (_auto) autoPlay();
		});
	};
	var active;
	var turnRight = function () {
		_btnNext.unbind("click", turnRight);
		if (_auto) autoStop();

		// [eonic 2011-06-16] additional script to show hide large version of context thumbnail
		_imgFrame.find(_child).removeAttr('class');
		$('.lightbox').fadeOut(400);
		// [eonic end]

		_imgFrame.find(_child + ":last").clone().show().prependTo(_imgFrame)

		// [eonic 2011-06-16] additional script to add active class
        .addClass('active');
		var activeLarge = _imgFrame.find(_child + ":first").attr('id').replace(/tn/g, 'det');
		$('#' + activeLarge).fadeIn(400);
		// [eonic end]

		_imgFrame.css("marginLeft", -_width);
		_imgFrame.animate({ marginLeft: 0 }, 'fast', '', function () {
			_imgFrame.find(_child + ":last").remove();
			_btnNext.bind("click", turnRight);
			if (_auto) autoPlay();
		});
	};

	_btnNext.css("cursor", "hand").click(turnRight);
	_btnPrev.css("cursor", "hand").click(turnLeft);

	var autoPlay = function () {
		_itv = window.setInterval(turnRight, 3000);
	};
	var autoStop = function () {
		window.clearInterval(_itv);
	};
	if (_auto) autoPlay();
};

/**
 * This is sketchy, I know, but I'm getting desperate and Cloud Zoom has no callbacks!!
 */
/*
$(function () {
	setInterval(function () {
		var wrap = $('#wrap'),
			img = wrap.find('img');
		wrap.width(img.width()).css({ margin: '0 auto' });
	}, 3);
});
*/

/*
AnythingZoomer v1.1 minified
Original by Chris Coyier: http://css-tricks.com
Get the latest version: https://github.com/Mottie/AnythingZoomer
*/
(function (b) { b.anythingZoomer = function (e, g) { var f, c, a = this; a.$wrap = b(e).addClass("az-wrap").wrapInner('<span class="az-wrap-inner"/>'); a.wrap = e; a.$wrap.data("zoomer", a); a.init = function () { a.options = c = b.extend({}, b.anythingZoomer.defaultOptions, g); a.state = !0; a.$small = a.$wrap.find("." + c.smallArea); a.$large = a.$wrap.find("." + c.largeArea); if (c.clone) f = a.$small.clone().removeClass(c.smallArea).addClass(c.largeArea), a.$large.length ? a.$large.html(f.html()) : (a.$small.after(f), a.$large = a.$wrap.find("." + c.largeArea)); a.largeDim = [a.$large.wrapInner('<span class="az-large-inner"/>').find(".az-large-inner").width(), a.$large.height()]; a.smallDim = [a.$small.wrapInner('<span class="az-small-inner"/>').find(".az-small-inner").width(), a.$small.height()]; a.$large.addClass("az-large").wrap('<div class="az-zoom"></div>'); a.$small.addClass("az-small"); a.$zoom = a.$wrap.find(".az-zoom"); a.ratio = [a.smallDim[0] === 0 ? 1 : a.largeDim[0] / a.smallDim[0], a.smallDim[1] === 0 ? 1 : a.largeDim[1] / a.smallDim[1]]; a.$inner = a.$wrap.find(".az-wrap-inner").css({ width: a.smallDim[0], height: a.smallDim[1] }); a.zoomDim = a.last = [a.$zoom.width(), a.$zoom.height()]; a.smallOffset = [a.$small.offset().left - a.$inner.position().left, a.$small.offset().top]; a.$inner.bind("mouseenter.anythingZoomer", function () { a.state && a.$zoom.fadeIn(100) }).bind("mouseleave.anythingZoomer", function () { if (a.state) a.timer = setTimeout(function () { a.$zoom.is(".az-windowed") && a.hideZoom() }, 200) }).bind("mousemove.anythingZoomer", function (d) { a.state && (clearTimeout(a.timer), a.zoomAt(d.pageX - a.smallOffset[0], d.pageY - a.smallOffset[1])) }).bind(c.switchEvent + (c.switchEvent !== "" ? ".anythingZoomer" : ""), function () { a.state ? a.showLarge() : a.showSmall() }); a.showSmall() }; a.showSmall = function () { a.state = !0; a.$small.show(); a.$zoom.removeClass("az-expanded").addClass("az-windowed az-zoom").css({ width: a.zoomDim[0], height: a.zoomDim[1] }); a.$inner.css({ width: a.smallDim[0], height: a.smallDim[1] }) }; a.showLarge = function () { a.state = !1; a.$small.hide(); a.$zoom.fadeIn(100).addClass("az-expanded").removeClass("az-windowed az-zoom").css({ height: "auto", width: "auto" }); a.$inner.css({ width: a.largeDim[0], height: a.largeDim[1] }); a.$large.css({ left: 0, top: 0, width: a.largeDim[0], height: a.largeDim[1] }) }; a.setTarget = function (d, c, k) { var e = 0, h = 0; a.$zoom.is(".az-windowed") || a.showSmall(); !isNaN(d) && !isNaN(c) ? (e = parseInt(d, 10), h = parseInt(c, 10)) : typeof d === "string" && b(d).length && (d = b(d), e = d.position().left + d.width() / 2 + (c ? c[0] || 0 : 0), h = d.position().top + d.height() / 2 + (c ? c[1] || 0 : 0)); a.zoomAt(e, h, k) }; a.zoomAt = function (d, e, b) { var f = (b ? b[0] || 0 : 0) || a.last[0], b = (b ? b[1] || b[0] || 0 : 0) || a.last[1], h = f / 2, g = b / 2, i = c.edge || h * 0.66, j = c.edge || g * 0.66; a.last = [f, b]; d < -i || d > a.smallDim[0] + i || e < -j || e > a.smallDim[1] + j ? a.hideZoom() : (a.$zoom.fadeIn(100), a.$zoom.css({ left: d - h, top: e - g, width: f, height: b }), a.$large.css({ left: -(d - h / 2) * a.ratio[0], top: -(e - g / 2) * a.ratio[1] })) }; a.hideZoom = function () { a.last = a.zoomDim; a.$zoom.fadeOut(100) }; a.init() }; b.anythingZoomer.defaultOptions = { smallArea: "small", largeArea: "large", clone: !1, switchEvent: "dblclick", edge: 30 }; b.fn.anythingZoomer = function (e, g, f, c) { return this.each(function () { var a = b(this).data("zoomer"); (typeof e).match("object|undefined") && !a ? new b.anythingZoomer(this, e) : (typeof e === "string" || !isNaN(e) && !isNaN(g)) && a.setTarget(e, g, f, c) }) }; b.fn.getAnythingZoomer = function () { return this.data("zoomer") } })(jQuery);
