$().ready(function () {

	//Add title for warranty icons
	$('.warranty-info img[alt], .product-links img[alt]').each(function () {
		$(this).attr('title', $(this).attr('alt'));
	});

	// hide the elements we don't need if we have javascript enabled.
	$(".no-script-only").hide();

	// make a '.clickable' element activate the first link it contains (when clicking anywhere on it)
	$(".clickable").biggerlink(); // requires: jquery.biggerlink.pack.js

	// search
	$(".product-code-input").focus(function () {
		if (this.value == "Product code/name")
			this.value = "";
	});
	$(".product-code-input").blur(function () {
		if (this.value == "")
			this.value = "Product code/name";
	});

	// my list stuff
	//if(!($.browser.msie && $.browser.version == 8)) // wierd bug which only affects IE8 on production server only.
	//$("#my-list").fadeTo(0, 0.7);
	
	DynamicWebSite.Framework.MyListAjax.GetMyListInfo(UpdateMyListInfo_CallBack)
	$("a.add-to-list").click(function () {
		var id = getIdFromClass($(this).parents(".product-info").attr("class"));
		//$(".indicator").text("working...");
		//DynamicWebSite.Framework.MyListAjax.ToggleOnMyList(id, ToggleOnMyList_CallBack);
		DynamicWebSite.Framework.MyListAjax.AppendToMyList(id, AppendToMyList_CallBack);
		return false;
	});

	SetUniqueRandomIds();

	$('.myList-feature').each(function () {
		if ($(this).find('.promo-price')[0]) {
			$(this).find('.promo-price').css({ 'min-height': '72px' });
			$(this).find('.myList-feature-details').css({ 'padding-bottom': '130px' });
		}
	});

	$("a.remove-from-list").click(function () {
		var features = $('.myList-feature');
		//Remove arrows (if top or bottom item was clicked)
		if ($(this).parents('.myList-feature').is(features.find(':first')))
			$(this).next('.myList-feature').find('.move-product-up').hide();
		if ($(this).parents('.myList-feature').is(features.find(':last')))
			$(this).prev('.myList-feature').find('.move-product-down').hide();
		//var id = getIdFromClass($(this).parents(".product-info").attr("class"));
		//$(".indicator").text("removing...");
		//DynamicWebSite.Framework.MyListAjax.RemoveFromMyList(id, RemoveFromMyList_CallBack);
		SetProductIndexes("a.remove-from-list");
		DynamicWebSite.Framework.MyListAjax.RemoveFromMyListByIndex($(this).attr('rel'));
		$(this).parents(".product-info").remove();
		return false;
	});

	$("a.move-product-up").click(function () {
		SetProductIndexes("a.move-product-up");
		if (parseInt($(this).attr('rel')) != 0) {
			MoveListItem(parseInt($(this).attr('rel')), -1);
			DynamicWebSite.Framework.MyListAjax.MoveItemUp($(this).attr('rel'));
		}
		return false;
	});
	$("a.move-product-down").click(function () {
		SetProductIndexes("a.move-product-down");
		if (parseInt($(this).attr('rel')) != $("a.move-product-down").length - 1) {
			MoveListItem(parseInt($(this).attr('rel')), 1);
			DynamicWebSite.Framework.MyListAjax.MoveItemDown($(this).attr('rel'));
		}
		return false;
	});

	$('a.move-product-up, a.move-product-down').show();
	$('a.move-product-up:first, a.move-product-down:last').hide();
	// initialise Google Tracking for File Downloads
	googleAnalyticsFileTracker();
});

function SetProductIndexes(selector) {
	var $buttons = $(selector);
	for (var i=0; i < $buttons.length; i++) {
		$buttons.eq(i).attr('rel', i);
	}
}

function SetUniqueRandomIds() {
	var $list = $('.myList-left-col .myList-feature');
	for (var i=0; i < $list.length; i++) {
		$list.eq(i).attr('id', 'item-' + Math.round(Math.random() * i * 999999999));
	}
}

function MoveListItem(index, amount){

	var $list = $('.myList-left-col .myList-feature');
	var count = $list.length;
	var $item = $list.eq(index);
	var newindex = index + amount;
	var sel = '#' + $list.eq(newindex).attr('id');

	if(parseInt(amount) > 0) {
		$item.clone(true).insertAfter($(sel));
		$item.empty().remove();
	} else {
		$item.clone(true).insertBefore($(sel));
		$item.empty().remove();
	}

	$('a.move-product-up, a.move-product-down').show();
	$('a.move-product-up:first, a.move-product-down:last').hide();
}


function getIdFromClass(fullclass) {
	var classes = fullclass.split(" ");
	var idclass="";
	for(var i=0; i<classes.length;i++)
	{
		if(classes[i].indexOf("id-") != -1)
		{
			idclass=classes[i];
			break;
		}
	}
	var id = idclass.replace("id-","");
	return id;
}


function UpdateMyListInfo_CallBack(response) {
	if (response.error) {
		alert(response.error.Message);
	}
	else {
		var count = response.value.IDs.length;
		$(".indicator").text("(" + count + ")");
		for (var i = 0; i < response.value.IDs.length; i++) {
			$(".id-" + response.value.IDs[i] + " a.add-to-list").text("added to list").addClass("selected");
		}
	}
}

function removeFromMyList(id)
{

}

function RemoveFromMyList_CallBack(response)
{
   if(response.error)
   {
		alert(response.error.Message);
   }
   else
   {
		$(".id-"+response.request.args.EntityID).fadeOut();
		$(".indicator").text("removed");
		
		DynamicWebSite.Framework.MyListAjax.GetMyListInfo(UpdateMyListInfo_CallBack);
		
   }   
}

function ToggleOnMyList_CallBack(response)
{
   if(response.error)
   {
		alert(response.error.Message);
   }
   else
   {
		if(response.value == true)
		{
			$(".id-"+response.request.args.EntityID+" a.add-to-list").text("added to list").addClass("selected");
			$(".indicator").text("added");
		}
		else
		{
			$(".id-"+response.request.args.EntityID+" a.add-to-list").text("add to list").removeClass("selected");
			$(".indicator").text("removed");
		}
		DynamicWebSite.Framework.MyListAjax.GetMyListInfo(UpdateMyListInfo_CallBack);
   }
}

function AppendToMyList_CallBack(response) {
	if(response.error)
	{
		alert(response.error.Message);
	}
	else
	{
		$(".id-"+response.request.args.EntityID+" a.add-to-list").text("added to list").addClass("selected");
	}
	DynamicWebSite.Framework.MyListAjax.GetMyListInfo(UpdateMyListInfo_CallBack);
}

function googleAnalyticsFileTracker() {
	$("a[href$=.pdf],a[href$=.doc],a[href$=.docx],a[href$=.xls],a[href$=.xlsx],a[href$=.ppt],a[href$=.pptx]").click(function() {
		pageTracker._trackPageview($(this).attr("href"));
	});
}

//For use to keep track of click state between Terousel and the AjaxGallery
var ClickState = {
	menuClickActive : false
};

//Author: Pat O'Callaghan : Terabyte (pat@terabyte.co.nz)
//Simple Carousel
(function($) {
   
  $.fn.terousel = function(options) {
	
	$.fn.terousel.defaults = {
	  speed : 1000,
	  easing : "easeInOutExpo",
	  ajaxPage : false
	};

	var opts = $.extend({}, $.fn.terousel.defaults, options);

	return this.each(function(){
		
		var currentLeftPosition = 0,
			$thisContainer = $(this),
			$thisWindow = $thisContainer.find('#scroll-window'),
			thisWindowWidth = $thisWindow.width(),
			$thisList = $thisWindow.find('ul'),
			$previous = $thisContainer.find('#previous'),
			$next = $thisContainer.find('#next'),
			$listLi = $thisList.find('li'),
			itemsPerRow = Math.floor(thisWindowWidth / $listLi.width());
			rowWidth = $listLi.width() * itemsPerRow,
			clickActive = false,
			listWidth = ($listLi.width() * $listLi.size());

		AjaxGallery.init('.gallery-detail');

		//Attach click event to List items if we are reloading the page using Ajax
		$listLi.each(function(index, val){
			if(jQuery.browser.msie && index % 7 === 0) {
				$(this).css("margin-left", "0");
			}
			if(opts.ajaxPage) {
				$(this).click(function(event){
					if(!ClickState.menuClickActive) {  
						ClickState.menuClickActive = true;  
						event.preventDefault();
						var $thisLi = $(this),
							href = $thisLi.find('a').attr("href"),
							$selected = $thisLi.parent().find('li.selected'),
							mask = $selected.find('#mask').empty().remove();
						AjaxGallery.run(href, '.gallery-detail', '.gallery-detail');
						$selected.removeClass('selected');
						$thisLi.addClass("selected");
						$thisLi.append("<div id='mask'>&nbsp;</div>");
					}
				});
			}
		});

		//Attach click event to next and previous buttons
		$.each([$next, $previous],function(){
			if (itemsPerRow >= $listLi.length) {
				$(this).addClass('hidden');
			}
			$(this).click(function(event){
				event.preventDefault();
				var $thisButton = $(this);
				if(!clickActive && !$thisButton.is('.disabled')) {
					clickActive = true;
					$thisButton.addClass('disabled');
					$thisButton.css("cursor", "default");
					slide(this.id);
					clickActive = false;
				}
			});
		});

		//Function to determine whether buttons should be disabled after a slide
		function setButtons(){
			$.each([$previous, $next], function(){
				var $thisButton = $(this);
				currentLeftPosition = getPixelValue($thisList.css("left"));
				if($thisButton.is("#previous.disabled") && currentLeftPosition < 0) {
					$thisButton.removeClass('disabled');
					$thisButton.css("cursor", "pointer");
				} else if ($thisButton.is("#next.disabled") && (currentLeftPosition > listWidth*-1) && 
					(currentLeftPosition <= 0) && currentLeftPosition - rowWidth > listWidth*-1) {
					$thisButton.removeClass('disabled');
					$thisButton.css("cursor", "pointer");
				}
			});
		}

		//Slide the list of items and then determine whether buttons need to be disabled after the slide
		function slide(direction){
			var width = $thisWindow.width(),
				currentLeftPosition = getPixelValue($thisList.css("left")),
				positionToMoveTo = direction === 'previous' ? currentLeftPosition + width : currentLeftPosition - width;
			$thisList.animate({
				left: positionToMoveTo + "px"
			}, opts.speed, opts.easing, function(){
				setButtons();
			});   
		}
		
	});

	//Utility function to take in string pixel value, e.g. "110px", and return number value, e.g. 100
	function getPixelValue(value) {
		return parseInt(value.match(/\-?\d+/));
	}  

  };

})(jQuery);

/** Karl Swedeberg tooltip http://www.learningjquery.com **/
(function($) {
   
	$.fn.tooltip = function(options) {
	
		$.fn.tooltip.defaults = {
	  
		};

		var opts = $.extend({}, $.fn.tooltip.defaults, options);
		$('<div id="tooltip"><div class="arrow">&nbsp;</div></div>').hide().appendTo('body');

		return this.each(function(){
			
			var tipTitle = '';
			$(this).bind('mouseover', function(event) {
				var $link = $(this).find('a');
				if ($link.length) {
					var link = $link[0];
					tipTitle = link.title;
					link.title = '';
					$('#tooltip')
						.css({
							top: event.pageY + 12,
							left: event.pageX + 12
						})
						.html('<div class="arrow">&nbsp;</div><div>' + tipTitle + '</div>')
						.show();
			   }
			}).bind('mouseout', function(event) {
				var $link = $(this).find('a');
				if ($link.length) {
					$link.attr('title', tipTitle);
					$('#tooltip').hide();
				}
			}).bind('mousemove', function(event) {
				if ($(this).find('a').length) {
					$('#tooltip').css({
						top: event.pageY + 12,
						left: event.pageX + 12
					});
				}
			})
		});
	}
})(jQuery);

var AjaxGallery = (function(){

	function init (elemToWrap){
		$(elemToWrap).wrapInner("<div class='ajax-content'></div>");
		$('<div class="loader"><span>Loading content...</span></div>').appendTo(elemToWrap);
	}
	
	/** "Main" method - this is the method that pulls it all together **/
	function run(href, elemToRetrieve, appendTo){
		if($(appendTo).find('.ajax-content').children().size() > 0) {
			removeCurrentContent(elemToRetrieve, function(){
				retrieveNewContent (href, elemToRetrieve, appendTo)
			});
		}
		
	}

	/** Remove the current content and carry out a callback once it's completed **/
	function removeCurrentContent(elem, callback){
		var callbackFired = false,
			ajaxElem = $(elem).find('.ajax-content');

		$(ajaxElem).children().fadeOut(400, function(){
			$(this).empty().remove();
			if(!callbackFired) {
				$(ajaxElem)
					.css("display", "none");
				callbackFired = true;
				AddLoadingScreen(elem);
				callback();
			}
		});
	}

	function AddLoadingScreen(elem, height) {
		$(elem).find('.loader')
			.css("display", "block");
	}

	/** Retrieve the new content using Ajax **/
	function retrieveNewContent (href, elemToRetrieve, appendTo){
		$(appendTo + ' .ajax-content').load(href + ' ' + elemToRetrieve + ' > * ', showContent(appendTo));
	}

	/** Show content **/
	function showContent (elem){
		var ajaxContainer = $(elem + ' .ajax-content');
		ajaxContainer
			.children()
				.hide('fast', function(){
					ajaxContainer.css("display", "block");
				})
				.end()
			.children()
				.fadeIn('fast', function(){
					$(elem).find(' .loader').css("display", "none");
				})
				.end();
		ClickState.menuClickActive = false;
	}

	return {
		init : init,
		run : run
	}

})();

