/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

/// <reference path="jquery-1.3.2-vsdoc.js" />
/*global $, jQuery */

function getResourceText(key) {
	if ($(".jsresources ." + key).length === 0) {
		return "Missing: " + key;
	}

	return $(".jsresources ." + key).text();
}

function getResourceHtml(key) {
	if ($(".jsresources ." + key).length === 0) {
		return "Missing: " + key;
	}

	return $(".jsresources ." + key).html();
}

//depends on getResourceText function
(function($) {
	// Password strength meter
	// This jQuery plugin is written by firas kassem [2007.04.05]
	// Firas Kassem  phiras.wordpress.com || phiras at gmail {dot} com
	// for more information : http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/

	function checkRepetition(pLen, str) {
		var res = "";
		for (var i = 0; i < str.length; i++) {
			var repeated = true;
			for (var j = 0; j < pLen && (j + i + pLen) < str.length; j++) {
				repeated = repeated && (str.charAt(j + i) === str.charAt(j + i + pLen));
			}

			if (j < pLen) {
				repeated = false;
			}

			if (repeated) {
				i += pLen - 1;
				repeated = false;
			} else {
				res += str.charAt(i);
			}
		}
		return res;
	}

	function passwordStrength(password, username) {
		var score = 0;

		//password < 6
		if (password.length < 6) {
			return 'short';
		}

		//password == username
		if (password.toLowerCase() === username.toLowerCase()) {
			return 'weak';
		}

		//password length
		score += password.length * 4;
		score += (checkRepetition(1, password).length - password.length) * 1;
		score += (checkRepetition(2, password).length - password.length) * 1;
		score += (checkRepetition(3, password).length - password.length) * 1;
		score += (checkRepetition(4, password).length - password.length) * 1;

		//password has 3 numbers
		if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {
			score += 5;
		}

		//password has 2 sybols
		if (password.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/)) {
			score += 5;
		}

		//password has Upper and Lower chars
		if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
			score += 10;
		}

		//password has number and chars
		if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {
			score += 15;
		}

		//password has number and symbol
		if (password.match(/([!,@,#,$,%,\^,&,*,?,_,~])/) && password.match(/([0-9])/)) {
			score += 15;
		}

		//password has char and symbol
		if (password.match(/([!,@,#,$,%,\^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)) {
			score += 15;
		}

		//password is just a nubers or chars
		if (password.match(/^\w+$/) || password.match(/^\d+$/)) {
			score -= 10;
		}

		//verifing 0 < score < 100
		if (score < 0) {
			score = 0;
		}
		if (score > 100) {
			score = 100;
		}

		if (score < 34) {
			return 'weak';
		}
		if (score < 68) {
			return 'good';
		}
		return 'strong';
	}

	$.fn.meterPasswordStrength = function(resultElement) {
		var results = {
			'short': getResourceText('PasswordStrength_TooShort'),
			'weak': getResourceText('PasswordStrength_Weak'),
			'good': getResourceText('PasswordStrength_Good'),
			'strong': getResourceText('PasswordStrength_Strong')
		};

		var that = $(this);

		that.keyup(function() {
			var result = passwordStrength(that.val(), '');
			resultElement.html(results[result]).attr('class', 'meterpasswordresult ' + result);
		});

		return that;
	};
})(jQuery);

(function($) {
	// jQuery labelize plugin
	
	$.fn.labelize = function(noValueClass) {

		noValueClass = noValueClass || "noValue";

		return $(this).each(function() {

			$(this).hide();
			var text = $(this).text(); //label text
			var field = $('#' + $(this).attr("for")); //input field the label is for

			if (!field) {
				return; // could not find a field to attach to
			}

			//set the label text, if attribule value has no value yet
			if (field.val() === '' || field.val() === text) {
				field.val(text).addClass("noValue");
			}

			field.focus(function() {
				//on focus clear the default label
				if ($(this).val() === text) {
					$(this).val('').removeClass(noValueClass);
				}
			}).blur(function() {
				//on blur, return the default value if field still empty
				if ($(this).val() === '') {
					$(this).val(text).addClass(noValueClass);
				}
			});

			function emptyDefaultValue() {
				if (!field) {
					return;
				}

				if (field.val() === text) {
					field.val('');
				}
			}

			//remove default values on form submit
			$(this).parents("form").submit(emptyDefaultValue);
			//hack for the asp.net web forms madness
			$('a[href*=__doPostBack]').click(emptyDefaultValue);
		});
	};
})(jQuery);

(function($) {
	// Flash wmode fix
	
	$.fn.flashWmodeFix = function() {
		$(this).append('<param name="wmode" value="transparent"></param>');
		$(this).find('embed').attr('wmode', 'transparent');
		$(this).parent().replaceWith($(this).parent().html());
	};
})(jQuery);

(function($) {
	// Tabbed navigation
	
	$.fn.tabbedNavigation = function() {
		$(this).click(function() {
			//remove selection from tabs
			$(this).parent().parent().children('.selected').removeClass('selected');
			var selectedTab = $(this).parent().attr('class');
			//mark this tab as selected
			$(this).parent().addClass('selected');
			//change the active content
			$(this).parents('.navigation').siblings('.content').children('.selected').show('fast', function() {
				$(this).removeClass('selected');
				$(this).parent().parent().find('.content').children('.' + selectedTab).hide('fast', function() {
					$(this).addClass('selected');
				});
			});
			return false;
		});
	};
})(jQuery);

(function($) {
	// Image bank

	$.fn.imageBank = function(fullWidth, fullHeight, allowCrop, plugin, gallery) {
		$(this).find('a').each(function() {
			if (!gallery) {
				$(this).removeAttr('rel');
			} else {
				$(this).addClass(plugin).attr({ rel: gallery });
			}
			var tnImage = $(this).find('img').attr('src');
			var tnFile = tnImage.match(/\/File\/[\w\-]*/);
			var tnName = tnImage.match(/[\w\-]*.[\w\-]*$/);
			$(this).attr({ href: tnFile + '/Width/' + fullWidth + '/Height/' + fullHeight + '/AllowCrop/' + allowCrop + tnName });
		});
	};
})(jQuery);

(function($) {
	// Carousel

	$.fn.carousel = function(target, amount, direction, animation, easing, wrap, delay) {
		var itemCount = $(target).find('li').length;
		var verticalValue;
		if (direction == 'vertical') {
			verticalValue = true;
		} else {
			verticalValue = false;
		}
		// alert(target + ' ' + amount + ' ' + verticalValue); 
		if (itemCount > amount) {
			if (delay > 0) {
				$(target).jcarousel({
					vertical: verticalValue,
					scroll: amount,
					animation: animation,
					easing: easing,
					wrap: wrap,
					auto: delay,
					initCallback: jCarouselInitCallback
				});
			} else {
				$(target).jcarousel({
					vertical: verticalValue,
					scroll: amount,
					animation: animation,
					easing: easing,
					wrap: wrap
				});
			}
		} else {
			return false;
		};
	};
})(jQuery);

function jCarouselInitCallback(carousel) {
	// jQuery autoscrolling for carousel

	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});

	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});

	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});
};

(function($) {
	// Image viewer

	$.fn.imageViewer = function(previewWidth, previewHeight, fullWidth, fullHeight, gallery) {
		var imageLink = $(this).find('.image a');
		var image = $(this).find('.image img');
		var thumbnailLinks = $(this).find('.thumbnails li a');

		// If gallery variable isn't defined, all rel attributes are removed from link elements 
		if (!gallery) {
			imageLink.removeAttr('rel');
			thumbnailLinks.removeAttr('rel');
		}

		thumbnailLinks.click(function() {
			var tnLink = $(this);
			var tnImage = $(this).attr('href');
			var tnFile = tnImage.match(/\/File\/[\w\-]*/);
			var tnAllowCrop = tnImage.match(/\/AllowCrop\/\w+\//);
			var tnName = tnImage.match(/[\w\-]*.[\w\-]*$/);

			imageLink.attr({ href: tnImage });
			image.attr({ src: tnFile + '/Width/' + previewWidth + '/Height/' + previewHeight + tnAllowCrop + tnName });

			if (gallery) {
				tnLink.parents().find('.thumbnails li a').attr({ rel: gallery });
				tnLink.removeAttr('rel');
			}
			return false;
		});

		for (var i = 0; i < thumbnailLinks.length; i++) {
			if ($(thumbnailLinks[i]).attr('href') == imageLink.attr('href')) {
				$(thumbnailLinks[i]).removeAttr('rel');
			} else {
				return true;
			}
		}
	}
})(jQuery);

(function($) {
	// Custom radio buttons / color selection

	$.fn.colorSelection = function(inputTrigger) {
		var inputs = $(this).find(inputTrigger);

		$(inputs).find('input').hide();

		for (var i = 0; i < inputs.length; i++) {
			if ($(inputs[i]).find('input').is(':checked')) {
				$(inputs[i]).addClass('selected');
			};
		}

		$(inputs).click(function() {
			$(inputs).removeClass('selected');
			$(inputs).find('input').removeAttr('checked');
			$(this).addClass('selected');
			$(inputs).unbind('click');
			$(this).find('input').attr('checked', 'checked').click();
		});
	}
})(jQuery);

function toggleDeliveryAddressVisibility() {
	if ($(".orderUseBillingAddressAsDelivery > input").is(":checked")) {
		$("#deliveryAddress").hide();
	} else {
		$('.orderUseBillingAddressAsDelivery > input').click(function() {
			if ($(".orderUseBillingAddressAsDelivery > input").is(":checked")) {
				$("#deliveryAddress").hide();
			} else {
				$("#deliveryAddress").show();
			}
		});
	}
}

function toggleGreetingSetSendingTimeVisibility() {
	if ($(".greetingSendNow > input").is(":checked")) {
		$("#delayedSendingTime").hide();
	} else {
		$("#delayedSendingTime").show();
	}
}

function toggleSponsorFieldsVisibility() {
	switch ($('.sponsorType > option:selected').val()) {
		case "COMPANY":
			$('#fieldSponsorCompanyName').show();
			$('#fieldSponsorCompanyVATNumber').show();
			$('#fieldSponsorGender').hide();
			$('#fieldSponsorDateOfBirth').hide();
			break;
			
		case "ASSOCIATION":
		case "SCHOOL":
		case "GROUP":
			$('#fieldSponsorCompanyName').show();
			$('#fieldSponsorCompanyVATNumber').hide();
			$('#fieldSponsorGender').hide();
			$('#fieldSponsorDateOfBirth').hide();
			break;

		default:
			$('#fieldSponsorCompanyName').hide();
			$('#fieldSponsorCompanyVATNumber').hide();
			$('#fieldSponsorGender').show();
			$('#fieldSponsorDateOfBirth').show();
			break;
	}
}

function toggleUserExternalRelationNumberVisibility() {
	if ($(".fieldUserIsSponsor > input").is(":checked")) {
		$('input[name$=fieldUserExternalRelationNumber]').val('0');
		$("#divUserExternalRelationNumber").show();
	}
	else {
		$('input[name$=fieldUserExternalRelationNumber]').val('');
		$("#divUserExternalRelationNumber").hide();
	}
}

(function($) {
	$.fn.browserResize = function() {
		if ($.browser.msie || $.browser.opera) {
			$(window).resize(function() {
				$('#footer').css('display', 'block');
			});
		};
	};
})(jQuery);

$(document).ready(function($) {
	$('.noscript').hide();
	$('.script').show();

	$(document).browserResize();

	$('.photoFolder table').imageBank(500, 500, 'false', 'thickbox', 'gallery');

	$(document).carousel('.campaignInformation .content ul', 1, 'horizontal', 'slow', 'swing', 'both', 0);
	$(document).carousel('.navigationCarousel .content ul', 1, 'horizontal', 'slow', 'swing', 'both', 0);

	$(document).carousel('.productCarousel .content ul', 3, 'horizontal', 'slow', 'swing', 'both', 10);
	$(document).carousel('.productCarouselVertical .content ul', 1, 'vertical', 'slow', 'swing', 'both', 0);

	$(document).carousel('.thumbnails ul', 4, 'horizontal', 'slow', 'swing', '', 0);
	$('.images').imageViewer(222, 222, 500, 500, 'gallery');
	$('a.thickbox').thickbox({
		macFFBgHack: '/Layout/Default/ImageShop/Thickbox/macFFBgHack.png',
		loadingImage: '/Layout/Default/ImageShop/Thickbox/thickbox-loading.gif'
	});
	$('.colorSelection').colorSelection('.colorSelect');

	$('*[class~=initialValue]').labelize();
	$('.actionBox .navigation ul a').tabbedNavigation();
	$('.meterpassword').meterPasswordStrength($('.meterpasswordresult'));

	toggleDeliveryAddressVisibility();
	$(".orderUseBillingAddressAsDelivery > input").change(function() {
		toggleDeliveryAddressVisibility();
	});

	toggleUserExternalRelationNumberVisibility();
	$(".fieldUserIsSponsor > input").bind("click change", function() {
		toggleUserExternalRelationNumberVisibility();
	});

	toggleSponsorFieldsVisibility();
	$('select.sponsorType').change(function() {
		toggleSponsorFieldsVisibility();
	});

	toggleGreetingSetSendingTimeVisibility();
	$('.greetingSendNow > input').click(function() {
		toggleGreetingSetSendingTimeVisibility();
	});
});