 var ocd;
 var calib;
 var tableWindow;
 var textWindow;
 var showControls=true;
 var selectNo=0;
 var source="ocp_null.js";
 var args;
 var wasWorking=false;
 var optionCommand="";
 var curveCommand="";
 var is_focussed=false;
 var ocdIndex;
 var tableDrawn=false;
 var leftLoaded=false;
 var loaderLoaded=false;
 var framesLoaded=false;
 var showingSequence=false;
 var svgContent="";
 var page;
 var headerSet=true;
  
 
 function makePlotOptionsString()
 {
  var str="";
  function addItem(ind)
  {
   str+="plotOptions."+ind+"="+plotOptions[ind]+";\n";
  };
  str+="plotOptions.showRange[1]="+plotOptions.showRange[1]+";\n";
  str+="plotOptions.showRange[2]="+plotOptions.showRange[2]+";\n";
  str+="plotOptions.showRange[3]="+plotOptions.showRange[3]+";\n";
  addItem("reportingStyle");
  addItem("showReversed");
  addItem("showWhole");
  addItem("plotsPerPage");
  addItem("scale");
  addItem("scaleFont");
  addItem("scaleLine");
  addItem("showIndices");
  addItem("showPropPlace");
  addItem("showADFirst");
  addItem("showNormalised");
  addItem("showAgreement");
  addItem("showConvergence");
  addItem("showOutliers");
  addItem("colorOutliers");
  addItem("showParameters");
  addItem("showVerbs");
  addItem("showItalics");
  addItem("showGrid");
  addItem("showText");
  addItem("showBandW");
  addItem("showBrackets");
  return str;
 };
 
 function readPlotOptionsString(str)
 {
  eval(str);
 };
 
 function saveOptions()
 {
  setCookie("OxCalPlotOptions",makePlotOptionsString());
 };
 
 function restoreOptions()
 {
  var str=getCookie("OxCalPlotOptions");
  if(str.length>100)
  {
   readPlotOptionsString(str);
  };
 };
 
 function getPlotName()
 {
  if(plotOptions.showBandW)
  {
   return "ocp_plot_bw.svg";
  };
  return "ocp_plot.svg";
 };
 
 function resetSettings()
 {
  if(!confirm("Reset OxCal to default settings?")){return;};
  delCookie("OxCalPlotOptions");
  delCookie("OxCalVersion");
  delCookie("OxCalWorkingPath");
  delCookie("OxCalHomePath");
  window.location=window.location;
 };
  
 function tidyText(str)
 {
  str=str.replace(/\x2b\x2f\x2d/g,String.fromCharCode(0x00b1));
  str=str.replace(/\</g,"&lt;");
  return str;
 };

 function defaultPaging(no)
 {
  var old=plotOptions.plotFrom;
  if(!no){no=1;};
  if(no > (parent.ocd.length-1)){return false;};
  if(no < 1){no=1;};
  plotOptions.plotFrom=no;
  plotOptions.plotLast=no-1;
  plotOptions.plotNext=no+1;
  plotOptions.plotPrev=no-plotOptions.plotsPerPage;
  plotOptions.plotTo=no+plotOptions.plotsPerPage;
  if(plotOptions.plotPrev<0){plotOptions.plotPrev=0;};
  if(plotOptions.plotLast<0){plotOptions.plotLast=0;};
  return old!=plotOptions.plotFrom;
 };
 
 function startPrint(single)
 {
  filecontent="\\documentclass[a4paper]{article}\n"
   +"\\usepackage[pdftex]{graphicx}\n"
   +"\\pagestyle{empty}\n"
   +"\\parindent=0pt\n"
   +"\\parskip=0pt\n"
   +"\\oddsidemargin  0cm\n"
   +"\\evensidemargin 0cm\n"
   +"\\textwidth      16.35cm\n"
   +"\\headheight     0cm\n"
   +"\\topmargin     -1cm\n"
   +"\\textheight  28cm\n"
   +"\\headsep  0cm\n";
  filecontent+="\\newcommand{\\oxcalfig}[1]{\\includegraphics[width=";
  if((plotOptions.viewType=="individual")&&(!single))
  {
   filecontent+="8";
  }
  else
  {
   filecontent+="16";
  };
  filecontent+="cm]{#1}}\n";
  filecontent+="\\begin{document}\n";
  svgContent="";
  page=0;
 };
 
 function getSVGContent()
 {
  var printPossible=right.location.toString().match(getPlotName()) && XMLSerializer;
  var cont;
  if(printPossible)
  {
   var xmlSerializer = new XMLSerializer(); // serialize
   cont=xmlSerializer.serializeToString(right.document);
   // get rid of duplicate header (Opera)
   cont=cont.replace('\<\?xml version="1.0"\?\>\<\?xml version="1.0" \?\>','\<\?xml version="1.0" \?\>');
   // add header if not there at all (Safari)
   if(cont.indexOf("\<\?xml")==-1)
   {
    cont="\<\?xml version=\"1.0\" encoding=\"UTF-8\"\?\>"+cont;
   };
   // get rid of any non-ascii characters
   cont=cont.replace(/[^\u000A\u000D\u0020-\u007F]/g,"_");
   return cont;
  };
  return false;
 };
 
 function pagePrint()
 {
  var cont;
  if(plotOptions.plotFrom > plotOptions.plotTo){return;};
  cont=getSVGContent();
  if(cont)
  {
   filename=source;
   svgContent+=cont;
   page++;
   filecontent+="\\oxcalfig{temp_"+page+"}\n";
   if(plotOptions.viewType=="individual")
   {
    if(!(page%2)){filecontent+="\n";};
   }
   else
   {
    filecontent+="\n";
   };
  };
 };
 
 function endPrint()
 {
   filecontent+="\\end{document}\n";
   filecontent+=svgContent;
   svgContent="";
   showingSequence=false;
   saveFileAs("tex");
 };
 
 function nextSlide()
 {
  var changed=false;
  pagePrint();
  switch(plotOptions.viewType)
  {
  case "individual":
   do
   {
    changed=defaultPaging(plotOptions.plotNext);
   }
   while(!ocd[plotOptions.plotFrom].selectNo && changed);
   break;
  case "select":
  case "multiple":
   changed=defaultPaging(plotOptions.plotTo+1);
   break;
  };
  if(changed)
  {
   updateView();
  }
  else
  {
   left.makeActive("main","7");
  };
 };

 function printPages()
 {
  switch(plotOptions.viewType)
  {
  case "individual":
  case "multiple":
  case "select":
   if(!XMLSerializer){alert("Not possible with this browser");return;};
   if(confirm("Print all pages?\n(this will lose any adjustments on this page)"))
   {
    startPrint(false);
    showingSequence=true;
    defaultPaging(0);
    updateView();
    break;
   };
   if(!confirm("Print just this page?"))
   {
    break;
   };
  case "curve":
  case "z":
   if(!XMLSerializer){alert("Not possible with this browser");return;};
   startPrint(true);
   pagePrint();
   endPrint();
   break;
  default:
   window.right.print();
   break;
  };
 };

 function plotData(i)
 {
  plotOptions.plotFrom=i;
  setView("individual");
 };
 
 function rawData(i)
 {
  plotOptions.plotFrom=i;
  setView("raw");
 };
 
 // sort first on whether relative, then on select order
 function selectSort(a,b)
 {
  if(a.rel && !b.rel){return 1;};
  if(b.rel && !a.rel){return -1;};
  return a.sel-b.sel;
 };
 
 function sortSelection()
 {
  ocdIndex=new Array;
  var i,j,last;
  j=0;last=0;
  for(i=0;i<ocd.length;i++)
  {
   if(!ocd[i]){continue;};
   if(ocd[i].selectNo>0)
   {
    if(ocd[i].op && (ocd[i].op=="Page") && (last!=0))
    {
     ocd[last].newPage=true;
     ocd[i].selectNo=0;
    }
    else
    {
     ocdIndex[j]=new Object;
     ocdIndex[j].ind=i;
     ocdIndex[j].sel=ocd[i].selectNo;
     ocdIndex[j].rel=ocd[i].relative;
     // put page breaks on main distributions, not intervals
     if(!ocd[i].relative)
     {
      last=i;
     };
     j++;
    };
   };
  };
  selectNo=j;
  ocdIndex.sort(selectSort);
  for(j=0;j<ocdIndex.length;j++)
  {
   ocd[ocdIndex[j].ind].selectNo=j+1;
  };
 };

 function isInternetExplorer()
 {
  return navigator.appName.indexOf("Microsoft")!=-1;
 };
 
 function runOxCal(command,direct)
 {
  var fullCmd;
  curveCommand=left.addCurve(true);
  left.setOptions();
  if(direct)
  {
   fullCmd=command;
  }
  else
  {
   fullCmd=optionCommand+
    "Plot(){"+curveCommand+command+"};";
  };
  if(onAServer())
  {
   source="/Quick.js";
   loader.document.getElementById("runFileCommand").value=fullCmd;
   loader.document.getElementById("runFile").submit();
   return true;
  }
  else
  {
   if(localFilePossible())
   {
    source="/Quick.js";
    localFileWrite(fullPath("Quick.oxcal"),fullCmd);
    source=fullPath("Quick.js");
    if(fullCmd.indexOf('Mix_')!=-1)
    {
     localOxCalLaunch(fullPath("Quick.oxcal"),false);
     window.setTimeout("reload();plotOxCal('','status')",1000);
    }
    else
    {
     localOxCalLaunch(fullPath("Quick.oxcal"),true);
     window.loader.location.reload();
    };
    return true;
   }
   else
   {
    alert("You cannot run OxCal from this Browser:\nSee documentation");
   };
  };
  return false;
 };
 
 function canSVG()
 {
  if(isInternetExplorer()){return false;};
  if(XMLSerializer){return true;};
  return false;
 };
 
 function setView(opt,redraw)
 {
  var comm,oldopt;
  if((ocd.length<2)&&(!calib.length))
  {
   right.location.replace("../oxcalhelp/hlp_contents.html");
   return;
  };
  switch(opt)
  {
  case "tab":
   editFile(source.replace('.js','.txt'),"txt");
   return;
  case "log":
   editFile(source.replace('.js','.log'),"log");
   return;
  };
  oldopt=plotOptions.viewType;
  plotOptions.viewType=opt;
  left.getoptions();
  saveOptions();
  switch(opt)
  {
  case "status":
   if(onAServer())
   {
    right.location.replace("ocp_status.php");
   }
   else
   {
    right.location.replace("ocp_status.html");
   };
   break;
  case "table":
   sortSelection();
   right.location.replace("ocp_right.html");
   break;
  case "parameter":
   right.location.replace("ocp_param.html");
   break;
  case "outlier":
   right.location.replace("ocp_outlier.html");
   break;
  case "raw":
   right.location.replace("ocp_raw.html");
   break;
  case "select":
   sortSelection();
  case "individual":
  case "multiple":
  case "x":
  case "y":
  case "z":
  case "curve":
  case "correlation":
  case "model":
   sortSelection();
   if(!redraw){resetOptions();};
   findSize();
   setupPlot();
   left.readback();
   if((onAServer()) && (!isInternetExplorer()))
   {
    if(canSVG())
	{
     right.location.replace(getPlotName());
	}
	else
	{
     right.location.replace("ocp_plot_loader.html");
	};
   }
   else
   {
    if(canSVG())
	{
     right.location.replace(getPlotName());
	}
	else
	{
     right.location.replace("ocp_plot.html");
	};
   };
   break;
  };
  if(!left){return;};
  switch(opt)
  {
  case "individual":
  case "multiple":
  case "select":
  case "raw":
     left.document.getElementById("Position").value=plotOptions.plotFrom;
     if(!mainMode)
     {
      left.document.getElementById("Pager").style.display="block";
     };
   break;
  default:
   if(left.document.getElementById("Pager"))
   {
    left.document.getElementById("Pager").style.display="none";
   };
   break;
  };
  if(args.Command)
  {
   comm=args.Command;
   args.Command=false;
   runOxCal(comm,true);
  };
  if((header_right&&(oldopt!=plotOptions.viewType))||(!headerSet))
  {
   headerSet=true;
   window.header_right.location.replace("oc_header_right.html");
  };
 };
 
 function updateView()
 {
  setView(plotOptions.viewType);
 };

 function redrawView()
 {
  setView(plotOptions.viewType,true);
 };

 function setupData()
 {
  var anyPosterior=false;
  var datacount=0;
  var first=NaN;
  if(ocd.length)
  {
   var i;
   for(i=0;i<ocd.length;i++)
   {
    // select the data
    if(ocd[i])
    {
     ocd[i].selectNo=i+1;
     if(ocd[i].likelihood)
     {
      if(ocd[i].likelihood.prob)
      {
       if(isNaN(first)){first=i;};
       datacount++;
      };
     };
     // check if there is any posterior
     if(ocd[i].posterior)
     {
      if(ocd[i].posterior.prob)
      {
       if(isNaN(first)){first=i;};
       datacount++;anyPosterior=true;
      };
     };
    };
   };
  };
  // if there is any posterior data then show it
  if(anyPosterior)
  {
   plotOptions.showPosterior=true;
   plotOptions.showIndices=true;
  }
  else
  {
   plotOptions.showPosterior=false;
   plotOptions.showIndices=false;
  };
  switch(datacount)
  {
  case 0:
   if(calib && calib.length>0)
   {
    plotOptions.viewType="curve";
    headerSet=false;
   };
   break;
  case 1:
   plotOptions.plotFrom=first;
   if(document.implementation.hasFeature("org.w3c.dom.svg","1.0"))
   {
    plotOptions.viewType="individual";
    headerSet=false;
   };
   break;
  };
  sortSelection();
 };
 function setData()
 {
  var test,i,podt,podd;
  if(!plotOptions.data){return;};
  podt=plotOptions.data.t;
  podd=plotOptions.data.d;
  if(!podt || !podd){return;};
  test=new Array;
  for(i=0;(i< podd.length) && (i< podt.length);i++)
  {
    if(plotOptions.reportingStyle!=0)
    {
     test[i]=Math.round((podt[i])*100)/100 + "\t" + podd[i];
    }
    else
    {
     test[i]=Math.round((plotOptions.BPDatum-podt[i])*100)/100 + "\t" + podd[i];
    };
  };
  right.document.getElementById("dataValues").value=test.join("\n");
  // set up data table from defaults
  right.document.getElementById("dataLabel").value=plotOptions.data.label;
  right.document.getElementById("dataMin").value=plotOptions.data.min;
  right.document.getElementById("dataMax").value=plotOptions.data.max;
  right.document.getElementById("dataBCAD").checked=(plotOptions.reportingStyle!=0);
 };
 function getData()
 {
  var test,i,podt,podd,line;
  if(!plotOptions.data){return;};
  plotOptions.data.t=new Array();
  plotOptions.data.d=new Array();
  podt=plotOptions.data.t;
  podd=plotOptions.data.d;
  test=right.document.getElementById("dataValues").value.split("\n");
  for(i=0;i< test.length;i++)
  {
   line=test[i].split("\t");
   if(line.length && line.length>1)
   {
    podt[i]=Number(line[0]);
    podd[i]=Number(line[1]);
   };
  };
  if(!right.document.getElementById("dataBCAD").checked)
  {
   for(i=0;i< podt.length;i++)
   {
    podt[i]=plotOptions.BPDatum-podt[i];
   };
  };
  plotOptions.data.label=right.document.getElementById("dataLabel").value;
  plotOptions.data.min=Number(right.document.getElementById("dataMin").value);
  plotOptions.data.max=Number(right.document.getElementById("dataMax").value);
 };
 function dataEditor(filename,clear)
 {
  if(clear)
  {
   plotOptions.data.label="";
   plotOptions.data.min=0;
   plotOptions.data.max=1;
   plotOptions.data.t=new Array();
   plotOptions.data.d=new Array();
  };
  right.location.replace(filename);
 };
 function dataOk()
 {
  getData();
  plotOptions.showData=true;
  updateView();
 };
 function dataCancel()
 {
  plotOptions.showData=false;
  updateView();
 };
 function reload()
 {
  loader.location.reload();
  window.status=source;
 };
 
 // set things up for viewing the data
 if(window.parent && window.parent.ocd)
 {
  ocd=parent.ocd;
  calib=parent.calib;
  setupData();
 }
 else
 {
  ocd=new Array;
  calib=new Array;
 };
 args=getArgs();
 if(args.source)
 {
  source=args.source;
 };
 if(args.view)
 {
  plotOptions.viewType=args.view;
 };
 window.status=source;
 window.focus();
 
