var highlightedline=1;
var dirty=false;
var lastfield = 0;
var chatcounter = 0;
var chattimer;
var editmode = false;

$.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();
    $("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();
  });
  
  function autocompleteOn()
  {
  	$(".Sheet").autocomplete(
  	  sheet,
  	  {
		matchContains: true,
		mustMatch: false,
		multiple: false,
		multipleSeparator: " ",
		max: 100
	  });
  	$(".Edgeband").autocomplete(
  	  edgeband,
  	  {
		matchContains: true,
		mustMatch: false,
		multiple: false,
		multipleSeparator: " "
	  });
  	$(".Edgeband").focus(
  	  function()
  	  {
  	    $(this).width(200);
  	  }
  	 );
  	$(".Edgeband").blur( function(){$(this).width(50);} );
  	$(".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 );
       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 );
    }
  }
  
  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 += "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));

  }
  
  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");
       //$("#ConsignmentPanels"+x).text('');
       //$("#hiddenConsignmentPanels"+x).val('');
       //$("#ConsignmentWeight"+x).text('');
  }
  
  function ChatStartStop(obj)
  {
  var v = $("#chatstartstopbutton").val();
    if (v == 'Stop')
    {
      $("#chatstartstopbutton").val('Start');
      clearTimeout(chattimer);
    }
    else
    {
      $("#chatstartstopbutton").val('Stop');
      UpdateChat();
      chattimer = setInterval( UpdateChat, 20000);
    }
  }
  
  function ChatMaximise(obj)
  {
  var v = $("#chatmaximisebutton").val();
    if (v == 'Maximise')
    {
      $("#chatmaximisebutton").val('Minimise');
      $("#chatmsgdiv").animate({height:"500px"},"normal");
    }
    else
    {
      $("#chatmaximisebutton").val('Maximise');
      $("#chatmsgdiv").animate({height:"150px"},"normal");
    }
  }
  
  function ChatAddMsg()
  {
    var m=document.getElementById('chatmsg').value;
    $('#chat').load("cutwrights.php?action=wms&msg="+escape(m));
  }
  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 OktoSend()
  {
    var offcuts=document.getElementById('cuttinglist[offcuts]').value;
    var delivery=document.getElementById('cuttinglist[delivery]').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;
    }
    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("<p>Loading customer "+id+" details...</p>");
      $("#cuttinglist").load("cutwrights.php?action=viewuser&user="+escape(id)+random());
    }
  }
  function loadcuttingjob(id)
  {
    if (checkdirty())
    {
      dirty=false;
      $("#viewstatus").html("<p>Loading Cutting Job OL"+id+" details...</p>");
      $("#cuttinglist").load("cutwrights.php?action=viewjob&job="+id+random());
            $(".admindetail").css("display","none");

    }
  }
  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.background = '#ffffff';
    div.style.border = "solid white 0px"; //'#360000 1px';
    var div=document.getElementById('cutlistline'+line);
    div.style.border = "solid black 1px"; //'#360000 1px';
    highlightedline=line;
    var w = document.getElementById('cuttinglist[width'+highlightedline+']').value;
    var l = document.getElementById('cuttinglist[length'+highlightedline+']').value;
    var m = document.getElementById('cuttinglist[Sheet'+highlightedline+']').value;
    if ((w!='') && (l!=''))
    {
      var edging = getEdgeBand(line);
      $("#grainimgcell").image("woodsegment.php?width="+w+"&height="+l+"&edging="+edging+"&material="+escape(m));
      //updateEdgeBand(line,'L1');
      //updateEdgeBand(line,'L2');
      //updateEdgeBand(line,'W1');
      //updateEdgeBand(line,'W2');
      $("#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 = 'cuttinglist[Sheet'+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 = 'cuttinglist[Sheet'+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('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 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 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)
  {
    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)
      {
        var newid = components[2]-1;
        //id = id.replace(/(Sheet|L1|L2|W1|W2|length|width|qty)(\d+)/, newid);
        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)
  {
    $("#optimiserresult").load("cutwrights.php?action=optimiser&job="+id+random(),'',prep_pscalc);
  }

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,'','')});
  pscalc();
}

function pscalc()
{
var grandtotal = 0;
  var lines = $(".ps_line");
  for (var i=0; i<lines.length; i++)
  {
    //alert($(lines[i]).html());
    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;
  }
  $("#ps_grandtotal").html('&pound;'+roundPound(grandtotal));
}

function roundPound(x)
{
  var y = Math.round(x*100);
  return y/100;
}
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('');}
  );
}
