function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' You must enter a valid delivery postcode at the top of the form and click for Quotation\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function copyAddress() {
	document.checkout_WorldPay_Shipping.delvName.value = document.checkout_WorldPay_Shipping.name.value
	document.checkout_WorldPay_Shipping.delvAddress.value = document.checkout_WorldPay_Shipping.address.value
	document.checkout_WorldPay_Shipping.delvPostcode.value = document.checkout_WorldPay_Shipping.postcode.value
	document.checkout_WorldPay_Shipping.MC_delvTel.value = document.checkout_WorldPay_Shipping.tel.value
}

function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

function leadingZero(num) {
	num = num.toString();
	if(num.length < 2) {
		num = '0'+num;
	}
	return num;
}

function setupDatePicker() {
	var pickers = $('.js_datepicker');
	
	for(var i=0; i<pickers.length; ++i) {
		var currentPicker = pickers.eq(i);
		var date = new Date();
		var day = leadingZero(date.getDate());
		var month = date.getMonth();
		var year = date.getFullYear();
		month++;
		var dayInput = currentPicker.find('.day');
		var monthInput = currentPicker.find('.month');
		var yearInput = currentPicker.find('.year');
		dayInput.find('option:selected').removeAttr('selected');
		dayInput.find('option[value='+day+']').attr('selected', 'selected');
		monthInput.find('option:selected').removeAttr('selected');
		monthInput.find('option[value='+leadingZero(month)+']').attr('selected', 'selected');
		yearInput.find('option:selected').removeAttr('selected');
		yearInput.find('option[value='+year+']').attr('selected', 'selected');
		
		var offset = currentPicker.find('.minus1');
		if(offset.length > 0) {
			if(--month < 1) {
				month = 12;
				year--;
			}
			offset.find('option:selected').removeAttr('selected');
			offset.find('option[value='+leadingZero(month)+']').attr('selected', 'selected');
			yearInput.find('option:selected').removeAttr('selected');
			yearInput.find('option[value='+year+']').attr('selected', 'selected');
		}
		
		dayInput.change(checkDateValid);
		monthInput.change(checkDateValid);
		yearInput.change(checkDateValid);
		dayInput.parents('form').submit(checkDateValid);
	}
}

function isLeapYear(year) {
	var bool = false;
	if(year%100 == 0) {
		bool = (year%400 == 0) ? true : false;
	}
	else {
		bool = (year%4 == 0) ? true : false;
	}
	return bool;
}

function checkDateValid() {
	var pickers = $('.js_datepicker');
	
	for(var i=0; i<pickers.length; ++i) {
		var form = pickers.eq(i);
		var day = form.find('.day').attr('value');
		var month = form.find('.month').attr('value');
		var year = form.find('.year').attr('value');
		
		if((month == "09" || month == "04" || month == "06" || month == "11") && day == "31") {
			alert("Incorrect day selected");
			return false;
		}
		else if((month == "02" && isLeapYear(year) && (day == "31" || day == "30")) || (month == "02" && !isLeapYear(year) && (day == "31" || day == "30" || day == "29"))) {
			alert("Incorrect day selected");
			return false;
		}
		
		var now = new Date();
		
		if(year == now.getFullYear()) {
			if(parseInt(month) > (now.getMonth() + 1)) {
				alert("Date is in the future");
				return false;
			}
			else if((parseInt(month) == (now.getMonth() + 1)) && (parseInt(day) > now.getDate())) {
				alert("Date is in the future");
				return false;
			}
		}
	}
}

/* function to supply confirmation when delete is selected from a form
 * form(s) must have class "delete_form"
 * function works by counting checked checkboxes so no other checkboxes should be used in the form
 * uses click rather than submit so that more than one submit button can be used to fire different actions in the php
 */
function confirmDelete() {
	var form = $('.delete_form');
	for(var i=0; i<form.length; ++i) {
		form.eq(i).find('.deleteSubmit').click(function () {
			var form = this.form;
			var numChecked = 0;
			for(var j=0; j<form.length; ++j) {
				if(form.elements[j].type == "checkbox" && form.elements[j].checked == true) {
					numChecked++;
				}
			}
			var msg = (numChecked > 1) ? 'Are you sure you want to delete these '+numChecked+' items?' : 'Are you sure you want to delete this item?';
			if(numChecked != 0) {
				var bool = confirm(msg);
				return bool;
			}
			else {
				alert('No items selected for deletion!');
				return false;
			}
		})
	}
}

/* functions to reorder table rows
 * prepareOrderListeners - sets up the a tags to fire the relevant js  
 * tables(s) must have class "reorder_table"
 * rows that are movable must have class "order"
 * rows must contain a hidden input with name "row_id" containing the database id of that item
 * the a tags used to move rows must have class "order_control"
 * the up a tag must also have class "up" and down class "down"
 * form must have a hidden input with name "order" which stores the current order
 * calls function applyOrder
 * buttons call function doOrder
 */
function prepareOrderListeners() {
	var table = $('.reorder_table');
	
	for(var i=0; i<table.length; ++i) {
		applyOrder(table.eq(i));
		var rows = table.eq(i).find('.order');
		
		for(var j=0; j<rows.length; ++j) {
			rows.eq(j).find('.order_control').css('display','inline');
			rows.eq(j).find('.order_control').click(doOrder);
			if(j==0) {
				rows.eq(j).find('.up').css('display','none');
			}
			if(j+1==rows.length) {
				rows.eq(j).find('.down').css('display','none');
			}
		}
		
	}	
}

/* reads the reordable rows set by class 'order'
 * from the passed table and sets the value of an input called 'order'
 * with the ordered ids of the rows, this is the value sent to PHP to apply the order in the DB */
function applyOrder(table) {
	var roworder = new Array();
	var rows = table.find('.order');
	for(var i=0; i<rows.length; ++i) {
		roworder.push(rows.eq(i).find('input[name=row_id]').attr('value'));
	}
	table.find('input[name=order]').attr('value', roworder);
}

// does the visual DOM swapping
function doOrder() {
	var currentRow = $(this).parent().parent();
	if((/up/).test($(this).attr('class'))){
		var swapRow = currentRow.prev();
	}
	else if((/down/).test($(this).attr('class'))){
		var swapRow = currentRow.next();
		swapRow = swapRow.next();
	}
	currentRow.insertBefore(swapRow);
	// reset the links
	prepareOrderListeners();
	return false;
}

function prepareSwapImages() {
	var links = $('.js_swap_image');
	for(var i=0; i<links.length; ++i) {
		links.eq(i).mouseover(function () {
			var image = $(this).children('img');
			var src = image.attr('src');
			image.attr('name', src);
			var file = src.split('.');
			var ext = file.pop();
			file = file.join('.');
			file += '_f2';
			file += '.' + ext;
			image.attr('src', file);
		})
		links.eq(i).mouseout(function () {
			var image = $(this).children('img');
			var src = image.attr('name');
			image.removeAttr('name');
			image.attr('src', src);
		})
	}
}

function initDOM() {
	prepareOrderListeners();
	confirmDelete();
	setupDatePicker();
	prepareSwapImages();
}

$(document).ready(initDOM);