var maxPagesInHistory = 10;
	
/* When document ready */
$(document).ready(function() {
	
	/* AutoSuggest */
	var options = {
		suggestionsDiv: $("#globalPageAutoComplete"),
		//autoCompleteURL: 'http://www.tine.no/searchblox61/servlet/AutoSuggest',
		autoCompleteURL: 'http://www.tine.no/webproxy',
		searchResultsURL: 'http://www.tine.no/searchblox61/servlet/SearchServlet',
		params: '&col=3&col=4&col=7&col=8',
		site: "&urlnum=1"
		
	};
	$('#globalSearch').searchbloxAutoComplete(options);
	
	/* Avoid text selection for +/- on number of people controls */
	$(".numberofpeople").disableSelection();

	/* Store page url and title for "pervious pages" */
	storeCurrentPageInHistory();

	/* Sets all gradient */
	$(".gradient").each(function() {
		
		/* Get colors */
		var fromColor = $(this).children(".from")[0];
		var toColor = $(this).children(".to")[0];
		fromColor = $(fromColor).text();
		toColor = $(toColor).text();
		
		/* Add style. The .htc file (behavior: url('scripts/pie/PIE.htc')) MUST be in the style sheet */
		$(this).attr("style", 
				"background: -moz-linear-gradient(100% 100% 90deg, " + toColor + ", " + fromColor + "); " +
				"background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(" + fromColor + "), to(" + toColor + ")); " +
				"-pie-background: linear-gradient(" + fromColor + ", " + toColor + "); "

		);
		
		/* Add arrow to the end */
		$(this).append("<img src='http://webfiles.tine.no/tine.no_v2/images/arrow_white_transparent.png' alt='arrow' class='arrow'/>");
	});
	
	
	if ($("#ownIngredients").size() == 1) {
		var ingredients = $("#ownIngredients span").split("<br/>");
		$("#ownIngredients").append().html("ul");
		for ( var i = 0; i < ingredients.length; i++) {
			var ingredient = ingredients[i];
			$("#ownIngredients ul").append().html("li", ingredient);
		}
	}
	
	/* Recipie page */
	if ($("#recipeDiv").size() > 0) {
		
		/* Save original */
		var oginalPortions = $("input.multipliable").val();
		var backupPortions = $("input.multipliable").val();
		
		/* Changing portions */
		$("input.multipliable").live('blur', function() {
			
			newPortions = parseInt($(this).val());

			/* Set amount for the print function*/
			recipePeopleAmount = newPortions;

			if (newPortions <= 0 || newPortions >= 100) {
				$(this).val(backupPortions);
				return false;
			}
			backupPortions = $(this).val();
			
			/* New value */
			var newPortions = $(this).val();
			
			/* Update ingridents on page */
			$(".ingredients").find(".amount").each(function() {

				/* Orginal amount */
				var orginalAmount = parseFloat($(this).prev().text().replace(",","."));

				if(isNaN(orginalAmount) == false)
				{
					/* Math */
					var newAmount = ((orginalAmount / oginalPortions) * newPortions);
					newAmount = roundNumber(newAmount, 2);
					
					/* Change 0.X -> X/X */
					if (newAmount < 1) {
						if (newAmount == "0.25") {
							newAmount = String.fromCharCode(188);
						} else if (newAmount == "0.5") {
							newAmount = String.fromCharCode(189);
						} else if (newAmount == "0.75") {
							newAmount = String.fromCharCode(190);
						}
					}
					
					/* Set it */
					$(this).text(newAmount);
				}
			});
			
			//TODO Update link
			var href = $("#addAmountToShoopingList").attr('href');
			var lastIndex = href.lastIndexOf(',');
			var tmpHref = href.substring(0, lastIndex);
			var newHref = tmpHref + "," + backupPortions + ")";
			$("#addAmountToShoopingList").attr('href', newHref);
		});
	}
	
	/* if contact page */
	if ($("#reklSkjema").size() == 1) {
		
		$("#HoldbarhetDatoInfo, #ProductionCodeInfo").bind('click', function() {
			var imgUrl = "http://webfiles.tine.no/Tine.no/images/produktholdbarhet/";
			var imgId = $("#WebProduct option:selected").attr('class');
			
			if ($.trim(imgId) == "") {
				return;
			}
			imgId = imgId.substring(3);
			imgUrl = imgUrl + imgId + ".jpg";
			
			//Get the screen height and width
			var maskHeight = $(document).height();
			var maskWidth = $(window).width();

			//Set heigth and width to mask to fill up the whole screen
			$('#mask').css({'width':maskWidth,'height':maskHeight});

			//Get the window height and width
			var winH = $(window).height();
			var winW = $(window).width();
			  
			//Get scroll
			var pos = getScrollXY();
			
			//Set the popup window to center
			$('#HoldbarhetDatoInfoBox').css('top',  (winH/2-$('#HoldbarhetDatoInfoBox').height()/2) + pos.y);
			$('#HoldbarhetDatoInfoBox').css('left', (winW/2-$('#HoldbarhetDatoInfoBox').width()/2) + pos.x);
			
			$('#HoldbarhetDatoInfoBox').find("img:not(.closeLogin)").remove();
			$('#HoldbarhetDatoInfoBox').append("<img src='" + imgUrl + "' title='Hjelpbilde' class='rounded'></img>");
			
			$("#mask").show();
			$("#HoldbarhetDatoInfoBox").show();
		});
		$("#ProductionSiteInfo").bind('click', function() {
			//Get the screen height and width
			var maskHeight = $(document).height();
			var maskWidth = $(window).width();

			//Set heigth and width to mask to fill up the whole screen
			$('#mask').css({'width':maskWidth,'height':maskHeight});

			//Get the window height and width
			var winH = $(window).height();
			var winW = $(window).width();
			
			//Get scroll
			var pos = getScrollXY();
			  
			//Set the popup window to center
			$('#ProductionSiteInfoBox').css('top',  winH/2-$('#ProductionSiteInfoBox').height()/2 + pos.y);
			$('#ProductionSiteInfoBox').css('left', winW/2-$('#ProductionSiteInfoBox').width()/2 + pos.x);
			
			$('#ProductionSiteInfoBox').find("img:not(.closeLogin)").remove();
			$('#ProductionSiteInfoBox').append("<img src='http://webfiles.tine.no/Tine.no/elm/meierinummer.gif' title='Hjelpbilde'></img>");
			
			$("#mask").show();
			$("#ProductionSiteInfoBox").show();
		});
		
		$('#mask, #HoldbarhetDatoInfoBox .closeLogin, #ProductionSiteInfoBox .closeLogin').click(function () {
			$("#mask").hide();;
			$("#HoldbarhetDatoInfoBox").hide();;
			$("#ProductionSiteInfoBox").hide();;
		});
		
		
		/* Extra feature */
		$.validator.addMethod(
		        "regex",
		        function(value, element, regexp) {
		            var check = false;
		            var re = new RegExp(regexp);
		            return this.optional(element) || re.test(value);
		        },
		        "Please check your input."
		);
		
		/* Validation */
		$("#reklSkjema").validate({
	        rules: {
	        	WebProduct: "required",
	        	ProductionSite: "required",
	        	HoldbarhetDato: {
	        		required: true,
	        		regex: "^[0-9]{2}\.[0-9]{2}\.[0-9]{4}$"
	        	},
	        	ProductionCode: "required",
	        	Body: "required",
	        	PersonFirstName: "required",
	        	PersonLastName: "required",
	        	CompanyStreetAddress: "required",
	        	CompanyPostalCode: "required",
	        	CompanyRegion: "required",
	        	MailAddress: {
			        required: true,
			        email: true
			    },
			    BankAccount: {
	        		required: false,
	        		regex: "^[0-9]{11}$"
	        	}
	        },
	        messages: {
	        	WebProduct: "- Du må velge et produkt",
	        	ProductionSite: "- Du må velge et meieri",
	        	HoldbarhetDato: "- Du må angi holdbarhetsdato (dd.mm.yyyy)",
	        	ProductionCode: "- Du må angi en produksjonskode",
	        	Body: "- Du må skrive inn en beskrivelse",
	        	PersonFirstName: "- Du må angi ditt fornavn",
	        	PersonLastName: "- Du må angi ditt etternavn",
	        	CompanyStreetAddress: "- Du må angi din adresse",
	        	CompanyPostalCode: "- Du må angi ditt postnummer",
	        	CompanyRegion: "- Du må angi ditt stedsnavn",
	        	MailAddress: {
	    	        required: "- Du må angi en gyldig e-post",
	    	        email: "- Du må angi en gyldig e-post"
			    },
			    BankAccount: {
	        		regex: "- Du må oppgi bankkonto-nummer"
	        	}
	        },
	        errorContainer: ".formError, .formErrorHeadline",
	        errorLabelContainer: ".formError ul",
	        wrapper: "li",
	        errorClass : "invalid",
	        highlight: function(element, errorClass, validClass) {
	            $(element).addClass("invalidForm");
	            $(element).prev().addClass("invalidLabel");
	         },
	         unhighlight: function(element, errorClass, validClass) {
				$(element).removeClass("invalidForm");
				$(element).prev().removeClass("invalidLabel");
	         }
	    });
		
		
		
		$("#WebProduct").live('change', function() {
			if($(this).val() != "") {
				$(".infoButton").show();
			} else {
				$(".infoButton").hide();
				$(".infoButtonShow").show();
			}
		});
	}
	
		if ($("#brochureForm").size() == 1) {
			$("#brochureForm").validate({
				rules: {
					customer_firstname: "required",
					customer_surname: "required",
					shipping_postaladdress: "required",
					shipping_postalcode: "required",
					shipping_location: "required",
					customer_email: {
						required: true,
						email: true
					}
				},
				/*messages: {
					customer_firstname: "- Du må XXX",
					customer_surname: "- Du må YYY",
					shipping_postaladdress: "- Du må ZZZ",
					shipping_postalcode: "- Du må XYZ",
					shipping_location: "- Du må XZY",
					customer_email: {
						required: "- Du må angi en gyldig e-post",
						email: "- Du må angi en gyldig e-post"
					}
				},*/
				//errorContainer: ".formError, .formErrorHeadline",
				errorLabelContainer: ".formError ul",
				//wrapper: "li",
				errorClass : "invalid",
				highlight: function(element, errorClass, validClass) {
					$(element).addClass("invalidForm");
					$(element).prev().addClass("invalidLabel");
				 },
				 unhighlight: function(element, errorClass, validClass) {
					$(element).removeClass("invalidForm");
					$(element).prev().removeClass("invalidLabel");
				 }
			});
			
			$(".deleteBrochure").live('click', function() {
				$(this).closest("form").submit();
			});
			
			$(".deleteBrochure").live('mouseover', function() {
				$(this).attr("src", "http://webfiles.tine.no/tine.no_v2/images/button_delete_hover.png");
			});
			$(".deleteBrochure").live('mouseout', function() {
				$(this).attr("src", "http://webfiles.tine.no/tine.no_v2/images/button_delete.png");
			});
			
			$("#brochureCart  .sendButton").live('click', function(e) {
				$(this).closest("form").submit();
				e.preventDefault();
			});
			
			
						
		}
		$(".cartAddButton").live('click', function(e) {
				$(this).parent("form").submit();
				e.preventDefault();
			});
		
		
		
	/* if contact page */
	if ($("#kontaktSkjema").size() == 1) {
		
		/* Validation */
		$("#kontaktSkjema").validate({
			rules: {
				PersonFirstName: "required",
				PersonLastName: "required",
				MailAddress: {
					required: true,
					email: true
				},
				Body: "required"
			},
			messages: {
				PersonFirstName: "- Du må angi ditt fornavn",
				PersonLastName: "- Du må angi ditt etternavn",
				MailAddress: {
					required: "- Du må angi en gyldig e-post",
					email: "- Du må angi en gyldig e-post"
				},
				Body: "- Du må angi en beskrivelse"
			},
			errorContainer: ".formError, .formErrorHeadline",
			errorLabelContainer: ".formError ul",
			wrapper: "li",
			errorClass : "invalid",
			highlight: function(element, errorClass, validClass) {
				$(element).addClass("invalidForm");
				$(element).prev().addClass("invalidLabel");
			},
			unhighlight: function(element, errorClass, validClass) {
				$(element).removeClass("invalidForm");
				$(element).prev().removeClass("invalidLabel");
			}
		});
	}
});

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return {
		'x' : scrOfX, 
		'y' : scrOfY
	}
}

$(".twitter-share-button").live('click', function(e) {
	var title = document.title;

	if(title.startsWith("TINE.no | ")) {
		title = title.substring(10);
	}

	//GA Tracking
	_gaq.push(['_trackPageview', '/share/twitter-share']);
	_gaq.push(['_trackEvent', 'Share', 'Twitter', title]);
});

$("#twitter-share-button").live('click', function(e) {
	var title = document.title;

	if(title.startsWith("TINE.no | ")) {
		title = title.substring(10);
	}

	//GA Tracking
	_gaq.push(['_trackPageview', '/share/twitter-share']);
	_gaq.push(['_trackEvent', 'Share', 'Twitter', title]);
});

$("#facebook-share-button").live('click', function(e) {
	var href = document.URL;

	//GA Tracking
	_gaq.push(['_trackPageview', '/share/fb-like']);
	_gaq.push(['_trackEvent', 'Share', 'Facebook', href]);
});


$("#mail-share-button").live('click', function(e) {
	e.preventDefault();
	$("#mail-share-lightbox").show();
	$("#mask").show();
	Cufon.replace('#mail-share-lightbox h1');
});

$("#mail-share-lightbox .sendtipbutton").live('click', function(e) {
	e.preventDefault();

	var fromName = $("#fromname").val();
	var fromEmail = $("#fromemail").val();
	var toEmail = $("#tomail").val();
	var comment = $("#comment").val();

	if(fromName == "") {
		$("#sendtiperror").html("Avsenders navn er et påkrevd felt.");
		$("#sendtiperror").show();
		return;
	}

	if(fromEmail == "") {
		$("#sendtiperror").html("Avsenders e-postadresse er et påkrevd felt.");
		$("#sendtiperror").show();
		return;
	}

	if(toEmail == "") {
		$("#sendtiperror").html("Mottakers e-postadresse er et påkrevd felt.");
		$("#sendtiperror").show();
		return;
	}

	sendTipToEmailAboutThisPage(
		toEmail, fromName, fromEmail, comment, 
		function() {
			$("#mail-share-lightbox").hide();
			$("#mask").hide();
		},
		function(err) {
			$("#sendtiperror").html("Det oppsto dessverre en feil under sending av tipset (" + err + ").");
		}
	);
});

$(".closeMailShare").live('click', function(e) {
	$("#mail-share-lightbox").hide();
	$("#mask").hide();
});

$("#othersites a").live("click", function(e) {
	var site = e.target.href;

	if(site.startsWith("http://")) {
		site = site.substring(7);
	}

	_gaq.push(['_trackPageview', '/exitlink/' + site]);
	_gaq.push(['_trackEvent', 'Clicks', 'Exit Links', site]);
});

$("#rss-button").live('click', function(e) {

	var href = document.URL;

	//GA Tracking
	_gaq.push(['_trackPageview', '/share/rss']);
	_gaq.push(['_trackEvent', 'Share', 'RSS', href]);
});

function trackAddToBrochureCart(title)
{
	//GA Tracking
	_gaq.push(['_trackEvent', 'Brosjyrebestilling', 'Legg i handlekurv', '' + title]);

	return true;
}

function showRecipePrint(key, title, amount) {
	//GA Tracking
	_gaq.push(['_trackEvent', 'Print', 'Oppskrift', title + " (" + key + ")"]);

	var href = "http://www.tine.no/oppskrifter/print?key=" + key + "&amount=" + amount;
	window.open(href, 'recipeprint', '');
	return false;
}

function showRecipePrintOwn(hash) {
	//GA Tracking
	//_gaq.push(['_trackPageview', '/print/recipe/' + title + " (" + key + ")"]);
	_gaq.push(['_trackEvent', 'Print', 'EgenOppskrift', hash]);

	var href = "http://www.tine.no/oppskrifter/printOwn?hash=" + hash
	window.open(href, 'recipeprint', '');
	return false;
}


function showArticlePrint(key, title) {
	//GA Tracking
	_gaq.push(['_trackEvent', 'Print', 'Artikkel', title + " (" + key + ")"]);

	var href = "http://www.tine.no/system-pages/article-print?key=" + key;
	window.open(href, 'articleprint', '');
	return false;
}

function doPrint(key, title) {
	//GA Tracking
	_gaq.push(['_trackEvent', 'Print', 'Annet', title + " (" + key + ")"]);


	window.print();
	return false;
}

function article_share_window(href) {
	window.open(href, 'sharer', 'toolbar=0,status=0,width=626,height=436');
	return false;
} 

/* Sist besøkte sider - Min side */

function showHistory() {
	_d("History: Starting to show history (" + new Date() + ")");

	var hist = getHistory();

	_d("History: Generating HTML (" + new Date() + ")");

	var html = "<h2>Sist besøkte sider</h2><ul class='account-prev-pages-list'>";
	for(var i = 0; i < 5 &&  i < hist.length; i++) {
		html += getHistoryItemHTML(hist[i])
	}
	html += "</ul>";
//	$(".account-content").html(html);

	html += "<ul class='account-prev-pages-list'>"
	for(var i = 5; i < hist.length; i++) {
		html += getHistoryItemHTML(hist[i])
	}
	html += "</ul>";
	$(".account-content").html(html);

	Cufon.replace('.account-content h2');	

	_d("History: Finished showing history (" + new Date() + ")");
}

function getHistoryItemHTML(item) {
	var html = "";

	html += "<li>";
	html += "<img src='" + item.imgurl + "'/><div class='info'><a class='linkbullet' href='" + item.url + "'>" + item.title + "</a>";
	html += "<p>Besøkt " + Date.parse(item.visited).toString("dd.MM.yyyy HH:mm") + "</p></div>";
	html += "<br clear='both'/></li>";

	return html;
}

/* Save current page in cookie for later */
function storeCurrentPageInHistory() {
	var hist = getHistory();

	var currentUrl = location.href;
	if(currentUrl.indexOf("#") != -1) {
		currentUrl = currentUrl.substring(0, currentUrl.indexOf("#"));
	}

	if(hist.length > 0 && hist[0].url == currentUrl) {
		return;
	}

	var img = $("meta[property='og:image']").attr("content");
	if(img.indexOf("youtube") != -1) {
		img = img.substring(img.indexOf("youtube/") + 8, img.lastIndexOf("/"));
		img = "http://www.tine.no/imageresize/youtube/" + img + "/63_45.jpg";

	} else if(img.indexOf("facebook") != -1) {
		img = "http://webfiles.tine.no/TINE.no_v2/images/bildemangler.gif";

	} else if(img.length > 0) {
		img = img.substring(img.lastIndexOf("/") + 1);
		img = img.substring(0, img.indexOf("_"));

		if(img.length > 0) {
			img = "http://www.tine.no/imageresize/" + img + "_63_45.png";
		} else {
			img = "http://webfiles.tine.no/TINE.no_v2/images/bildemangler.gif";
		}

	} else {
		img = "http://webfiles.tine.no/TINE.no_v2/images/bildemangler.gif";
	}

	var title = document.title;
	if(title.indexOf("#") != -1) {
		title = title.substring(0, title.indexOf("#"));
	}

	var data = {
		'url': currentUrl,
		'title': document.title,
		'visited': new Date().toString("yyyy-dd-MM HH:mm"),
		'imgurl': img
	};

	if(data.title.indexOf('TINE.no ') == 0) {
		data.title = data.title.substring(10);
	}
	hist.unshift(data);

	hist = hist.slice(0, maxPagesInHistory);

	storeHistory(hist);
}

/* Clear history */
function clearHistoryFromLocalStorage() {
	window.localStorage.removeItem("prevPages");
}

/* Get history selector */
function getHistory() {
	if(supports_html5_storage()) {
		return getHistoryFromLocalStorage();
	} else {
		return getHistoryFromCookie();
	}
}

/* Store history selector */
function storeHistory(hist) {
	if(supports_html5_storage()) {
		storeHistoryToLocalStorage(hist);
	} else {
		storeHistoryToCookie(hist);
	}
}

/* HTML5 Local Storage storage */
function storeHistoryToLocalStorage(hist) {
	window.localStorage.setItem("prevPages", JSON.stringify(hist));
}

function getHistoryFromLocalStorage() {
	_d("History: Getting history from local storage");

	var hist = JSON.parse(window.localStorage.getItem("prevPages"));
	if(hist == null) {
		hist = new Array();
	}
	return hist;
}

/* Cookie storage */
function storeHistoryToCookie(hist) {
	$.cookie("prevPages", JSON.stringify(hist), { 'path': '/' });
}

function getHistoryFromCookie() {
	_d("History: Getting history from cookie");

	var hist = JSON.parse($.cookie("prevPages"));
	if(hist == null) {
		hist = new Array();
	}
	return hist;
}

/* Check if browser supports local storage */
function supports_html5_storage() {
	try {
		return 'localStorage' in window && window['localStorage'] !== null;
	} catch (e) {
		return false;
	}
}

/* General date formatting code */
/*
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"januar", "februar", "mars", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

*/
