/// <summary>
/// Array.prototype.inArray
/// </summary>
Array.prototype.inArray = function(value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
	var i;

	for (i = 0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}

	return false;
};

var famap = {};

famap.animateProductBoughtPopup = function() {
	$('#productBoughtPopup').animate({ opacity: 1.0 }, 5000).fadeOut(1000);
};

famap.slideProductCommentAddContainer = function() {
	if ($("div#productCommentAddContainer").is(":hidden")) {
		$("div#productCommentAddContainer").slideDown("slow");
	} else {
		$("div#productCommentAddContainer").slideUp("slow");
	}
};

// summary
// Saving selected tab before postback
// /summary
// params
// containerSelector: (string) selector of element that contains the tabs
// hiddenFieldName: (string) name of asp:HiddenField 
// /params
famap.SaveSelectedTab = function(hiddenFieldName, containerSelector) {
	// get all tab links
	var links = $(containerSelector + ' ul li a');

	links.each(function(i, item) {
		$(item).click(function() {
			//foreach tab link - on click save number of selected tab in hidden field
			var elem = i + 1;
			$("input[id='" + hiddenFieldName + "']").val(elem);
		});
	});
};

// summary
// Setting currently sellected tab after postback
// /summary
// params
// containerSelector: (string) selector of element that contains the tabs
// hiddenFieldName: (string) name of asp:HiddenField 
// /params
famap.SetSelectedTab = function(hiddenFieldName, containerSelector) {
	// get list of tabs
	var listItems = $('#searchnavitem-tabnav li');
	// get from hidden container number of selected tab 
	var selectedTabNumber = parseInt($("input[id='" + hiddenFieldName + "']").attr("value"));

    // when no value found set default value, first tab selected
	if (isNaN(selectedTabNumber) || !selectedTabNumber)	{
		selectedTabNumber = 1;
	}

	listItems.each(function(i, item) {
		var currentElem = i + 1;
		var $e = $(containerSelector + ' ' + containerSelector + currentElem);
		// check number for each tab
		if (currentElem === selectedTabNumber) {
			// if tab is selected set 'selected' class for header and content
			$(item).addClass('selected');
			//$e.css('display: block;');
			$e.addClass('selected');			
		} else {
			// set default class for header and content
			$(item).removeClass('selected');
			//$e.css('display: none;');
			$e.removeClass('selected');
		}
	});
};

// summary
// initTabNavigation
// Initalizes tabs
// /summary
// params
// containerSelector: (string) selector of element that contains the tabs
// contentSelector: (string) selector that matches all tab elements
// contentIdPrefix: (string) id prefix of respective tab element, e.g. an given an id of "foo1" the id prefix is "foo"
// headingSelector: (string) selector that matches the heading inside a tab
// showHeadings: (bool) show/hide the heading elements inside the tab elements
// /params
famap.initTabNavigation = function(containerSelector, contentSelector, contentIdPrefix, headingSelector, showHeadings) {
	var hasSelected = false;
	var $list = $(document.createElement('ul')); // The navigation list.
	var navigationElementId = contentIdPrefix + '-tabnav';

	$list.attr('id', navigationElementId);
	$list.addClass('clearbox tabnav');

	$(contentSelector).each(function(j) {
		var selected = $(this).hasClass('selected');
		var currentContentId = $(this).attr("id");

		$(this).find(headingSelector).each(function(i) {
			var $item = $(document.createElement('li'));
			var $link = $(document.createElement('a'));
			var $span = $(document.createElement('span'));
			var $span2 = $(document.createElement('span'));

			var text = $(this).attr('title'); // Get the title attribute from the heading element.

			// If the title attribute is missing, get the text content.
			if (text === '') {
				text = $(this).text();
			}

			// Add id attribute to li element
			if (currentContentId.match(/\d{1,}\.{0,}\d{0,}/)) {
				$item.attr('id', navigationElementId + currentContentId.match(/\d{1,}\.{0,}\d{0,}/));
			}
			if (selected) {
				$item.addClass('selected');
			}

			$span.text(text);
			$link.attr('href', '#' + currentContentId);

			// Bind a function to each of the a elements click event.
			$link.bind('click', { currentContentId: currentContentId }, function(e) {
				$(contentSelector).hide(); // Hide all content elements.
				$('#' + e.data.currentContentId).show(); // Show the content element that corresponds to the clicked a element.
				$('#' + navigationElementId + ' > li').removeClass('selected'); // Remove the 'selected' class from all of the navigation links.
				$(this).parent(0).addClass('selected'); // And add it to the one that was clicked.
				return false;
			});

			$span2.append($span);
			$link.append($span2);
			$item.append($link);
			$list.append($item);

			if (!showHeadings) {
				// Hide the actual heading element within the content element.
				// Since hide() fails in Safari, we do css instead...
				//	see http://dev.jquery.com/ticket/3038
				//$(this).hide();
				$(this).css('display', 'none');
			}
		});

		// Show or hide the content element.
		if (selected) {
			hasSelected = true;
			$(this).show();
		} else {
			$(this).hide();
		}
	});

	$(containerSelector).prepend($list);

	if (!hasSelected) { // We found no element with class 'selected', so we show the first tab.
		$list.find('ul.tabnav > li:first').addClass('selected'); // And add the class selected to that tab.
		$(contentSelector + ':first').show(); // show the matching element
		hasSelected = true;
	}
};

/// <summary>
/// http://beardscratchers.com/journal/fixing-the-enter-keypress-event-in-aspnet-with-jquery
/// </summary>
famap.KeyListener =
{
	init: function() {
		var CLASSNAME_PREFIX = 'defaultsubmit-';
		var CLASSNAME_PREFIX_LENGTH = 14;

		$('body').bind('keypress', function(e) {
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			var target = e.target.tagName.toLowerCase();

			if (key === 13 && target === 'input') {
				e.preventDefault();
				var parentFieldset = $(e.target).parents('fieldset');
				parentFieldset = parentFieldset.filter('[class^=' + CLASSNAME_PREFIX + ']').eq(0);

				if (parentFieldset.length > 0) {
					var classnames = parentFieldset.attr('class').split(' ');

					for (var i = 0; i < classnames.length; i++) {
						if (classnames[i].substring(0, CLASSNAME_PREFIX_LENGTH) === CLASSNAME_PREFIX) {
							var button = $('a.' + classnames[i] + ', button.' + classnames[i], $(this)).eq(0);

							if (button.length > 0) {
								if (typeof (button.get(0).onclick) === 'function') {
									button.trigger('click');
								} else if (button.attr('href')) {
									window.location = button.attr('href');
								} else {
									button.trigger('click');
								}
							}

							break;
						}
					}
				}
			}
		});
	}
};

/// <summary>
/// Initialize links in bannerads lists. Links with rel attribute set to external 
/// will open a new window.
/// </summary>
famap.initBannerAds = function() {
	$('ul.bannerads a[rel=external]').click(function() {
		window.open($(this).attr('href'));
		return false;
	});
};

/// <summary>
/// Display an animated login error message
/// </summary>
famap.displayLoginError = function() {
	$('#fw-loginerror').animate({ backgroundColor: '#dd0000', color: '#000' }, 0).animate({ backgroundColor: 'transparent', color: '#dd0000' }, 3000);
};

/// <summary>
/// Validate a password, make sure it doesn't include illegal characters.
/// </summary>
famap.passwordValidate = function(source, args) {
	// If the input element we're validating is disabled we skip the validation.
	if ($('#' + source.controltovalidate).is(':disabled')) {
		args.IsValid = true;
		return;
	}

	var illegalCharacters = ["<", ">"];
	var password = args.Value;

	for (var i = 0, s; s = illegalCharacters[i]; i++) {
		if (password.indexOf(s) !== -1) {
			args.IsValid = false;
			return;
		}
	}

	args.IsValid = true;
};

/// <summary>
/// Tests the supplied birthdate against a defined format.
/// </summary>
famap.validateBirthdate = function(source, args) {
	args.IsValid = new RegExp(/^[12]\d{3}-?[01][0-9]-?[0-3][0-9]$/).test(args.Value.replace(/\s/g, ''));
};

/// <summary>
/// Creates a cornerbox with rounded corners
/// </summary>
famap.cornerbox = function(elementSelector) {
	var $elementSelector = $(elementSelector);
	var $c1 = $(document.createElement('div'));
	var $c2 = $(document.createElement('div'));
	var $c3 = $(document.createElement('div'));
	var $c4 = $(document.createElement('div'));
	$c1.attr('class', 'boxcorner boxcorner1');
	$c2.attr('class', 'boxcorner boxcorner2');
	$c3.attr('class', 'boxcorner boxcorner3');
	$c4.attr('class', 'boxcorner boxcorner4');
	$elementSelector.addClass('cornerbox');
	$elementSelector.append($c1);
	$elementSelector.append($c2);
	$elementSelector.append($c3);
	$elementSelector.append($c4);
};

famap.initCornerBoxes = function() {
	famap.cornerbox('.cornerbox');
};

/// <summary>
/// Toggles default text for input, e.g. 'Enter your username'
/// </summary>
famap.toggleDefaultTextForInput = function(inputId, defaultText) {

	// Get input element
	var $textInput = $('input#' + inputId);

	// Set default text value for input
	$textInput.val(defaultText);

	// On text input focus, empty value
	$textInput.focus(function() {
		if ($(this).val() === defaultText) {
			$(this).val('');
		}
	});

	// On text input blur, set default text if empty
	$textInput.blur(function() {
		if ($(this).val() === '') {
			$(this).val(defaultText);
		}
	});
};

/// <summary>
/// Toggles default text for input, e.g. 'Enter your password'
/// </summary>
famap.toggleDefaultTextForPasswordInput = function(inputId, defaultText) {

	// Get password input element
	var $passwordInput = $('input#' + inputId);

	// Hide password input
	$passwordInput.hide();

	// Create text input for showing default text
	var $passwordTemporaryInput = $(document.createElement('input'));
	$passwordTemporaryInput.attr("type", "text");
	$passwordTemporaryInput.attr("class", $passwordInput.attr('class'));
	$passwordTemporaryInput.attr("id", inputId + '-defaultvalue');
	$passwordTemporaryInput.val(defaultText);

	// On text input focus, show password input
	$passwordTemporaryInput.focus(function() {
		$(this).hide();
		$passwordInput.show();
		$passwordInput.focus();
	});

	// Add text input
	$passwordInput.after($passwordTemporaryInput);

	// On password input blur, show text input if no text entered
	$passwordInput.blur(function() {
		if ($(this).val() === '') {
			$(this).hide();
			$passwordTemporaryInput.show();
		}
	});
};

famap.templates = {
	checkorder: (function() {
		var that = {};
		
		var initDeliverySelector = function() {
			// Somehow this is needed since some browsers don't pre-select radiobuttons.
			$('#DeliveryMethodSelector input[checked=checked]').attr('checked', 'checked');
		};

		that.init = function(params) {
			var $smsNotificationButton = $('#' + params.smsButtonID);
			var $mailNotificationButton = $('#' + params.mailButtonID);
			var $smsNotificationText = $('#' + params.smsTextID);

			// Disable/enable phone text field according to the choice of delivery notification.
			if ($smsNotificationButton.length > 0 && $mailNotificationButton.length > 0 && $smsNotificationText.length > 0) {
				var setNotification = function() {
					$smsNotificationText.attr('disabled', !$smsNotificationButton.is(':checked'));
				};

				$smsNotificationButton.click(setNotification);
				$mailNotificationButton.click(setNotification);
				setNotification();
			}
			
			initDeliverySelector();
		};

		return that;
	})()
};

famap.initPrint = function(params) {
	var $li = $(document.createElement('li'));
	var $a = $(document.createElement('a'));
	$li.attr('id', params.nodeId);
	$a.attr('href', '#');
	$a.text(params.nodeText);
	$a.click(function()	{
		window.print();
		return false;
	});
	$li.append($a);
	$('#' + params.parentNodeId).append($li);
};

// famap.init, called from the constructor on $(document).ready().
famap.init = function() {
	famap.initCornerBoxes();
	famap.initBannerAds();
	famap.KeyListener.init();
};

// famap constructor.
(function() {
	$(document).ready(function() {
		famap.init();
	});
})();

