var highlightedline=1;
var dirty=false;
var lastfield = 0;
var chatcounter = 0;
var chattimer;
var editmode = false;
var matchingedgeband = [];
var totalboardthumbnails = 0;
var boardthumbnails_initialised = false;
var ignorefitorderchange = false;
var wanted_jobs = [];

var DDstartday = 0;

$.fn.image = function(src, f){
    return this.each(function(){ 
        var i = new Image();
        i.src = src;
        while (this.firstChild)
        {
          //alert(this.firstChild);
          this.removeChild(this.firstChild);
        }     
        this.appendChild(i);
    });
}

	
  $(document).ready(function()
  {
    autocompleteOn();
    loadPreviousDoors();
    $("a.cwuser").click("return false;");
    if ($("#customers").length)
    {
      $("#customers").load("cutwrights.php?action=searchusers&searchterm="+random());
    }
    if ($("#cuttingjobs").length)
    {
      /*$("#cuttingjobs").css("backgroundImage", "url('spinner.gif')");*/
      $("#cuttingjobs").html("Loading cutting jobs <img src='spinner.gif'>");
      $("#cuttingjobs").load("cutwrights.php?action=searchjobs&searchterm="+random());
    }
    if ($("#sawopjobs").length)
    {
      $("#sawopjobs").load("cutwrights.php?action=sawopjobs&searchterm="+random());
      $(".admindetail").css("display","none");
    }
    $("#submit").submit("return false;");
    $("#grainimgcell").image("woodsegment.php?width=100&height=50",function(){
  //alert("The image is loaded now");
});
    $("#deliveryaddress").hide();
    $("#magiclist").hide();
       
//$.ui.dialog.defaults.bgiframe = true;    $("#dialog").dialog();
  });
  
  window.onbeforeunload = function() {
    //return 'You have unsaved changes!';
    //checkdirty();
    if (dirty)
    {
      return "You've made changes to the current cutting list but have not saved them. If you continue you will discard these changes.\n\nPress OK to continue or press Cancel to stay on this page, then press the 'Save Cutting List' button if you want the changes saved.";
    }
}

  function setEdgebandOptions(id)
  {
    var re = /(L1|L2|W1|W2)(\d+)/;
    var r;
    r = id.match(re);
    id = r[2];
    var s = document.getElementById('cuttinglistSheet'+id+'').value;
    s = s.replace(/^\s+/i, "");
    s = s.replace(/\s+$/i, "");
    var i;
    for (i=0; i < sheet.length; i++)
    {
      if (s == sheet[i])
      {
        break;
      }
    }
    //alert(i+' '+sheet[i]+' '+s+edgeband[i]);
    matchingedgeband = [];
    var e = edgeband[i];
    if (typeof(e) == 'undefined')
    {
      return;
    }
    //alert(e);
    if (e != '')
    {
      //e = e.replace(/(^|\t)([^\t]*2mm[^\t]*)(\t|$)/i,"\t$2 RADIUS\t$2 SQUARE\t"); 
      matchingedgeband = e.split("\t");
    }
    //alert(matchingedgeband);
  }
  
  function autocompleteOn()
  {
    jQuery("#optimiserresult").find("input").change( function(){pscalc(this)} );
    jQuery("#sendquote").click(function(){sendQuote(); return false;});

  	$(".Sheet").autocomplete(
  	  sheet,
  	  {
		matchContains: true,
		mustMatch: false,
		multiple: false,
		multipleSeparator: " ",
		max: 100,
        minChars: 0
	  });

  	$(".Sheet").focus(
  	  function()
  	  {
  	    var id = $(this).attr("id");
  	    $('#currentline').val(id);
      }
    );
    
  	$(".Edgeband").autocomplete(
  	  matchingedgeband,
  	  {
		matchContains: true,
		mustMatch: false,
		multiple: false,
		multipleSeparator: " "
	  });
  	$(".Edgeband").focus(
  	  function()
  	  {
  	    $(this).removeClass('edgeband-minimised');
  	    $(this).addClass('edgeband-maximised');
  	    var id = $(this).attr('id');
  	    //$(this).parent().append("<a href='' class='cwhelper' onclick=\"populateEdgebandSelect('"+id+"'); return false;\">?</a>");
  	    setEdgebandOptions(id);
  	    //$(this).val(matchingedgeband[0]);
  	    //$(this).val(" ");

  	    $(this).flushCache().autocomplete(
    	  matchingedgeband,
    	  {
	    	matchContains: true,
		    mustMatch: false,
		    multiple: false,
		    multipleSeparator: " ",
		    minChars: 0
  	      });
  	      // autocomplete bug fix? Need to send click event to activate autocomplete 
  	      $(this).click();
  	      //alert("Press space to see list of edge options");
  	      //$(this).show();
  	      //$(this).search();
  	    }
  	   );
  	$(".Edgeband").blur(
  	  function()
  	  {
  	    $(this).removeClass('edgeband-maximised');
  	    $(this).addClass('edgeband-minimised');
  	    //$(this).parent().find('.cwhelper').remove();
  	  }
  	 );
  	$(".spreadsheet").bind('keydown', 'up', function(){handleSpecialKey(this,'up');});
  	$(".spreadsheet").bind('keydown', 'down', function(){handleSpecialKey(this,'down');});
  	$(".spreadsheet").bind('keydown', 'right', function(){handleSpecialKey(this,'right');});
  	$(".spreadsheet").bind('keydown', 'left', function(){handleSpecialKey(this,'left');});
  	$(".spreadsheet").bind('keydown', 'tab', function(){editmode=false;});
    $(".datepicker").datepicker();
    $('input.time').timepicker();
    $("#dateboardarrived").datepicker();
    $('.datepicker').datepicker('option', 'dateFormat', 'dd/mm/yy');
    $('#dateboardarrived').datepicker('option', 'dateFormat', 'dd-mm-yy');
	//$(".draggable").multidraggable();    
    $(".draggable").draggable({
   start: function(event, ui) { $(this).css("border",'solid black 1px');  }
});
    $(".draggable").click(function () {
      if ($(this).css("border").indexOf('black') > -1)
      {
        //alert($(this).css("border"));
        $(this).css("border",''); 
      }
      else
      {
        $(this).css("border",'solid black 1px'); 
      }
    });

    calcweight(1);

    $(".droppable").droppable({
      drop: function()
      {
      var x = $(this).attr("name");
      var p = '';
      var weight = 0;
         if (!isNaN( parseFloat($("#ConsignmentWeight"+x).text()) ))
         {
           weight = parseFloat($("#ConsignmentWeight"+x).text());
         }
         $(".draggable [style*='solid black 1px']").css("display","none");
         $(".draggable").each(function()
         {
           if ($(this).css("border").indexOf("black") != -1)
           {
             $(this).css("display","none");
             $(this).css("border","");
             var i = $(this).find(".dragpanelid").html() - 1;
             p += (i+1) + ' ';
           }
         }
       )
       var panellist = $("#ConsignmentPanels"+x).text()+p;
       $("#ConsignmentPanels"+x).text(panellist);
       $("#hiddenConsignmentPanels"+x).val(panellist);
       $("#ConsignmentWeight"+x).text( weight );
       $("#hiddenConsignmentWeight"+x).val( weight );
       calcweight();
      }
    });
  }
  
  function calcweight()
  {
    var x;
    for (x=1; x<6; x++)
    {
      var panellist = $("#ConsignmentPanels"+x).text();
      var panels = panellist.split(" ");
      var i;
      var weight = 0;
      for (i=0; i<panels.length; i++)
      {
        if (!(isNaN(parseInt(panels[i]))))
        {
          panels[i]--;
          if (!(isNaN(parseFloat($('#panelweight'+panels[i]).text()))))
          {
            weight += parseFloat($('#panelweight'+panels[i]).text());
          }
        }
      }
      weight = Math.floor(parseFloat(weight)*100)/100;
      $("#ConsignmentWeight"+x).text( weight );
      $("#hiddenConsignmentWeight"+x).val( weight );
    }
  }
  
  function deliverynotification(x)
  {
  var r = '';
  var e = '';
  var job;
    job = document.getElementById('clid').value;
    r += "The following email will be sent to the customer. Press OK to send it or cancel to not send.";
    r += "\n\n";
    e += "A delivery for order OL" + job + " has been scheduled for ";
    e += document.getElementById('deliverydate'+x).value + ' ';
    e += document.getElementById('cuttinglistdeliverytime'+x).value;
    
    e += "\n";
    e += document.getElementById('consignmentcontent'+x).value
    e += "\n";

    e += "***We aim to be there at the scheduled time but please allow 30 minutes either side of this delivery time***\n";
    e += "Please ensure contact details for delivery/collection are correct in case our delivery team need to get in contact with you";    
    var a;
    a = confirm(r+e);
    if (a == false)
    {
      return false;
    }
    //$("#updatemsg").html("Delivery notification sent for Job OL"+job);
    $("#updatemsg").load("cutwrights.php?action=email&job="+job+"&text="+escape(e)+"&log=deliverynotification");
    $("#updatemsg").show();
  }
  
  function emptydelivery(x)
  {
    var panellist = $("#ConsignmentPanels"+x).text();
    var panels = panellist.split(" ");
    var i;
    for (i=0; i<panels.length; i++)
    {
      $("#dragpanel"+panels[i]).css("display","block");
    }
    $("#ConsignmentPanels"+x).text("");
    $("#hiddenConsignmentPanels"+x).val("");
    $("#ConsignmentWeight"+x).text("0");
    $("#hiddenConsignmentWeight"+x).val(0);
       //$("#ConsignmentPanels"+x).text('');
       //$("#hiddenConsignmentPanels"+x).val('');
       //$("#ConsignmentWeight"+x).text('');
  }
  
  function ChatStartStop(obj)
  {
  var v = $("#chatstartstopbutton").val();
    if (v == 'Stop')
    {
      $("#chatstartstopbutton").val('Start');
      ChatStop();
    }
    else
    {
      $("#chatstartstopbutton").val('Stop');
      ChatStart();
    }
  }
  
  function ChatStart()
  {
    UpdateChat();
    chattimer = setInterval( UpdateChat, 20000);
  }

  function ChatStop()
  {
    clearTimeout(chattimer);
  }
  
  function ChatMaximise(state)
  {
  var v = $("#chatmaximisebutton").val();
    if ((state == 'Maximise') && ( v == 'Minimise'))
    {
      return;
    }
    if (v == 'Maximise')
    {
      $("#chatmaximisebutton").val('Minimise');
      $("#chatmsgdiv").animate({height:"500px"},"normal");
    }
    else
    {
      $("#chatmaximisebutton").val('Maximise');
      $("#chatmsgdiv").animate({height:"150px"},"normal");
    }
  }
  
  function ChatAddMsg(m, id)
  {
    //var m=document.getElementById('chatmsg').value;
    $('#chat').load("cutwrights.php?action=wms&id="+id+"&msg="+escape(m));
  }

  function ChatAddTelephoneMsg()
  {
  var msg = $('#telephonelogmsgstart').val();
    if (msg == '')
    {
      return;
    }
  var m = '[#FAO:';
    m += $('#telephonelogfao').val();
    m += '#]';
    m += '[#CUSTOMER:';
    m += $('#telephonelogcustomerref').val();
    m += '#]';

    m += '[#JOB:';
    m += $('#telephonelogjobref').val();
    m += '#]';
    m += msg;

    m += '[#PRIORITY:';
    m += $('#telephonelogpriority').val();
    m += '#]';

    ChatAddMsg(m,-1);
    $("#wmsnewloggedmsg").hide('slow');
    $("#telephonelogcustomerref").val('');
    $("#telephonelogjobref").val('');
    $("#telephonelogmsgstart").val('');
  }

  function UpdateChat()
  {
    //$('#chat').html(chatcounter++);
    if (document.getElementById('chat'))
    {
      $('#chat').load("cutwrights.php?action=wms");
    }
    //clearInterval(chattimer);
  }
  
  function RefreshSawOpJobs()
  {
    $("#sawopjobs").load("cutwrights.php?action=sawopjobs&searchterm="+random());
  }
  function RefreshJobsCustomers()
  {
    search();
    //$("#customers").load("cutwrights.php?action=searchusers&searchterm=''"+random());
    //$("#cuttingjobs").load("cutwrights.php?action=searchjobs&searchterm=''"+random());
  }
  
  function CheckIncompleteList()
  {
  var i = 0;
  var max = 10;
    while (i<max)
    {
      var s = $('#cuttinglistSheet'+i).val();
      var l = $('#cutlistline'+i).find('.clLength').find('input').val();
      var w = $('#cutlistline'+i).find('.clWidth').find('input').val();
      var q = $('#cutlistline'+i).find('.clQty').find('input').val();
      if ( (i==0) && (s=='') && (l=='') && (w=='') && (q=='') )
      {
        alert("The first line of your cutting list is incomplete. You can't submit a Job with an empty first line. List not sent.");
        return false;
      }
      if ((s!='') || (l!='') || (w!='') || (q!=''))
      {
        if ((l == 0) || (w == 0))
        {
          alert("Line "+(i+1.0)+" has 0 for the length or width. Please complete lines before pressing the 'Send Cutting List' button. List not sent.");
          return false;
        }
        if ((s=='') || (l=='') || (w=='') || (q==''))
        {
          alert("Line "+(i+1.0)+" is incomplete. Please complete lines before pressing the 'Send Cutting List' button. List not sent.");
          return false;
        }
      }
      i++;
    }
    return true;
  }
  
  function OktoSend()
  {
    if (!checklock())
    {
      return false;
    }
    if (!CheckIncompleteList())
    {
      return false;
    }
    var offcuts=document.getElementById('cuttinglistoffcuts').value;
    var delivery=document.getElementById('cuttinglistdelivery').value;
    var deliveryaddress=document.getElementById('cuttinglist[deliveryaddress]').value;
    //alert(offcuts+' '+delivery);
    var msg ='';
    if (offcuts == '-')
    {
      msg = " - what to do with offcuts from your cutting job\n";
    }
    if (delivery == '-')
    {
      msg += " - whether you want the cutting job delivered\n";
    }
    if ((delivery == 'DELIVERY REQUIRED') && (deliveryaddress == ''))
    {
      msg += " - the delivery address\n";
    }
    if (msg != '')
    {
      msg = "Before we can process your cutting job we need you to tell us the following\n\n"+msg;
      msg += "\nPlease complete these parts of the form and then press 'Send Cutting list' again";
      alert(msg);
      return false;
    }
    dirty=false;
    return true;
  }
  
  function minfo(obj)
  {
    //alert(obj+obj.id);
    if (obj==infocsv)
    {
      str = "To load to into Ardis, download the CSV file to desktop (you can do this by right clicking on the Download CSV link, then saving to desktop). In Ardis select File->New. Right click on Parts. Select 'Add parts file'. Browse to Desktop. Look for the CSV file you just saved. Select 'open' and the file will appear under parts";
    }
    $(obj).append('<span class=minfo>'+str+'</span>');
    return false;
  }
  
  function checkdirty()
  {
    if (!dirty)
    {
      return true;
    }
    var r = confirm("You've made changes to the current cutting list. If you continue you will discard these changes.\n\nPress OK to continue or press Cancel to stay on this page, then press the 'Save Cutting List' button if you want the changes saved.");
    if (r == false)
    {
      return false;
    }
    return true;
  }
  
  function loaduserinfo(id)
  {
    if (checkdirty())
    {
      dirty=false;
      $("#viewstatus").html("Loading customer "+id+" details...<img src='spinner.gif'>");
      $("#cuttinglist").load("cutwrights.php?action=viewuser&user="+escape(id)+random());
    }
  }
  function loadcuttingjob(id)
  {
    if (checkdirty())
    {
      dirty=false;
      $("#viewstatus").html("Loading Cutting Job OL"+id+" details...<img src='spinner.gif'>");
      $("#cuttinglist").load("cutwrights.php?action=viewjob&job="+id+random(), function(){jobloaded()});
      $(".admindetail").css("display","none");
    }
  }
  function jobloaded()
  {
    $('div.twisty').twisty();
  }
  function deletecuttingjob(id)
  {
    var r = confirm("Are you sure you want to delete job OL"+id+'?');
    if (r == true)
    {
      $("#cuttingjobs").load("cutwrights.php?action=deletejob&job="+id+random());
      document.getElementById('cuttinglist').innerHTML = 'Job OL'+id+' deleted';
    }
  }
  function deletelogin(id)
  {
    var r = confirm("Are you sure you want to delete login "+id+'?');
    if (r == true)
    {
      $("#customers").load("cutwrights.php?action=deletelogin&username="+escape(id)+random());
      document.getElementById('cuttinglist').innerHTML = 'Login '+id+' deleted';
    }
  }
  function cutlistline(line)
  {
    var div=document.getElementById('cutlistline'+highlightedline);
    div.style.border = "solid white 0px"; //'#360000 1px';
    var div=document.getElementById('cutlistline'+line);
    div.style.border = "solid black 1px"; //'#360000 1px';
    highlightedline=line;
    //alert(highlightedline);
    var w = document.getElementById('cuttinglist[width'+highlightedline+']').value;
    var l = document.getElementById('cuttinglist[length'+highlightedline+']').value;
    var m = document.getElementById('cuttinglistSheet'+highlightedline+'').value;
    if ((w!='') && (l!=''))
    {
      var edging = getEdgeBand(line);
      $("#grainimgcell").image("woodsegment.php?width="+w+"&height="+l+"&edging="+edging+"&material="+escape(m));
      $("#partpreview").css({'visibility':'visible'});
    }
    else
    {
      $("#partpreview").css({'visibility':'hidden'});
    }
  }

  function handleSpecialKey(obj,key)
  {
    if (editmode)
    {
      return;
    }
    var components;
    if (components = obj.name.match(/(Sheet|EdgebandL1|EdgebandL2|EdgebandW1|EdgebandW2|length|width|qty|comment)(\d+)/))
    {
      id = -1;
      if (key == 'up')
      {
        if (components[2] == 0)
        {
          this.focus();
          return;
        }
        var newid = components[2]-1;
        id = 'cuttinglist['+components[1]+newid+']';
      }
      if (key == 'down')
      {
        var newid = parseInt(components[2])+1;
        id = 'cuttinglist['+components[1]+newid+']';
      }
      
      if (key == 'right')
      {
        if (components[1] == 'Sheet')
        {
          id = 'cuttinglist[length'+components[2]+']';
        }
        if (components[1] == 'length')
        {
          id = 'cuttinglist[width'+components[2]+']';
        }
        if (components[1] == 'width')
        {
          id = 'cuttinglist[qty'+components[2]+']';
        }
        if (components[1] == 'qty')
        {
          id = 'cuttinglist[EdgebandL1'+components[2]+']';
        }
        if (components[1] == 'EdgebandL1')
        {
          id = 'cuttinglist[EdgebandL2'+components[2]+']';
        }
        if (components[1] == 'EdgebandL2')
        {
          id = 'cuttinglist[EdgebandW1'+components[2]+']';
        }
        if (components[1] == 'EdgebandW1')
        {
          id = 'cuttinglist[EdgebandW2'+components[2]+']';
        }
        if (components[1] == 'EdgebandW2')
        {
          id = 'cuttinglist[comment'+components[2]+']';
        }
      }

      if (key == 'left')
      {
        if (components[1] == 'length')
        {
          id = 'cuttinglistSheet'+components[2]+'';
        }
        if (components[1] == 'width')
        {
          id = 'cuttinglist[length'+components[2]+']';
        }
        if (components[1] == 'qty')
        {
          id = 'cuttinglist[width'+components[2]+']';
        }
        if (components[1] == 'EdgebandL1')
        {
          id = 'cuttinglist[qty'+components[2]+']';
        }
        if (components[1] == 'EdgebandL2')
        {
          id = 'cuttinglist[EdgebandL1'+components[2]+']';
        }
        if (components[1] == 'EdgebandW1')
        {
          id = 'cuttinglist[EdgebandL2'+components[2]+']';
        }
        if (components[1] == 'EdgebandW2')
        {
          id = 'cuttinglist[EdgebandW1'+components[2]+']';
        }
        if (components[1] == 'comment')
        {
          id = 'cuttinglist[EdgebandW2'+components[2]+']';
        }
      }
      
      if (document.getElementById(id))
      {
        document.getElementById(id).focus();
      }
    }
  }
  
  function handleEnter (field, event, fn, fnarg)
  {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if ((keyCode != 13) && (keyCode != 39))
	{
	  editmode = true;
	  return true;
	}
	if (fnarg)
	{
      fn(fnarg); //alert(fn+fnarg);
    }

    var components = field.name.match(/(Sheet|EdgebandL1|EdgebandL2|EdgebandW1|EdgebandW2|length|width|qty|comment)(\d+)/);

    if (components[1] == 'Sheet')
    {
      id = 'cuttinglist[length'+components[2]+']';
    }
    if (components[1] == 'length')
    {
      id = 'cuttinglist[width'+components[2]+']';
    }
    if (components[1] == 'width')
    {
      id = 'cuttinglist[qty'+components[2]+']';
    }
    if (components[1] == 'qty')
    {
      id = 'cuttinglist[EdgebandL1'+components[2]+']';
    }
    if (components[1] == 'EdgebandL1')
    {
      id = 'cuttinglist[EdgebandL2'+components[2]+']';
    }
    if (components[1] == 'EdgebandL2')
    {
      id = 'cuttinglist[EdgebandW1'+components[2]+']';
    }
    if (components[1] == 'EdgebandW1')
    {
      id = 'cuttinglist[EdgebandW2'+components[2]+']';
    }
    if (components[1] == 'EdgebandW2')
    {
      id = 'cuttinglist[comment'+components[2]+']';
    }
    if (components[1] == 'comment')
    {
      id = parseInt(components[2]) + 1;
      id = 'cuttinglistSheet'+id+'';
    }

    if (document.getElementById(id))
    {
      document.getElementById(id).focus();
    }

    editmode = false;
	return false;
  }

  function ohandleEnter (field, event, fn, fnarg)
  {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if ((keyCode == 13) || (keyCode == 39))
	{
	  if (fnarg)
	  {
        fn(fnarg); //alert(fn+fnarg);
      }

	  var i;
	  for (i = lastfield; i < field.form.elements.length; i++)
	  {
	    if (field == field.form.elements[i])
		  break;
	  }
	  if (field != field.form.elements[i])
	  {
	    for (i = 0; i < field.form.elements.length; i++)
	    {
	      if (field == field.form.elements[i])
		    break;
	    }
	  }
	  alert(field.name+' '+field.form.elements[i].name);
	  i = (i + 1) % field.form.elements.length;
	  field.form.elements[i].focus();
	  lastfield = i;
	  editmode = false;
	  return false;
	} 
	else
	{
	  editmode = true;
	  return true;
	}
  }
  
function formcondition()
{
var condition = "";
  if (document.getElementById('JobsCompleted').checked)
  {
    condition += "completed";
  }
  if (document.getElementById('JobsQuotation').checked)
  {
    condition += "quotation";
  }
  if (document.getElementById('JobsQuery').checked)
  {
    condition += "query";
  }
  if (document.getElementById('JobsDraft').checked)
  {
    condition += "draft";
  }
  if (document.getElementById('JobsAll').checked)
  {
    condition = "all";
  }
  //if (condition != '')
  //{
  //  condition += " AND ";
  //}
  if (document.getElementById('JobsWon').checked)
  {
    //condition += "CuttingList LIKE %WON%";
    condition += "won";
  }
  //alert(document.getElementById('JobsAll').checked+'  '+condition);
  return condition;
}

function listjobsbystatus()
{
  var term = '';
  if (document.getElementById('searchtermbox'))
  {
    var term = document.getElementById('searchtermbox').value;
    term = term.replace(/ /,'|');
  }
  var condition = formcondition();
  //alert(condition);
  $("#cuttingjobs").html("Loading cutting jobs <img src='spinner.gif'>");
  $("#cuttingjobs").load("cutwrights.php?action=searchjobs&searchterm="+term+"&status="+condition+random());
}
  
  function listjobsorder(order)
  {
  var term = '';
    if (document.getElementById('searchtermbox'))
    {
      term = document.getElementById('searchtermbox').value;
      term = term.replace(/ /,'|');
    }
    var condition = formcondition();
    $("#cuttingjobs").html("Loading cutting jobs <img src='spinner.gif'>");
    $("#cuttingjobs").load("cutwrights.php?action=searchjobs&searchterm="+term+"&order="+order+"&status="+condition+random());
  }

  function listjobsbydate()
  {
    if (document.getElementById('searchtermbox'))
    {
      var term = document.getElementById('searchtermbox').value;
      term = term.replace(/ /,'|');
    }
    var condition = formcondition();
    $("#cuttingjobs").html("Loading cutting jobs <img src='spinner.gif'>");
    $("#cuttingjobs").load("cutwrights.php?action=searchjobs&searchterm="+term+"&order=date&status="+condition+random());
  }
  
  function search()
  {
    if (document.getElementById('searchtermbox'))
    {
      var term = document.getElementById('searchtermbox').value;
      term = term.replace(/ /,'|');
      //alert(term);
      //term="\""+term+"\"";
      var re = /OL(\d+)/i;
      var r = term.match(re);
      if (r)
      {
        loadcuttingjob(r[1]);
      }
      else
      {
        var condition = formcondition();
        $("#customers").load("cutwrights.php?action=searchusers&searchterm="+term+random());
        $("#cuttingjobs").html("Loading cutting jobs <img src='spinner.gif'>");
        $("#cuttingjobs").load("cutwrights.php?action=searchjobs&searchterm="+term+"&status="+condition+random());
      }
    }
  }
  
  function listusersbytype()
  {
    var term = '';
    if (document.getElementById('searchtermbox'))
    {
      term = document.getElementById('searchtermbox').value;
      term = term.replace(/ /,'|');
    }
    var type='';
    if ($("#UsersRetail").attr('checked'))
    {
      type += 'retail';
    }
    if ($("#UsersTrade").attr('checked'))
    {
      type += 'trade';
    }
    if ($("#UsersPriority").attr('checked'))
    {
      type += 'priority';
    }
    $("#customers").load("cutwrights.php?action=searchusers&searchterm="+term+"&type="+type+random());
  }
  
  function chkpostcode()
  {
    if (document.getElementById('deliverypostcode'))
    {
      var postcode = document.getElementById('deliverypostcode').value;
      postcode = postcode.replace(/ /, "");
      //alert(postcode);
      $("#postcoderesult").load("cutwrights.php?action=checkpostcode&postcode="+postcode);
    }
    return false;
  }
  function dbbackup()
  {
    $("#backupresult").load("cutwrights.php?action=dbbackup"+random());
  }
  function CSV()
  {
    var job = document.getElementById('job').value;

    $("#csv").load("cutwrights.php?action=cuttinglistcsv&job="+job+random());
  }
  function random()
  {
    var randomnumber=Math.floor(Math.random()*90000);
    var ret = '&token=';
    return ret+randomnumber;
  }
  function upload()
  {
    var file = document.getElementById('file').value;
    $("#uploadresult").load("upload_file.php?action=searchusers&searchterm="+term+random());
    $("#cp2").load("cutwrights.php?action=searchjobs&searchterm="+term+random());
  }
  function getEdgeBand(board)
  {
  var ret = '';
    if (document.getElementById('cuttinglist[EdgebandL1'+board+']').value != '')
    {
      ret += 'L1';
    }
    if (document.getElementById('cuttinglist[EdgebandL2'+board+']').value != '')
    {
      ret += 'L2';
    }
    if (document.getElementById('cuttinglist[EdgebandW1'+board+']').value != '')
    {
      ret += 'W1';
    }
    if (document.getElementById('cuttinglist[EdgebandW2'+board+']').value != '')
    {
      ret += 'W2';
    }
    return ret;
  }
  function updateEdgeBand(board,edge)
  {
    var selected = document.getElementById('cuttinglist[Edgeband'+edge+board+']').value;
    var colour = "solid black 5px";
    //alert(selected);
    //alert('[Edgeband'+edge+board+'] '+document.getElementById('cuttinglist[Edgeband'+edge+board+']').selectedIndex);
    //document.getElementById('grainimgcell0').style.border = "solid white 5px";
    if (selected == '')
    {
      colour = "solid white 5px";
    }
    if (edge == 'W1')
    {
      document.getElementById('grainimgcell').style.borderLeft = colour;
    }
    if (edge == 'W2')
    {
      document.getElementById('grainimgcell').style.borderRight = colour;
    }
    if (edge == 'L1')
    {
      document.getElementById('grainimgcell').style.borderTop = colour;
    }
    if (edge == 'L2')
    {
      document.getElementById('grainimgcell').style.borderBottom = colour;
    }
  }
  function materialSheetChange(obj,id)
  {
    var i=obj.options[obj.selectedIndex].value;
    var md=document.getElementById('materialdescription');
    md.innerHTML=materialdescription[i];
  }
  function materialEdgebandChange(obj,id,edge)
  {
    var i=obj.options[obj.selectedIndex].value;
    var md=document.getElementById('materialdescription');
    md.innerHTML=materialdescription[i];
    updateEdgeBand(id,edge);
  }
  function autofill(id)
  {
    //alert('autofill');
    var e = document.getElementById(id);
    if (!e) return;
    if (e.value == '')
    {
      var components = id.match(/(Sheet|EdgebandL1|EdgebandL2|EdgebandW1|EdgebandW2|length|width|qty)(\d+)/);
      if (components[2] > 0)
      {
        // get id/value of line above and use that to set this element
        var newid = components[2]-1;
        //id = id.replace(/(Sheet|L1|L2|W1|W2|length|width|qty)(\d+)/, newid);
        
        if (components[1].indexOf('Edgeband') != -1)
        {
          var thismaterial = $("#cuttinglistSheet"+components[2]).val();
          var previousmaterial = $("#cuttinglistSheet"+(components[2]-1)).val();
          var previousedging = document.getElementById("cuttinglist["+(components[1])+(components[2]-1)+"]").value;
          if ((previousmaterial == '') || (previousedging  == ''))
          {
            return;
          }
          if (thismaterial != previousmaterial)
          {
            if (thismaterial == '')
            {
              alert("Can't automatically copy down edging as you haven't entered a material for this line yet");
              return;
            }
            else
            {
              alert("Can't automatically copy down edging as the material on this line is different to the material on the line above.\nPrevious material:"+previousmaterial+", this material:"+thismaterial+"\nPress OK then spacebar to see the edge options available for "+thismaterial);
              return;
            }
          }
        }
        
        if (components[1] == 'Sheet')
        {
          // Sheet id uses new format without square brackets
          id = 'cuttinglist'+components[1]+newid+'';
        }
        else
        {
          id = 'cuttinglist['+components[1]+newid+']';
        }
        if (document.getElementById(id))
        {
          e.value = document.getElementById(id).value;
        }
      }
    }
  }
  
  function jsalert(str)
  {
    str = str.replace(/(<br\/>|,)/g,'\n');
    alert(str);
  }

function magiclisthelp()
{
window.open("magiclistexample.png","Example Magic List in Excel");
}

  function edgehelp()
  {
    var str='';
    for (var i=0; i<5; i++)
    {
      str += '\t'+edgeband[i]+'\n';
    }
    
    alert("In these columns you specify the edging type, L1 and L2 correspond to the long (with the grain) edges and W1 and W2 correspond to the width edges. The available edgebandings are:\n"+str);
  }

  function optimiser(id)
  {
    //alert("cutwrights.php?action=optimiser&job="+id);
    $("#optimiserresult").load("cutwrights.php?action=optimiser&job="+id+random(),'',optimisationcomplete);
  }

  function optimisationcomplete()
  {
    prep_pscalc();
    var f = $("a.templatelink").attr('href');
    $("#optimisationpdf").remove();
    $("#cwform").append("<input type='hidden' name='cuttinglist[optimisationpdf]' id='optimisationpdf' value='"+f+"'>");
    //alert(f);
  }
  
  function rerunoptimiser()
  {
  var i=0;
  var fitorder='';
  var preferred_orientation='';
  var preferred_stock='';
  var job=$("#clid").val();
    $('.readinstock').each(function(index) {
      if ($('#stock'+index+':checked').length > 0)
      {
        preferred_stock+=index+'x';
      }});
    console.debug('preferred_stock:'+preferred_stock);
    $('.fitorderdata').each(function(index) {
      fitorder += $(this).find("input.readinorder").val()+'x';
      preferred_orientation += $(this).find("input.readinorder").val()+'o'+$(this).find("input.orientation").val()+'x';
    });
  
$("#optimiserresult").load("cutwrights.php?action=optimiser&job="+job+"&fitorder="+fitorder+"&orientation="+preferred_orientation+"&stock"+preferred_stock+random(),'',optimisationcomplete);
  }

function optimiserbindings()
{
  //$(".fitorder").bind('change', 
}

function fitorderchange(fi)
{
var i=0;
  if (ignorefitorderchange)
  {
    return;
  }
  ignorefitorderchange = true; // prevents multiple onchange messages when manipulating elements
  var neworder = $("#fitorder"+fi).val();
  var orientation = $("#orientation"+fi).val();
  var html = "<div id='fitorderdata"+fi+"' class='fitorderdata moved'>"+$("#fitorderdata"+fi).html()+"</div>";
  $("#fitorderdata"+fi).remove();
  //alert(html);
  if ($(".fitorderdata").eq(neworder).length == 0)
  {
    $(".fitorderblock").append(html); //"<input id='fitorder"+fi+"' value='"+neworder+"'>");
  }
  else
  {
    $(".fitorderdata").eq(neworder).before(html); //"<input id='fitorder"+fi+"' value='"+neworder+"'>");
  }
  $("#orientation"+fi).val(orientation);
  ignorefitorderchange = false;
}

function prep_pscalc()
{
  var input_elements = $(".ps_line").find("input");
  input_elements.change(pscalc);
  //input_elements.css("color","red");
  input_elements.keypress(function(e){return handleEnter(this,e,'','')});
  $('div.twisty').twisty();
  pscalc();
}

function pscalc(obj)
{
//alert($(obj).attr('id'));
if (obj)
{
  $(obj).replaceWith("<input value='"+$(obj).val()+"' onchange='pscalc(this)'>");
}
var grandtotal = 0;
var table = '<p>Customer Quote (Generated '+timestamp()+')</p>';
  table += '<br>'+$('#quotecomments').val()+'<br>';
  table += '\n<table align=right>';
  table += '<tr><td>';
  //table += $("#cutlistforquote").html();
  table += '</td></tr>';
  table += '<tr><td>';
  table += '\n<table align=right>';
  table += '<tr><th>Item</th><th>Qty</th><th>Unit Cost</th><th>Total Cost</th></tr>';
  var lines = $(".ps_line");
  for (var i=0; i<lines.length; i++)
  {
    //alert($(lines[i]).html());
    var item = $(lines[i]).find('.ps_item').text();
    var qty = $(lines[i]).find('.ps_qty').find("input").val();
    var ps_unitcost = $(lines[i]).find('.ps_unitcost').find("input").val();
    var ps_markup = $(lines[i]).find('.ps_markup').find("input").val();
    var ps_totalcost = $(lines[i]).find('.ps_totalcost');
    var ps_totalcostmarkup = $(lines[i]).find('.ps_totalcostmarkup');
    $(ps_totalcost).html(roundPound(qty*ps_unitcost));
    var totalcostmarkup = roundPound(qty*ps_unitcost*(1+ps_markup/100));
    $(ps_totalcostmarkup).html(totalcostmarkup);
    grandtotal += totalcostmarkup;
    
    table += '<tr>';
    table += '  <td>'+item+'</td><td>'+qty+'</td><td>'+ps_unitcost+'</td><td>'+totalcostmarkup+'</td>';
    table += '</tr>';
  }
  table += '</table>';
  table += "<p style='clear:both'></p>";
  table += '\n<table align=right>';
  table += '<tr><td></td><td></td><td>Cutting/Edging<br>Sub total</td><td>'+ roundPound(grandtotal) + '</td></tr>';
  var discount = $(".ps_discount").find('.ps_markup').find("input").val();
  var discount_amount = roundPound(grandtotal*discount/100);
  grandtotal -= discount_amount;
  $(".ps_discount").find(".ps_totalcostmarkup").text(roundPound(grandtotal));
  var vat = $(".ps_vat").find('.ps_markup').find("input").val();
  $(".ps_vat").find(".ps_totalcostmarkup").text(roundPound(vat*grandtotal/100));
  if (discount != 0)
  {
     table += '<tr><td>Discount @ ' + discount + '%</td><td></td><td>' + ' ' + '</td><td>-'+ discount_amount + '</td></tr>';
  }
  table += '<tr><td>VAT @ ' + vat + '%</td><td></td><td>' + ' ' + '</td><td>'+ roundPound(vat*grandtotal/100) + '</td></tr>';

  var deliverycost = $(".ps_delivery").find(".ps_unitcost").find("input").val();
  var specialdeliverycost = $(".ps_specialdelivery").find(".ps_unitcost").find("input").val();
  grandtotal_nodelivery = roundPound(grandtotal*(1+vat/100));
  grandtotal_delivery = roundPound((grandtotal+parseFloat(deliverycost))*(1+vat/100));
  if (isNaN(grandtotal_delivery))
  {
    grandtotal_delivery = '-';
  }
  grandtotal_specialdelivery = roundPound((grandtotal+parseFloat(specialdeliverycost))*(1+vat/100));
  if (isNaN(grandtotal_specialdelivery))
  {
    grandtotal_specialdelivery = '-';
  }

  table += '<tr><td>Sub total </td><td></td><td>' + ' ' + '</td><td>'+ grandtotal_nodelivery + '</td></tr>';

  table += "<tr></tr>";
  table += '<tr><td>OPTION 1 Total excluding delivery (collect from Workshop)</td><td></td><td></td><td><span id="grandtotal_nodelivery">'+grandtotal_nodelivery+'</span></td></tr>';
  table += '<tr><td>OPTION 2 Total including Regular delivery (Regular delivery '+deliverycost+')</td><td></td><td></td><td><span id="grandtotal_delivery">'+grandtotal_delivery+'</span></td></tr>';
  //table += '<tr><td>OPTION 3 Total including Special delivery (Special delivery '+specialdeliverycost+')</td><td></td><td></td><td><span id="grandtotal_specialdelivery">'+grandtotal_specialdelivery+'</span></td></tr>';
  //table += '<tr><td></td><td></td><td>Total to pay</td><td>'+grandtotal+'</td></tr>';
  table += '</table>';

  table += '</td></tr>';
  table += '</table>';
  //var emailcontent = table;
  //$("#ps_grandtotal").html(grandtotal);
  $("#customerquote").html(table);
  table = table.replace(/</g,'&lt;');
  table = table.replace(/>/g,'&gt;');
  //alert(table);
  $("#customerquotepersist").val(table);
 
  var or;
  or = $("#optimiserresult").html();
  var t;
  or = or.replace(/onchange=\"[^\"]*\"/g,"");
  //if (t=or.indexOf("change"))
  //{
  //alert(or.substring(t-100,t+100));
  //}
  or = or.replace(/<!--(.*)-->\n/g,"");
  or = or.replace(/</g,"###LESSTHAN###");
  or = or.replace(/>/g,"###MORETHAN###");
  or = or.replace(/\"/g,"###QD###");
  or = or.replace(/\'/g,"###QS###");
  or = or.replace(/\n/g,"");
  //or = or.replace(/&/g,"&amp;");
  //alert(or);
  $("#optimiserresultpersist").val(or);

}

function roundPound(x)
{
  var y = Math.round(x*100);
  return y/100;
}

var deliverylocations;

function daySelected(obj)
{
  wanted_jobs = [];
  $(".DDday").removeClass('DaySelected');
  $(obj).addClass('DaySelected');
  obj = $(obj).attr('id');
  var job;
  $('#'+obj+' a').each(function(){
    job = $(this).text();
    if (job.indexOf('OL') != -1)
    {
      //console.debug(job);
      wanted_jobs.push(job);
    }
  });
  initialiseDeliveryPlannerMap();
}

function initialiseDeliveryPlannerMap()
{
var customerpostcode = "WD3 1NE";
  customerpostcode = $("#deliverypostcode").val();
  dpmap = new GMap2($("#deliveryplannermap").get(0));
  dpmap.setCenter(ourLocation, 8);
  dpmap.addControl(new GLargeMapControl);
  //GEvent.addListener(dpmap, "click", placeFromClick);
  //GEvent.addListener(dpmap, "addoverlay", mapUpdated);
  geocoder = new GClientGeocoder();
  
  var l = $("#deliverylocations").text();
  deliverylocations = l.split(',');
  getNextDeliveryAddress();
}

function getNextDeliveryAddress()
{
  if (deliverylocations.length > 0)
  {
    var dl = deliverylocations.pop();
    var kv = dl.split('->');
    if (kv.length > 1)
    {
    //console.debug(wanted_jobs);
    //console.debug(kv[0]);
      if (jQuery.inArray(kv[0], wanted_jobs) != -1)
      {
        showDeliveryAddress(kv[0],kv[1]);
      }
      else
      {
        getNextDeliveryAddress();
      }
    }
    else
    {
      getNextDeliveryAddress();
    }
  }
}

function showDeliveryAddress(job,address) {
  geocoder.getLatLng(
    address+',UK',
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
        var customicon = new GIcon(G_DEFAULT_ICON, 'mapmarker1.png');
        customicon.iconSize = GSize(50, 52);
        var marker = new GMarker(point,{icon:customicon, title:job+' '+address});
        dpmap.addOverlay(marker);
      }
      getNextDeliveryAddress();
    }
  );
}


function initialiseMap()
{
var customerpostcode = "WD3 1NE";
  customerpostcode = $("#deliverypostcode").val();
  map = new GMap2($("#map").get(0));
  map.setCenter(ourLocation, 10);
  map.addControl(new GLargeMapControl);
  GEvent.addListener(map, "click", placeFromClick);
  GEvent.addListener(map, "addoverlay", mapUpdated);
  geocoder = new GClientGeocoder();
				
  map.openInfoWindow(map.getCenter(),
  document.createTextNode("Our Workshop"));
  
  //showAddress('WD3 1NE');
  //showAddress('RG2 9BE');
												
  directionsPanel = document.getElementById("directiondisplay");
  directions = new GDirections(map, directionsPanel);
  GEvent.addListener(directions, "load", onGDirectionsLoad);
  GEvent.addListener(directions, "addoverlay", onGDirectionsAddoverlay);

  	fromto = "from: "+ourAddress+" to: "+customerpostcode;
	showDirections(true);

}

  function displayPoint(marker, index){
    $("#message").hide();
					
    var moveEnd = GEvent.addListener(map, "moveend", function(){
      var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
      $("#message")
       .fadeIn()
	   .css({ top:markerOffset.y, left:markerOffset.x });
					
    GEvent.removeListener(moveEnd);
  });
  map.panTo(marker.getLatLng());
}

function showDirections(getStepsPref)
{
	$("#directiondisplay").html("");
 	directions.load(fromto,{preserveViewport:true,getSteps:getStepsPref});
 	$("#directiondisplay").append("<button onclick=\"showDirections(true); return false;\">Get driving directions</button>");
}

function directionsFromLatLng(response)
{

  map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
    marker = new GMarker(point);
    map.addOverlay(marker);
    /*
    marker.openInfoWindowHtml(
        '<b>orig latlng:</b>' + response.name + '<br/>' + 
        '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
        '<b>Status Code:</b>' + response.Status.code + '<br>' +
        '<b>Status Request:</b>' + response.Status.request + '<br>' +
        '<b>Address:</b>' + place.address + '<br>' +
        '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
        '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
        */
	fromto = "from: "+ourAddress+" to: "+place.address;
	//var fromto = "from: london,uk to: "+place.address;
	//alert(fromto);
	showDirections(true);
  }
}

function placeFromClick(overlay, latlng)
{
  if (latlng != null) {
    address = latlng;
    geocoder.getLocations(latlng, directionsFromLatLng);
  }
}

function mapUpdated(overlay)
{
}

function onGDirectionsAddoverlay()
{
 	var route = $("#directiondisplay").text();
 	//alert(route);
 	if (route.indexOf('toll') != -1)
 	{
 	  alert("Congestion zone");
 	  $("#congestionzone").attr('checked', true);
 	}
 	else
 	{
 	  $("#congestionzone").attr('checked', false);
 	}
}

function onGDirectionsLoad()
{
var d;
var tripduration;
var miles;
var weight;
	d = directions.getDistance().meters;
 	$("#deliverydistance").val(d);
 	miles = Math.floor(0.62*d/1000);
 	$("#deliverydistancecl").val(miles);
 	var cost = Math.floor((15+parseInt(miles))/5)*5;
 	if ($("#congestionzone").attr('checked'))
 	{
 	  cost += 8;
 	}
 	$("#deliverymilescost").val(cost);
 	weight = $("#totalweight").text();
 	//alert(directions.getDuration().seconds);
 	//tripduration = Math.floor(2*directions.getDuration().seconds/60 + 5*weight/30);
 	// time each way plus 20mins unloading
 	tripduration = Math.floor(2*directions.getDuration().seconds/60 + 20);
 	$("#tripduration").val(Math.floor(tripduration/60)+'hr '+tripduration%60+'min');
 	var costinfo='';
 	if (d < 1000)
 	{
 	  costinfo = "You are less than a kilometre from our workshop. Why don't you pop in and collect the order?";
 	}
 	else if (d < 25000)
 	{
 	  costinfo = "Standard delivery cost is 25 Euros";
 	}
 	else if (d < 50000)
 	{
 	  costinfo = "Standard delivery cost is 35 Euros";
 	}
 	else if (d < 100000)
 	{
 	  costinfo = "Standard delivery cost is 60 Euros";
 	}
 	else if (d < 150000)
 	{
 	  costinfo = "Standard delivery cost is 80 Euros";
 	}
 	else if (d < 200000)
 	{
 	  costinfo = "Standard delivery cost is 100 Euros";
 	}
 	if (d < 50000)
 	{
 	  costinfo += "<br>Special delivery cost is 50 Euros";
 	}
 	else
 	{
 	  var c = 50 + (d-50000)/1000;
 	  costinfo += "<br>Special delivery cost is "+roundPound(c)+" Euros";
 	}
 	$("#deliverycost").html(costinfo);
}

function sendQuote()
{
//css('background-color', 'red');
  //$("#optimiserresult").find('.ps_line').find('.ps_markup').remove();
  //var h = $("#optimiserresult").html();
  var job = document.getElementById('clid').value;
  var q = {};
  q['text'] = ($("#customerquote").html());
  //var p = $("#ps_grandtotal").text();
  var pspecial = $("#grandtotal_specialdelivery").text();
  var pregular = $("#grandtotal_delivery").text();
  var pnodelivery = $("#grandtotal_nodelivery").text();

  var deliverycost = $(".ps_delivery").find(".ps_unitcost").find("input").val();
  if (deliverycost == '-')
  {
    alert("You need to update the delivery cost. Quote not sent.");
    return;
  }
  //alert(q);
$('#customerquoteinfo').load('cutwrights.php?action=sendquote&job='+job+'&price='+pnodelivery+'&pricer='+pregular+'&prices='+pspecial,q);
}

function timestamp()
{
  var ret = '';
  var currentTime = new Date();
  var month = currentTime.getMonth() + 1;
  var day = currentTime.getDate();
  var year = currentTime.getFullYear();

  ret += day+'/'+month+'/'+year+' ';
  var hour = currentTime.getHours();
  if (hour.length == 1)
  {
    ret += '0';
  }
  ret += hour+':';
  var minute = currentTime.getMinutes();
  if (minute.length == 1)
  {
    ret += '0';
  }
  ret += minute+':';
  var seconds = currentTime.getSeconds();
  if (seconds.length == 1)
  {
    ret += '0';
  }
  ret += seconds;

  return ret;
}

function populateMaterialSelect(id)
{
  $('#materialselect').remove();
  $('#materialselectdialog').append("<select id='materialselect' onchange='materialselectdialogchange()' size='20'></select>");
  for (var i=0; i<sheet.length; i++)
  {
    //$("#").addOption(sheet[i], sheet[i]);
    $('#materialselect').append( $('<option></option>').val(sheet[i]).html(sheet[i]) );
  }
  $('#materialselectdialog').dialog('open');
  $('#materialselectdialog').dialog( "option", "width", 500);
  $('#sheettext').show();
  $('#edgetext').hide();

  $('#currentline').val(id);
 }
function populateEdgebandSelect(id)
{
  setEdgebandOptions('L1'+id);
  $('#materialselect').remove();
  $('#materialselectdialog').append("<select id='materialselect' onchange='' size='20'></select>");
  for (var i=0; i<matchingedgeband.length; i++)
  {
    //$("#").addOption(sheet[i], sheet[i]);
    $('#materialselect').append( $('<option></option>').val(matchingedgeband[i]).html(matchingedgeband[i]) );
  }
  if (matchingedgeband.length == 0)
  {
    alert("You need to have a material selected before any edgebanding options are displayed");
  }
  $('#materialselectdialog').dialog('open');
  $('#sheettext').hide();
  $('#edgetext').show();
  $('#currentline').val('cuttinglistSheet'+id);
 }
 
 function materialselectdialogchange()
 {
   //alert($('#currentline').val());
   var line = '#' + $('#currentline').val();
   //alert($('#materialselect').val() + line);
   $(line).val( $('#materialselect').val() );
 }
 
function updateboardthumbnails()
{
  totalboardthumbnails = 0;
  loadnextthumbnail();
}

function loadnextthumbnail()
{
  var v = $("#boardthumbnailcaption"+totalboardthumbnails).text();
  if (v == '-1')
  {
    $('#boardthumbnailncaption'+totalboardthumbnails).remove();
    return;
  }
  totalboardthumbnails++;
  if (totalboardthumbnails < 1000)
  {
    $('#boardthumbnails').append("<div id='boardthumbnailncaption"+totalboardthumbnails+"' class='boardthumbnailncaption' onmouseover=\"boardthumbnailmouseover(this)\">");
    $('#boardthumbnailncaption'+totalboardthumbnails).append("<div id='boardthumbnail"+totalboardthumbnails+"' class='photoleft'>");
    $('#boardthumbnailncaption'+totalboardthumbnails).append("<br><div id='boardthumbnailcaption"+totalboardthumbnails+"' class='boardcaption'>");

    $("#boardthumbnail"+totalboardthumbnails).image("woodsegment.php?width=1400&height=1400&noannotation=1&n="+totalboardthumbnails+"");
    $("#boardthumbnailcaption"+totalboardthumbnails).load("woodsegment.php?info=1&n="+totalboardthumbnails+"",function(){loadnextthumbnail();});
  }

//$("#boardthumbnail"+totalboardthumbnails).attr("class", "vtip" );
totalboardthumbnails--;
$("#boardthumbnail"+totalboardthumbnails).attr("title", $("#boardthumbnailcaption"+totalboardthumbnails).text() );
totalboardthumbnails++;

}

function boardthumbnailmouseover(obj)
{
  //alert(obj);
  //$(obj).find('.boardcaption').css('font-size', '20px');
}

function stats()
{
  $("#cuttinglist").html("Statistics");
  $("#cuttinglist").load("cutwrights.php?action=stats"+random());
}

function clearcuttinglist()
{
var answer = confirm("This will delete all the lines from your current cutting list. Press 'OK' to confirm or else cancel.")
	if (answer){
		alert("All lines deleted")
	}
	else{
		return;
	}
  $(".spreadsheet").each(function()
   {$(this).val('');}
  );
}

function updateproductiontargets(job)
{
  var cuttingactual = $("#productiontargets"+job).find(".cuttingactual").val();
  var cuttingcomments = $("#productiontargets"+job).find(".cuttingcomments").val();
  var edgingactual = $("#productiontargets"+job).find(".edgingactual").val();
  var edgingcomments = $("#productiontargets"+job).find(".edgingcomments").val();
  //alert(cuttingactual+edgingactual+cuttingcomments+edgingcomments);
  $("#productiontargetsinfo"+job).load("cutwrights.php?action=sawopupdate&job="+job+"&cuttingactual="+cuttingactual+"&edgingactual="+edgingactual+"&cuttingcomments="+cuttingcomments+"&edgingcomments="+edgingcomments+random());

}

//DDstartday
function DDadvanceday()
{
  //DDstartday
  for (var i=-10; i<=30; i++)
  {
    if ((i<DDstartday-5) || (i>DDstartday+5))
    {
      $("#d"+i).hide();
    }
    else
    {
      $("#d"+i).show();
    }
  }
}

function timeslotclick(obj)
{
  $(obj).css("background-color","red");
}

function checklock()
{
var lock;
  lock = $("#JobLocked").val();
  if (lock == 'on')
  {
    var a = confirm("Job Locked\nThis job has already been quoted for and therefore no further changes can be made.\nIf you do need to make changes please phone the office on the number at the bottom of the page and ask for this job to be unlocked.\nIf you press 'OK' without first asking the office to unlock the job any changes you may have made now will be lost.");
    if (a == false)
    {
      return false;
    }
  }
  return true;
}

function savefooter()
{
  var footer = escape($("#emailfooter").val());
 $("#footerfeedback").load("cutwrights.php?action=s&f=footer&t="+footer+random());

}

function addlines()
{
  var lineblock = $("#cutlistline99999").html();  
  var i=5;
  while ($("#cutlistline"+i).length != 0)
  {
    i++;
  }
  i++;
  for (var j=i; j<i+10; j++)
  {
    var itemnumber = j;//+parseInt(1);
    newlineblock = lineblock.replace(/100000/i,itemnumber);
    newlineblock = newlineblock.replace(/99999/ig,j-1);
    $("#cutlistblock").append("<div class='cutlistline' id='cutlistline"+(j-1)+"' onmouseover='cutlistline("+(j-1)+")'>"+newlineblock+"</div>");
  }
  document.getElementById('cutlistline'+(i-3)).scrollIntoView();
  autocompleteOn();
}


