var hideDelay = 10;
var hGap = 0;
$(document).ready(function()
	{ // when html is loaded
	$('div.popmenu').popMenu();
	initOverLabels();
	$('div.flyout').linkFlyout();
	$('div.bmlayout').linkFlyout({flyoutInParent: true, alignToContainer: 'td'});
	if ($('#layout').length == 0)
		setTall();
	});

var clicked = false;
$(function()
	{
	if ( ! $.browser.msie)
		{
		$('a.viewdesign').click(function(e)
			{
			if (clicked)
				return false;
//console.log('viewdesign click');
			clicked = true;
			$('body').css('overflow-y', 'hidden');

			$('<div id="overlay"></overlay>')
				.css('top', $(document).scrollTop())
				.css('opacity', '0')
				.animate({'opacity': '0.5'}, 'slow')
				.appendTo('body');
			var closeP = $('<p align="right"></p>');
			var close = $('<a href="#"></a>')
				.click(function()
					{
					$('#overlay, #lightbox')
						.fadeOut('slow', function()
							{
							$(this).empty().remove();
							$('body').css('overflow-y', 'auto');
							});
					clicked = false;
					return false;
					})
				.appendTo(closeP);
			var closeIcon = $('<img width="39" height="36" src="/images/close.png" border="0" alt="Close"/>')
				.appendTo(close);
			$('<div id="lightbox"></div>')
				.hide()
				.append(closeP)
				.appendTo('body')
				.append($('<div></div>').load('/admin/preview-design.php', $(this).attr('href').match(/\?([^ ]*)/)[1], function()
					{
					setTimeout(function()
						{
						var top = ($(window).height() - $('#lightbox').height()) / 2;
						var left = ($(window).width() - $('#lightbox').width()) / 2;
						$('#lightbox')
							.css({'top': top+$(document).scrollTop(), 'left': left})
							.fadeIn();
						}, 10);
					}));
			return false;
			});
		}
	});

(function($)
	{
	$.fn.popMenu = function()
		{
		return this.each(function()
			{
			var self = $(this);
			self.data('hiding', false); // init timeout id
			var id = self.attr('id');
			var menuEl = $('a.'+id); // menu link class = dropdown id
			// position under menu link; using offsetHeight because height() seems to give the link's non block height
			pos = menuEl.offset();
			height = menuEl.attr('offsetHeight');
			if (typeof(height) == "undefined")
				return;
			self.css({'left': (pos.left+hGap)+'px', 'top': (pos.top + height)+'px'});
			// apply hover (mouseover, mouseout) to both menu link and dropdown.
			$.each([self, menuEl], function()
				{
				$(this).hover(
					function()
						{
						if (self.data('hiding'))
							{
							clearTimeout(self.data('hiding'));
							self.data('hiding', false);
							}
						$('div#'+id).show();
						menuEl.addClass('current');
						},
					function()
						{ // delay hide so if the pointer passes between the menu and dropdown the hide can be cancelled
						self.data('hiding', setTimeout(function()
							{
							menuEl.removeClass('current');
							$('div#'+id).hide();
							}, hideDelay));
						});
				});
			});
		}
	})(jQuery);

(function($)
	{
	$.fn.linkFlyout = function(options)
		{
		$.fn.linkFlyout.defaults = 
			{
			flyoutInParent: false,
			alignToContainer: ''
			};
		options = $.extend($.fn.linkFlyout.defaults, options);
		return this.each(function()
			{
			var flyout = $(this);
			//flyout.data('hiding', false);
			var id = flyout.attr('id');
			$('a.'+id).each(function()
				{
				var link = $(this);
				if (options.alignToContainer.length > 0)
					{
					link = link.closest(options.alignToContainer);
					}
				$(this).hover(
					function()
						{
						var windowTop = $(window).scrollTop();
						var linkOffset = link.offset();
						var linkWidth = link.outerWidth();
						var flyoutWidth = flyout.outerWidth();
						var flyoutHeight = flyout.outerHeight();
						var windowHeight = $(window).height();

						var left = linkOffset.left - flyoutWidth;
						if (left < 0)
							left = linkOffset.left + linkWidth;
						var top = linkOffset.top;
						if (flyoutHeight + linkOffset.top - windowTop > windowHeight)
							top = windowTop + windowHeight - flyoutHeight;

						if (options.flyoutInParent)
							{
							var parentOffset = link.offsetParent().offset();
							left -= parentOffset.left;
							top -= parentOffset.top;
							}

						$('div#'+id).css({'top': top+'px', 'left': left+'px'}).show();
						},
					function()
						{
						$('div#'+id).hide();
						});
				$(this).click(function() {return false;});
				});
			});
		}
	})(jQuery);

// Create plugin to preview a particular layout id
(function($)
	{
	$.fn.previewLayout = function(settings, layers, admin)
		{
		return this.each(function()
			{
			var layout = $(this);

			// Set local options and initialise layout
			$('#layout-container').css('width', settings.layout_w+'px');
			//$('#lightbox').css('width', settings.layout_w+'px');
			$('#layout-container').css('margin', '0');
			$('#layout-container').css('margin-bottom', '10px');

			// Set local options and initialise layout
			//$("#layout").jloData(settings);
			$('#layout').jloSpace({
				css: {
					"background": settings.hex,
					"width": (settings.layout_w) + 'px',
					"height": (settings.layout_h) + 'px',
					"-webkit-border-radius": settings.corners_r+'px',
					"-moz-border-radius": settings.corners_r+'px',
					"border-radius": settings.corners_r+'px'
				},
				hex: settings.hex
			});

			DD_roundies.addRule('#layout', settings.corners_r+'px');
		
			// Set default colours text and BG
			$.fn.jloColours.defaults.colours = [
				["grey1",191,191,191,"#BFBFBF"],
				["grey2",127,127,127,"#7F7F7F"],
				["grey3",64,64,64,"#404040"],
				["black",0,0,0,"#000000"]
			];
			$.fn.jloColours.defaults.startKey = 'black';

			// add layers to layoutSpace using saved layer info
			$(layers).each( function()
				{
				if (this.type == "txt")
					{
					var newLayer = $('<span />');	
					//newLayer.jloData(settings);
					$('#layout').append(newLayer);
					newLayer.text(this.value);
					newLayer.css(
						{
						'display': 'block',
						'position': 'absolute',
						'top': this.top,
						'left': this.left,
						'color': this.colour,
						'font-size': this.size,
						'font-family': this.font
						});
					}
				else
				if (this.type == "img")
					{
					var newLayer = $('<img />');
					//newLayer.jloData(this);
					$('#layout').append(newLayer);
					newLayer.attr('src',this.src);
					newLayer.css(
						{
						'display': 'block',
						'position': 'absolute',
						'top': this.top,
						'left': this.left
						});
					newLayer.attr('width', this.width);
					newLayer.attr('height', this.height);
					}
				});

			if ($('#layout-data').length > 0)
				{
				var conv = settings.badge_wmm / settings.layout_w;
//console.log('badge_wmm='+settings.badge_wmm+' layout_w='+settings.layout_w+' conv='+conv);
				var dataHTML = '<table class="layoutdata" width="'+settings.layout_w+'">';
				dataHTML += '<tbody><tr><th colspan="2">Badge Design</th></tr>';
				dataHTML += '<tr><td>Badge width</td><td>'+settings.badge_wmm+'mm</td></tr>';
				dataHTML += '<tr><td>Badge height</td><td>'+settings.badge_hmm+'mm</td></tr>';
				if (admin)
					dataHTML += '<tr><td>Badge corner radius</td><td>'+settings.corners_rmm+'mm</td></tr>';
				var i = 0;
				$.each(layers, function()
					{
					i++;
					var mmLeft = Math.round(parseInt(this.left) * conv);
					var mmTop  = Math.round(parseInt(this.top)  * conv);
					var index = parseInt(this.index)+1;
					if (this.type == 'txt')
						{
						dataHTML += '<tr><th colspan="2">Text layer '+index+'</th></tr>';
						dataHTML += '<tr><td>Text</td><td>'+this.value+'</td></tr>';
						if (admin)
							{
							dataHTML += '<tr><td>Left</td><td>'+mmLeft+'mm</td></tr>';
							dataHTML += '<tr><td>Top</td><td>'+mmTop+'mm</td></tr>';
							}
						var f = this.font.match(/([^,]*)/);
						dataHTML += '<tr><td>Font</td><td>'+f[1]+'</td></tr>';
						dataHTML += '<tr><td>Font size</td><td>'+this.size+'</td></tr>';
						if (admin)
							dataHTML += '<tr><td>Font colour</td><td>'+this.hex+'</td></tr>';
						}
					else
					if (this.type == 'img')
						{
						var mmWidth  = Math.round(parseInt(this.width)  * conv);
						var mmHeight = Math.round(parseInt(this.height) * conv);
						dataHTML += '<tr><th colspan="2">Image layer '+index+'</th></tr>';
						if (admin)
							{
							dataHTML += '<tr><td>Left</td><td>'+mmLeft+'mm</td></tr>';
							dataHTML += '<tr><td>Top</td><td>'+mmTop+'mm</td></tr>';
							dataHTML += '<tr><td>Width</td><td>'+mmWidth+'mm</td></tr>';
							dataHTML += '<tr><td>Height</td><td>'+mmHeight+'mm</td></tr>';
							}
						dataHTML += '<tr><td>File</td><td><a href="/v2/getfile.php?id='+settings.layout_id+'&layer='+i+'">Download</a></td></tr>';
						}
					});
				dataHTML += '</tbody></table>';
				$('#layout-data').html(dataHTML);
				}
			setTall();
			});
		}
	})(jQuery);

function setTall()
	{
	var otherOuterHeight = $('#header').outerHeight(true) + $('#menu').outerHeight(true) + $('#footer').outerHeight(true);

	var content = $('#content');
	var contentOuterHeight = content.outerHeight(true);
	var contentPadEtc = contentOuterHeight - content.height();

	var rightbar = $('#rightbar');
	var rightbarOuterHeight = rightbar.outerHeight(true);
	var rightbarPadEtc = rightbarOuterHeight - rightbar.height();
	var rightbar1stsection = $('#rightbar .section:eq(2) div:eq(0)');
	var rightbar1stsectionOuterHeight = rightbar1stsection.outerHeight(true);
	var rightbar1stsectionPadEtc = rightbar1stsectionOuterHeight - rightbar1stsection.height();

	var maxHeight = Math.max(contentOuterHeight, Math.max(rightbarOuterHeight, $(window).height()-otherOuterHeight));
	content.height(maxHeight - contentPadEtc);
	rightbar1stsection.height(rightbar1stsection.height() + maxHeight - rightbarPadEtc - rightbar.height());
	//rightbar.height(maxHeight - rightbarPadEtc);
	}

//window.onload = function()
//	{
//	setTimeout(initOverLabels, 10);
//	}
function initOverLabels()
	{
	if (!document.getElementById)
		return;      

	var labels, id, field;

	// Set focus and blur handlers to hide and show 
	// labels with 'overlabel' class names.
	labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++)
		{

		if (labels[i].className == 'overlabel')
			{

			// Skip labels that do not have a named association
			// with another field.
			id = labels[i].htmlFor || labels[i].getAttribute ('for');
			if (!id || !(field = document.getElementById(id)))
				{
				continue;
				} 

			// Change the applied class to hover the label 
			// over the form field.
			labels[i].className = 'overlabel-apply';

			// Hide any fields having an initial value.
			if (field.value !== '')
				{
				hideLabel(field.getAttribute('id'), true);
				}

			// Set handlers to show and hide labels.
			field.onfocus = function ()
				{
				hideLabel(this.getAttribute('id'), true);
				};
			field.onblur = function ()
				{
				if (this.value === '')
					{
					hideLabel(this.getAttribute('id'), false);
					}
				};

			// Handle clicks to label elements (for Safari).
			labels[i].onclick = function ()
				{
				var id, field;
				id = this.getAttribute('for');
				if (id && (field = document.getElementById(id)))
					{
					field.focus();
					}
				};

			}
		}
	};

function showOrder()
	{
	window.name='origin';
	var w = window.open('','order',
		'width=500,height=400,resizable,scrollbars,status,top=10,left=10');
	w.document.clear();
	w.focus();
	return true;
	}
function showProduct(pic)
	{
	var w = window.open('', 'product', 'width=500,height=600,resizable,scrollbars,top=0,left=30');
	var d = w.document;
	d.write('<html><head><title>Name Badge World Close Up</title></head><body bgcolor="white" leftmargin="6" topmargin="6">');
	d.write('<center><table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td align="center">');
	d.write('<img src="' + pic + '">');
	d.write('</td></tr><tr><td align="center"><form>');
	d.write('<input type="button" value="Close this window" onClick="window.close();">');
	d.write('</form></td></tr></table></center></body></html>');
	d.close();
	w.focus();
	return false;
	}
function showWin()
  {
  var w = window.open('','popup','width=600,height=500,resizable,scrollbars,status,left=80,top=80');
  w.document.clear();
  w.focus();
  return true;
  }
function showSearch()
	{
	window.name='origin';
	var w = window.open('','search','width=250,height=550,resizable,scrollbars,status,top=0,left=0');
	w.document.clear();
	w.focus();
	return true;
	}
function showPic()
  {
	//window.name='origin';
	var w = window.open('','gallery','width=400,height=400,resizable,scrollbars,status,left=0,top=0');
	w.document.clear();
	w.focus();
	return true;
	}
function checkShopBuy(formEl)
  {
	var value = formEl.quantity.value;
	if (value == "" || value == null || isNaN(value) || value < 1)
 		{
		alert("Please enter a quantity");
		return false;
		}
	return true;
	}
function initOverLabels()
	{
	if (!document.getElementById)
		return;      

	var labels, id, field;

	// Set focus and blur handlers to hide and show 
	// labels with 'overlabel' class names.
	labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++)
		{

		if (labels[i].className == 'overlabel')
			{

			// Skip labels that do not have a named association
			// with another field.
			id = labels[i].htmlFor || labels[i].getAttribute ('for');
			if (!id || !(field = document.getElementById(id)))
				{
				continue;
				} 

			// Change the applied class to hover the label 
			// over the form field.
			labels[i].className = 'overlabel-apply';

			// Hide any fields having an initial value.
			if (field.value !== '')
				{
				hideLabel(field.getAttribute('id'), true);
				}

			// Set handlers to show and hide labels.
			field.onfocus = function ()
				{
				hideLabel(this.getAttribute('id'), true);
				};
			field.onblur = function ()
				{
				if (this.value === '')
					{
					hideLabel(this.getAttribute('id'), false);
					}
				};

			// Handle clicks to label elements (for Safari).
			labels[i].onclick = function ()
				{
				var id, field;
				id = this.getAttribute('for');
				if (id && (field = document.getElementById(id)))
					{
					field.focus();
					}
				};

			}
		}
	};

function hideLabel (field_id, hide)
	{
	var field_for;
	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++)
		{
		field_for = labels[i].htmlFor || labels[i]. getAttribute('for');
		if (field_for == field_id)
			{
			labels[i].style.textIndent = (hide) ? '-2000px' : '0px';
			return true;
			}
		}
	}

function mailIt()
	{
  var email = "michael"
  var emailHost = "nametagsaustralia.com.au"
  document.write("(<a href=" + "mail" + "to:" + email + "@" + emailHost + ">click here</a>)")
	}

function reuseStyleCheck(el)
	{
	thisElValue = el.options[el.selectedIndex].value;
	otherEl = el.form.colour;
	otherElOption = otherEl.options[otherEl.selectedIndex];
	otherElValue = otherElOption.value;

	if (thisElValue.toLowerCase().indexOf('plain') > -1)
		{
		otherEl.options[0].value = 'Please select';
		otherEl.options[0].text = 'Please select...';
		otherEl.disabled = false;
		lbl = document.getElementById('colourlabel');
		lbl.className = 'ml req';
		}
	else
		{
		otherEl.options[0].value = '';
		otherEl.options[0].text = 'N/A';
		otherEl.selectedIndex = 0;
		otherEl.disabled = true;
		lbl = document.getElementById('colourlabel');
		lbl.className = 'ml';
		}
	}
function styleCheck(el)
	{
	thisElValue = el.options[el.selectedIndex].value;
	otherEl = el.form.metalcolour;
	otherElOption = otherEl.options[otherEl.selectedIndex];
	otherElValue = otherElOption.value;
	
	if (thisElValue.toLowerCase().indexOf('metal') > -1)
		{
		otherEl.options[0].value = 'Please select';
		otherEl.options[0].text = 'Please select...';
		otherEl.disabled = false;
		lbl = document.getElementById('metalcolourlabel');
		lbl.className = 'ml req';
		}
	else
		{
		otherEl.options[0].value = '';
		otherEl.options[0].text = 'N/A';
		otherEl.selectedIndex = 0;
		otherEl.disabled = true;
		lbl = document.getElementById('metalcolourlabel');
		lbl.className = 'ml';
		}
	}
function sizeCheck(el)
	{
	thisElValue = el.options[el.selectedIndex].value;
	surroundEl = el.form.surround;
	surroundElOption = surroundEl.options[surroundEl.selectedIndex];
	surroundElValue = surroundElOption.value;
	
	if (thisElValue == '75mmx25mm' || thisElValue == '65mmx20mm' || thisElValue == '70mmx17mm')
		{
		surroundEl.options[0].value = 'Please select';
		surroundEl.options[0].text = 'Please select...';
		surroundEl.disabled = false;
		surroundEl.selectedIndex = 1;
		lbl = document.getElementById('surroundlabel');
		lbl.className = 'ml req';
		}
	else
		{
		surroundEl.options[0].value = '';
//surroundEl.options[0].value = 'No Surround';
		surroundEl.options[0].text = 'N/A';
		surroundEl.selectedIndex = 0;
		surroundEl.disabled = true;
		lbl = document.getElementById('surroundlabel');
		lbl.className = 'ml';
		if (thisElValue == '65mmx35mm metal oval')
			{
			styleEl = el.form.style;
			styleElValue = styleEl.options[styleEl.selectedIndex].value;
			if (styleElValue.toLowerCase().indexOf('metal') == -1)
				{
				alert('65mmx35mm metal oval is only available for metal styles.');
				el.selectedIndex = 0;
				}
			}
		}
	}
function surroundCheck(el)
	{
	thisElValue = el.options[el.selectedIndex].value;
	sizeEl = el.form.size;
	sizeElOption = sizeEl.options[sizeEl.selectedIndex];
	sizeElValue = sizeElOption.value;
	
	if (thisElValue == '' || thisElValue == 'No Surround')
		return;
	if (sizeElValue != '75mmx25mm' && sizeElValue != '65mmx20mm' && sizeElValue != '70mmx17mm')
		{
		alert('Surrounds are only available for badge sizes 75mmx25mm, 65mmx20mm and 70mmx17mm.');
		el.selectedIndex = 0;
		return;
		}
	}
function labelStyleCheck(el)
	{
	thisElValue = el.options[el.selectedIndex].value;
	numcoloursEl = el.form.numcolours;
	numcoloursElOption = numcoloursEl.options[numcoloursEl.selectedIndex];
	numcoloursElValue = numcoloursElOption.value;
	
	if (thisElValue == 'Etched')
		{
		numcoloursEl.options[0].value = '';
		numcoloursEl.options[0].text = 'N/A';
		numcoloursEl.selectedIndex = 0;
		numcoloursEl.disabled = true;
		lbl = document.getElementById('numcolourslabel');
		lbl.className = 'ml';
		}
	else
		{
		numcoloursEl.options[0].value = 'Please select';
		numcoloursEl.options[0].text = 'Please select...';
		numcoloursEl.disabled = false;
		lbl = document.getElementById('numcolourslabel');
		lbl.className = 'ml req';
		}
	}

