
$().ready(function() {

	function findValueCallback(event, data, formatted) {
		lastslashIndex = data.toString().lastIndexOf("/");
		comp2Value = data.toString().substr(lastslashIndex+1);
		comp1Value = event.target.id.replace(/ac_me/, '');
		displayApMoreResult(1,comp1Value, comp2Value);
		//save the selected value to apMoreValues
                document.getElementById(comp1Value.replace(/-.*/,"")).apMoreValues.value += comp2Value + ",";

	}
	
	function formatItem(row) {
		return row[0] + " (<strong>id: " + row[1] + "</strong>)";
	}
	function formatResult(row) {
		return row[0].replace(/(<.+?>)/gi, '');
	}
	$("input.ac_me").autocomplete("http://virbo.org/js/autocomplete/search.php", {
                minChars: 0,
                max: 100,
                autoFill: false,
                mustMatch: true,
                matchContains: false,
                scrollHeight: 420,
                width: 500,
                selectFirst: false
        });
	$(":text, textarea").result(findValueCallback).next().click(function() {
		$(this).prev().search();
	});	
	$("#scrollChange").click(changeScrollHeight);
	

	$("#clear").click(function() {
		$(":input").unautocomplete();
	});
});

function changeOptions(){
	var max = parseInt(window.prompt('Please type number of items to display:', jQuery.Autocompleter.defaults.max));
	if (max > 0) {
		$("#suggest1").setOptions({
			max: max
		});
	}
}

function setYear(formName,Year_o,Year_f) {
	var form = document.getElementById(formName);
	for (var i=0; i<form.yearo.options.length; i++){
		if(form.yearo.options[i].value == Year_o){
			form.yearo.options[i].selected = true;
			break;
		}
	}
	for (var i=0; i<form.yearf.options.length; i++){
                if(form.yearf.options[i].value == Year_f){
                        form.yearf.selectedIndex = i;
                        break;
                }
        }
}

function changeScrollHeight() {
    var h = parseInt(window.prompt('Please type new scroll height (number in pixels):', jQuery.Autocompleter.defaults.scrollHeight));
    if(h > 0) {
        $("#suggest1").setOptions({
			scrollHeight: h
		});
    }
}

function launchAp(type, imgId, outid) {

    var catid = outid.replace(/-.*/,"");

    //check the box if it's unchecked
    linkIndex = parseInt(outid.split("-")[1]);
    if (document.getElementById(catid).param[linkIndex-1].checked == false){
    document.getElementById(catid).param[linkIndex-1].checked = true;
    }
    showError(catid, "");
    pdfString = ""; 
    svgString = "";
    clearString = "<a class='header' onClick='JavaScript:toggleclearbelow(0, \""+outid+"\")' style='cursor:pointer'>Remove Image</a>";
    outids = outid.replace(/-.*/,"");
    StartDate = document.getElementById(outids).yearo.value + document.getElementById(outids).montho.value + document.getElementById(outids).dayo.value;
    EndDate = document.getElementById(outids).yearf.value + document.getElementById(outids).monthf.value + document.getElementById(outids).dayf.value;
    PPD = document.getElementById(outids).ppd.value;
    FILTER = document.getElementById(outids).filter.value;

    IMGURL = "http://timeseries.org/cgi-bin/get.cgi?";
    IMGURL = IMGURL + "StartDate=" + StartDate;
    IMGURL = IMGURL + "&EndDate=" + EndDate;
    IMGURL = IMGURL + "&ext=bin&out=jnlp&ppd=";
    IMGURL = IMGURL + PPD + "&filter=" + FILTER;
    IMGURL = IMGURL + "&param1=" + outid;

    //    alert(IMGURL);
    window.open(IMGURL,"_blank");
    
}

function checkForm(form,id){

	if (checkParamSelected(id) && checkOther()){
	    // alert(form.action());
		form.submit();
	}
}
function checkParamSelected(id){
	var result = false;
	if(document.getElementById(id).param.checked)
	    result = true;
	//alert(id);
	else{
	    for (var i =0 ; i<document.getElementById(id).param.length ; i++){
		if (document.getElementById(id).param[i].checked){
			result = true;
		}
	    }
	}
	
	if (result){
		return true;
	} else {
		alert("No parameter selected.");
		return false;
	}
}
function checkOther(){
        // for example //
	return true;
}

function toggleexpand(toggle,divnum) {
    if (toggle){
	//        document.getElementById("expand"+divnum).style.visibility="visible";
        document.getElementById("expand"+divnum).style.display="block";
    }
    else {
        document.getElementById("expand"+divnum).style.display="none";
    }
}

function toggleclearbelow(toggle,divnum) {
   var catid = divnum.replace(/-.*/,"");
   linkIndex = parseInt(divnum.split("-")[1]); 
   if (toggle){
	document.getElementById("clearbelow"+divnum).style.display="block";
	document.getElementById("xresult"+divnum).style.display="block";
	document.getElementById("ac_me"+divnum).style.display="block";
	//document.getElementById("ac"+divnum).style.display="none";
    }
    else {        
	//document.getElementById("clearbelow"+divnum).style.visibility="hidden";
	document.getElementById("clearbelow"+divnum).style.display="none";
	//document.getElementById("xresult"+divnum).style.visibility="hidden";
	document.getElementById("xresult"+divnum).style.display="none";
	document.getElementById("ac"+divnum).style.display="none";
	//	document.getElementById("xresultmore2" + divnum).display = "none";

	//	document.getElementById("ac_me" + divnum).display = "none";
	document.getElementById("xresultmore2"+divnum).style.display="none";
	document.getElementById("xresult" + divnum).innerHTML = "";
	document.getElementById("xresultmore2" + divnum).innerHTML = "";
	document.getElementById("ac_me" + divnum).innerHTML = "";
	if(document.getElementById("ac" + divnum).style.display=="none"){
		//clearn textfield content
	   	document.getElementById("ac_me"+divnum).value="";
		document.getElementById("ac_me"+divnum).style.display="none";
		//document.getElementById("ac" + divnum).style.visibility="hidden";

	}
	//hide overview and histogram
	//document.getElementById("ov"+divnum).style.visibility= "hidden";
	//	document.getElementById("ov"+divnum).style.display= "none";
      
    	if (document.getElementById(catid).param.checked ==true ){
        	document.getElementById(catid).param.checked = false;
    	}
    	else if (document.getElementById(catid).param[linkIndex-1] != null && document.getElementById(catid).param[linkIndex-1].checked == true){
        	document.getElementById(catid).param[linkIndex-1].checked = false;
    	}
   }

   var flag=0;
   field = document.getElementById(catid).param;
   for (i = 0; i < field.length; i++)
        if (field[i].checked == true)
           flag=1;

   if (flag==0)
     document.getElementById(catid).clearSelected.style.visibility="hidden"; 
}

function togglecheckall(toggle) {
    if (toggle){
	document.getElementById("CheckAll").style.visibility="hidden";
    }
}

function updatepage(str,divnum){
    document.getElementById("xresult" + divnum).innerHTML = "<br>"+str+"";
        
}

function checkAll(id,num)
{

    field = document.getElementById(id).param;
for (i = 0; i < field.length; i++)
	field[i].checked = true;
        document.getElementById("CheckAll"+num).value="Unselect All";
        document.getElementById("CheckAll"+num).onclick = function onclick(event) {uncheckAll(id,num)};
}

function uncheckAll(id,num)
{
for (i = 0; i < field.length; i++)
	field[i].checked = false;

        document.getElementById("CheckAll"+num).value="Select All";
        document.getElementById("CheckAll"+num).onclick = function onclick(event) {checkAll(id,num)};

}

function loadXMLDoc(fname)
{
var xmlDoc;
// code for IE
if (window.ActiveXObject)
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  }
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation 
&& document.implementation.createDocument)
  {
  xmlDoc=document.implementation.createDocument("","",null);
  }
else
  {
  alert('Your browser cannot handle this script');
  }
xmlDoc.async=false;
xmlDoc.load(fname);
return(xmlDoc);
}

function displayResult(divnum)
{
fxsl = "/tmp/tinydict.xsl";
fxml = "/tmp/tinyrend.xml";
//fxsl = "/timeseries/xsl/spase-combined.xsl";
//fxml = "/timeseries/data/SourceAcronym/Subset/SourceAcronym_Subset-1-v0-SPASE-0.xml";
outid = "xresult" + divnum;

xml=loadXMLDoc(fxml);
xsl=loadXMLDoc(fxsl);
// code for IE
if (window.ActiveXObject)
  {
  ex=xml.transformNode(xsl);
  document.getElementById(outid).innerHTML=ex;
  }
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation 
&& document.implementation.createDocument)
  {
  xsltProcessor=new XSLTProcessor();
  xsltProcessor.importStylesheet(xsl);
  resultDocument = xsltProcessor.transformToFragment(xml,document);
document.getElementById(outid).appendChild(resultDocument);
//kids = document.getElementById(outid);
//alert(kids);
//document.getElementById(outid).style.visibility = "hidden";
//alert(kids.length);
//document.getElementById(outid).removeChild(kids[0]);
//result    = resultDocument.getElementsByTagName('DICTIONARY')[0].firstChild.data;
//updatepage(result,divnum);
  }
    toggleclearbelow(1,divnum);
}

/// kokovin ////

function deleteLoading(id) {
    if(document.getElementById(id) != null)
	document.getElementById(id).style.visibility="hidden";
}

function updateSpan(str,spanId){
  if (str!=""){
      document.getElementById(spanId).innerHTML = str;
    //document.getElementById(spanId).innerHTML = "<table border=1 cellpadding=2 
    //cellspacing=2><tr><td>"+str+"</td></tr></table>";
  } else {
    document.getElementById(spanId).innerHTML = "";
  }     
}

function displayXmlResult(type, xmlUr, outid){

clearString = "<a onClick='JavaScript:toggleclearbelow(0, \""+outid+"\")' style='cursor:pointer'>Remove Information</a>";
idnum = outid;
outid = "xresult" + outid;
fxml = xmlUr;
if (type == "spase"){
  fxsl = "http://aurora.gmu.edu/tmp/spase3.xsl";
} else {
  fxsl = "error.xsl";
}

xml=loadXMLDoc(fxml);
xsl=loadXMLDoc(fxsl);

 if (window.ActiveXObject) { // code for IE
  ex=xml.transformNode(xsl);
  document.getElementById(outid).innerHTML=ex;
 } else {  // code for Mozilla, Firefox, Opera, etc.
 if (document.implementation && document.implementation.createDocument) {
   xsltProcessor=new XSLTProcessor();
   xsltProcessor.importStylesheet(xsl);
   resultDocument = xsltProcessor.transformToFragment(xml,document);
   toggleclearbelow(1,idnum);
   updateSpan("",outid);
   updateSpan(clearString,outid);
   document.getElementById(outid).appendChild(resultDocument);
  }
 }

}


function displayImgResult(type, imgId, outid){
    tmpstr2 = outid.replace(/-.*/,"");
    tmpstr1 = tmpstr2.replace(/_/g,"/");    
    BASEURLfull = BASEURL + tmpstr1 + "/figures" + "/" + tmpstr2;

       pdfString = "<a class=\"header\" href=\"" + BASEURLfull + imgId + ".pdf\">pdf</a>";
       clearString = "<a class='header' onClick='JavaScript:toggleclearbelow(0, \""+outid+"\")' style='cursor:pointer'>Remove Image</a>";

     if (type==1){
	expandString = "| " + clearString + " | ";
	//var widthheightEndIndex = BaseURLfull.indexOf("&", BaseURLfull.indexOf("height=")+1);
	//BASEURL4large = BASEURLfull.replace(BASEURLfull.subString(BASEURLfull.indexOf("width="), widthheightEndIndex), "width=1024&height=768"); 
	 expandString = expandString + "<a class='header' onClick='JavaScript:displayImgResult(0, \""+imgId+"\", \""+outid+"\")' style='cursor:pointer'>Smaller size</a>";

       	expandString = expandString + " | " + pdfString + " | ";
       	strURL = expandString + "<br><img src=\"" + BASEURLfull + imgId + ".png\"/>";
     } else {
	 expandString = "| " + clearString + " | "; 
	expandString = expandString + "<a class='header' onClick='JavaScript:displayImgResult(1, \""+imgId+"\", \""+outid+"\")' style='cursor:pointer'>Larger size</a>";
       expandString = expandString + " | " + pdfString + " |";
       strURL = expandString + "<br><img src=\"" + BASEURLfull + imgId + "_s.png\"/>";
     }
     updateSpan(strURL,"xresult" + outid );

     toggleclearbelow(1,outid);
}


function displayApResult(type, imgId, outid) {

    var catid = outid.replace(/-.*/,"");

    //check the box if it's unchecked
    linkIndex = parseInt(outid.split("-")[1]);
    if (document.getElementById(catid).param.checked == false){
	document.getElementById(catid).param.checked = true;
    }
    else if (document.getElementById(catid).param[linkIndex-1] != null && document.getElementById(catid).param[linkIndex-1].checked == false){
	document.getElementById(catid).param[linkIndex-1].checked = true;
    }
    showError(catid, "");
    pdfString = ""; 
    svgString = "";
    //clearString = "<a class='header' onClick='JavaScript:toggleclearbelow(0, \""+outid+"\")' style='cursor:pointer'>Remove Image</a>";
    outids = outid.replace(/-.*/,"");
    StartDate = document.getElementById(outids).yearo.value + document.getElementById(outids).montho.value + document.getElementById(outids).dayo.value;
    EndDate = document.getElementById(outids).yearf.value + document.getElementById(outids).monthf.value + document.getElementById(outids).dayf.value;
    PPD = document.getElementById(outids).ppd.value;
    FILTER = document.getElementById(outids).filter.value;

    //    alert(outids);

    //    IMGURL = "http://virbo.org:8080/AutoplotServlet/SimpleServlet?url=http%3A%2F%2Fwww.sarahandjeremy.net%2F%7Ejbf%2F1wire%2Fdata%2F2007%2F0B000800408DD710.%25Y%25m%25d.d2s%3Ftimerange%3D20071210";
    //StartDate=20010101&EndDate=20010101&ext=bin&ppd=24&param1=SourceAcronym_Subset-1-v0
    IMGURL = "http://virbo.org/AutoplotServlet/SimpleServlet?url=tsds.http%3A%2F%2Ftimeseries.org%2Fget.cgi%3F";
    var IMGcacheURL = "http://virbo.org/cache/AutoplotServlet/SimpleServlet?url=tsds.http%3A%2F%2Ftimeseries.org%2Fget.cgi%3F";
    if(document.getElementById(catid).defaultChecker.value==1)  //date has been changed
    	IMGURL = IMGURL + "StartDate%3D" + StartDate;
    else	//date has not been changed
	IMGURL = IMGcacheURL + "StartDate%3D" + StartDate;

    IMGURL = IMGURL + "%26EndDate%3D" + EndDate;
    IMGURL = IMGURL + "%26ext%3Dbin%26out%3Dtsml%26ppd%3D";
    IMGURL = IMGURL + PPD + "%26filter%3D" + FILTER;
    IMGURL = IMGURL + "%26param1%3D" + outid;

    var widthid = "width"+''+outids;
    var heightid = "height"+''+outids;
    //    var widthfdid = "widthfd" + ''+outids;
    //    var heightfdid = "heightfd"+''+outids;
    var widthfdid = "widthfd";
    var heightfdid = "heightfd";
    if(catid!=null && document.getElementById("xresultmore"+catid)!=null && document.getElementById("xresultmore" + catid).innerHTML!="" && document.getElementById(widthfdid).value !="" && document.getElementById(heightfdid).value !=""){
	IMGURL = IMGURL + "&width=" + document.getElementById(widthfdid).value;
        IMGURL = IMGURL + "&height=" + document.getElementById(heightfdid).value;
    }
    else {
    	IMGURL = IMGURL + "&width=" + document.getElementById(widthid).value;
    	IMGURL = IMGURL + "&height=" + document.getElementById(heightid).value;
    }
    pdfString = "<a class='header' href=\"" + IMGURL + "&format=application%2Fpdf"+ "\" TARGET=\"_blank\">pdf</a>";
    svgString = "<a class='header' href=\"" + IMGURL + "&format=image%2Fsvg%2Bxml"+ "\" TARGET=\"_blank\">svg</a>";

    if(catid!=null && document.getElementById("xresultmore"+catid)!=null && document.getElementById("xresultmore" + catid).innerHTML!=""){
        IMGURL += "&process=" + encodeURIComponent(document.getElementById("filter"+catid).value);
	IMGURL += "&renderType=" + encodeURIComponent(document.getElementById("renderType"+catid).value);
	IMGURL += "&color=" + encodeURIComponent(document.getElementById("color"+catid).value);
        IMGURL += "&fillcolor=" + encodeURIComponent(document.getElementById("fillColor"+catid).value);
        IMGURL += "&foregroundColor=" + encodeURIComponent(document.getElementById("foregroundColor"+catid).value);
        IMGURL += "&backgroundColor=" + encodeURIComponent(document.getElementById("backgroundColor"+catid).value);
        IMGURL += "&column=" + encodeURIComponent(document.getElementById("column"+catid).value);
        IMGURL += "&row=" + encodeURIComponent(document.getElementById("row"+catid).value);
        //IMGURL += "&autolayout"
        //IMGURL += "&sparkline"
        IMGURL += "&font=" + encodeURIComponent(document.getElementById("font"+catid).value);
	
	pdfString = "<a class=\"header\" href=\"" + IMGURL + "&format=application%2Fpdf"+ "\" TARGET=\"_blank\">pdf</a>";
	svgString = "<a class=\"header\" href=\"" + IMGURL + "&format=image%2Fsvg%2Bxml"+ "\" TARGET=\"_blank\">svg</a>";
	var format = encodeURIComponent(document.getElementById("format"+outids).value);
        IMGURL += "&format=" + encodeURIComponent(document.getElementById("format"+catid).value);
    }
    else{ //'more option' is not expanded
	IMGURL += "&column=5em%2C100%25-10em&row=3em%2C100%25-3em&font=sans-14";
	IMGURL += "&color=%230000ff";
    }
    //make "Remove Selected" visible if not
    //    alert(document.getElementById(catid));
    document.getElementById(catid).clearSelected.style.visibility="visible";
    
    if (type==1 || type==-1){
	//expandString = "<br>" + "| " + clearString + " | "; 
        expandString = "<a class='header' onClick='JavaScript:displayApResult(0, \""+imgId+"\", \""+outid+"\")' style='cursor:pointer'>Larger size</a>";
        expandString = expandString + " | " + pdfString + " | " + svgString + "<br>";
	strURL = expandString + "<img onload=\"deleteLoading('loading"+outid+"');\" src=\"" + IMGURL + "\"/>";
    } else {
        //expandString = "| " + clearString + " | ";
        expandString = "<a class=\"header\" onClick='JavaScript:displayApResult(1, \""+imgId+"\", \""+outid+"\")'  style='cursor:pointer'>Smaller size</a>";
        expandString = expandString + " | " + pdfString +  " | " + svgString + "<br>";
        var widthheightEndIndex = IMGURL.indexOf("&", IMGURL.indexOf("height=")+1);
        IMGURL4large = IMGURL.replace(IMGURL.substring(IMGURL.indexOf("width="), widthheightEndIndex), "width=1024&height=768");
        strURL = expandString + "<img onload=\"deleteLoading('loading"+outid+"');\" src=\"" + IMGURL4large + "\"/>";
    }
    if(format!=null && (format=="application%2Fpdf" || format=="image%2Fsvg%2Bxml")){
	//alert(IMGURL);
	window.open(IMGURL,"_blank");
    }
    else{
	//set autocomplete field visible
	//	document.getElementById("ac"+outid).style.visibility="visible";
	document.getElementById("ac"+outid).style.display="block";
	loadingURL = "<img id='loading" + outid + "' src='http://virbo.org/wiki/images/loading.gif'>";
    	updateSpan(strURL+loadingURL,"xresult" + outid);
    	toggleclearbelow(1,outid);
    }

    //show overview and histogram
    //document.getElementById("ov"+outid).style.visibility= "visible";
    
    //switch text between 'Plot' and 'Remove Image' 
    plotLink = document.getElementById("plot"+outid); 
    if(plotLink != null && plotLink.innerHTML == "Plot"){
    	plotLink.innerHTML="Remove Image";
    }
    else if (type==-1){
    	plotLink.innerHTML="Plot";
	toggleclearbelow(0, outid);
    }
}

function displayApMoreResult(type, outid, compareId) {

    var catid = outid.replace(/-.*/,"");
    //clearString = "<a onClick='JavaScript:toggleclearbelow(0, \""+outid+"\")' style='cursor:pointer'>Remove Image</a>";
    outids = outid.replace(/-.*/,"");
    var compids = compareId.replace(/-.*/,"");
    StartDate = document.getElementById(outids).yearo.value + document.getElementById(outids).montho.value + document.getElementById(outids).dayo.value;
    EndDate = document.getElementById(outids).yearf.value + document.getElementById(outids).monthf.value + document.getElementById(outids).dayf.value;
    PPD = document.getElementById(outids).ppd.value;

    IMGURL = "http://virbo.org/AutoplotServlet/SimpleServlet?url=tsds.http%3A%2F%2Ftimeseries.org%2Fget.cgi%3F";
    IMGURL = IMGURL + "StartDate%3D" + StartDate;
    IMGURL = IMGURL + "%26EndDate%3D" + EndDate;
    IMGURL = IMGURL + "%26ext%3Dbin%26out%3Dtsml%26ppd%3D";
    //IMGURL = IMGURL + PPD + "%26param1%3D" + "OMNI_" +compareId + "-1-v0";
    IMGURL = IMGURL + PPD + "%26param1%3D" + compareId;

    var widthid = "width"+''+outids;
    var heightid = "height"+''+outids;
    IMGURL = IMGURL + "&width=" + document.getElementById(widthid).value;
    IMGURL = IMGURL + "&height=" + document.getElementById(heightid).value;
    if(document.getElementById("xresultmore"+catid)!=null && document.getElementById("xresultmore" + catid).innerHTML!=""){
        IMGURL += "&color=" + encodeURIComponent(document.getElementById("color"+outids).value);
        IMGURL += "&fillcolor=" + encodeURIComponent(document.getElementById("fillColor"+outids).value);
        IMGURL += "&foregroundColor=" + encodeURIComponent(document.getElementById("foregroundColor"+outids).value);
        IMGURL += "&backgroundColor=" + encodeURIComponent(document.getElementById("backgroundColor"+outids).value);
        IMGURL += "&column=" + encodeURIComponent(document.getElementById("column"+outids).value);
        IMGURL += "&row=" + encodeURIComponent(document.getElementById("row"+outids).value);
        //IMGURL += "&autolayout"
        //IMGURL += "&sparkline"
	IMGURL += "&format=" + encodeURIComponent(document.getElementById("format"+outids).value);
        IMGURL += "&font=" + encodeURIComponent(document.getElementById("font"+outids).value);
    }
    else{ //'more option' is not expanded
    	IMGURL += "&column=5em%2C100%25-10em&row=3em%2C100%25-3em&font=sans-14";
	IMGURL += "&color=%230000ff";
    
    }

    strURL = "<img onload=\"deleteLoading('loading"+outid+"x');\" src=\"" + IMGURL  + "\"/>"; 
	loadingURL = "<img id='loading" + outid + "x' src='http://virbo.org/wiki/images/loading.gif'>";
    updateSpan(strURL + loadingURL,"xresultmore2"+ outid);
    toggleclearbelow(1,outid);
    
    //make "Remove Selected" visible if not
  //  alert(document.getElementById(catid));
  //  document.getElementById(catid).clearSelected.style.visibility="visible";
    
}

//update dropdown2's selection according to dropdown1's selection
function updateWH(dropdown1, dropdown2){
	var newIndex = dropdown1.selectedIndex;
	dropdown2.selectedIndex = newIndex;
}

function displayMoreOptions(outid){
	idnum = outid;
	outid = "xresultmore" + outid;
	if(document.getElementById(outid).innerHTML==""){
 		expandString = '<br>or other size:&nbsp;&nbsp;&nbsp;&nbsp;Width <input style=\"width:65px;font-family:monospace;font-size:100%\" size="1" value="" id=\"widthfd' + idnum + '\">&nbsp;Height&nbsp;<input style=\"width:65px;font-family:monospace;font-size:100%\" value="" id=\"heightfd' + idnum + '\"><br>';
		expandString +='Sparkline:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"checkbox\" id=\"sparkline' + idnum + '\" value=false></input> <a href=\"http://autoplot.org/layout_specification\">help</a><br>';
		expandString +='Autolayout:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" id="autolayout' + idnum + '" value="false"></input> <a href=\"http://autoplot.org/layout_specification\">help</a><br>';
		expandString +='Other filter:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select class="gray" name="otherFilter" id="filter' + idnum + '" style=\"width: 148px;\"  onchange=defaultCheck(\"' + idnum + '\") ><option selected></option><option value="histogram">histogram</option><option value="magnitude(fft)">magnitude(fft)</option></select><br>';
		expandString +='Style:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select class=\"gray\" name="renderType" id="renderType' + idnum + '" style="width:148px"   onchange=defaultCheck(\"' + idnum + '\")>';
		expandString +='<option selected></option><option>spectrogram</option><option>series</option>';
		expandString +='<option>scatter</option><option>stairs</option><option>fill_to_zero</option>';
		expandString +='</select><br>';
		expandString +='Line color:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select class=\"gray\" style="width:148px" name="linecolor" id=\"color' + idnum + '\"  onchange=defaultCheck(\"' + idnum + '\")><option selected value="#0000ff">blue</option><option value="#00ff00">green</option><option value="##ff0000">red</option></select><br>';
		expandString +='FillColor:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select class=\"gray\" style="width:148px" name="fillcolor" id=\"fillColor' + idnum + '\" style=\"width: 148;\"  onchange=defaultCheck(\"' + idnum + '\") ><option selected value="#000000">black</option><option value="#00ff00">green</option><option value="##ff0000">red</option></select><br>';
//<input id=\"fillColor' + idnum + '\" value=\"#aaaaff\"><br>';
		expandString +='Foreground:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select class=\"gray\" style="width:148px" name="foregroundColor" id=\"foregroundColor' + idnum + '\" style=\"width: 148;\"  onchange=defaultCheck(\"' + idnum + '\")><option selected value="#000000">black</option><option value="#00ff00">green</option><option value="##ffff00">yellow</option></select><br>';
//<input id=\"foregroundColor' + idnum + '\" value=\"#ffffff\"><br>';
		expandString +='Background:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select class="gray" style="width:148px" name="backgroundColor" id=\"backgroundColor' + idnum + '"  onchange=defaultCheck(\"' + idnum + '\")><option selected value="#ffffff">white</option><option value="#0000ff">blue</option><option value="#000000">black</option></select><br>';
//<input id=\"backgroundColor' + idnum + '\" value=\"#000000\"><br>';
		expandString +='Horiz position:&nbsp;&nbsp;&nbsp;<input class="gray" style="width:146px" id="column' + idnum + '" value="5em,100%-10em"> <a href="http://www.autoplot.org/autoplot/index.php/Discussion#Layout_Specification">help</a><br>';
		expandString +='Vert position:&nbsp;&nbsp;&nbsp;&nbsp;<input class="gray" style="width:146px" id="row' + idnum + '" value="3em,100%-3em"> <a href="http://www.autoplot.org/autoplot/index.php/Discussion#Layout_Specification">help</a><br>';
		expandString +='Output format:&nbsp;&nbsp;&nbsp;&nbsp;<select class="gray" style="width:148px" name="format" id="format' + idnum + '"  onchange=defaultCheck(\"' + idnum + '\")><option>image/png</option><option>application/pdf</option><option>image/svg+xml</option></select><br>';
		expandString +='Font:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input class="gray" style="width:146px" id="font' + idnum + '" value="sans-14"><br>';

		//expandString +='Filter:           <select id="filter' + idnum + '" style="width:148"><option value="mean">none</option><option value="numbervalid">Number valid</option><option value="max">Maximum</option><option value="min">Minimum</option></select>';
		
		updateSpan(expandString, outid);
		document.getElementById("moreOption"+idnum).innerHTML = "Hide more options";
		//show overview span
		fields = getElementsByClass(document.getElementById(idnum),'ov', '*');
		for (i=0; i<fields.length; i++){
			//alert(fields[i]);
		    fields[i].style.visibility = "visible";
		    //fields[i].style.display = "block";
		}
	}
	else{
		updateSpan("", outid);
		document.getElementById("moreOption"+idnum).innerHTML = "Show more options";
		//hide overview span
		fields = getElementsByClass(document.getElementById(idnum),'ov', '*');
		                for (i=0; i<fields.length; i++)
		                        fields[i].style.visibility = "hidden";

		//                for (i=0; i<fields.length; i++)
		//			fields[i].style.display = "none";

	}
}

/**
function sparklineWH(){ 
	if (document.getElementById("sparkline"+idnum).checked){
		document.getElementById("heightfd"+idnum).disabled=false;
		document.getElementById("widthfd"+idnum).disabled=false;
	}
	else{
		document.getElementById("widthfd"+idnum).disabled=true;
		document.getElementById("heightfd"+idnum).disabled=true;
	}
}
**/

function displayHtmResult(type, imgId, outid){
    strURL = "http://virbo.org/virbo/viewPrintData.jsp?docname=";
    strURL = strURL + outid + "-SPASE-0";
    strURLh = "<p><a href=" + strURL + ">" + strURL + "</a>";
    strURL='<iframe id="ifrm" name="ifrm" src="'+strURL+'" scrolling="auto" width="100%" height="400" frameborder="0"></iframe>';
    clearString = "<p><a class='header' onClick='JavaScript:toggleclearbelow(0, \""+outid+"\")' style='cursor:pointer'>Remove Information</a>";
    strURL = clearString + strURLh + strURL;
    updateSpan(strURL,"xresult" + outid);

    toggleclearbelow(1,outid);
    plotLink = document.getElementById("plot"+outid);
      if(plotLink != null && plotLink.innerHTML == "Remove Image"){
           plotLink.innerHTML="Plot";
         }
}

function plotSelected(catid){
	field = document.getElementById(catid).param;
	var apValues = new Array(1);
	apValues[0] = "";
	var hasSelection = false;
	if(field.checked) {
		displayApResult(1,"-1-v0",catid+"-1-v0");
                apValues.push(catid+"-1-v0");
               	hasSelection = true;
	}
	else{
		for (var i = 0; i < field.length; i++){
        		if(field[i].checked){
				displayApResult(1,"-"+(i+1)+"-v0",catid+"-"+(i+1)+"-v0");
				apValues.push(catid+"-"+(i+1)+"-v0");
				hasSelection = true;
		
			}
		}
	}
	if(hasSelection == false){
		showError(catid, "Please select at least one parameter.<br>");
		return false;
	}
	else
		showError(catid, "");
	valueList = document.getElementById(catid).apMoreValues.value.split(",");
	for (var i = 0; i<valueList.length; i++){
		if(valueList[i] != "")
			displayApMoreResult(1,apValues[i+1],valueList[i]);
	}
}

//autocomplete functions
function selectItem(li) {
        if (li.extra) {
                //alert("That's '" + li.extra[0] + "' you picked.")
        }
}
function formatItem(row) {
        return row[0] + "<br>";
}
//end of autocomplete functions


//check if default value of dropdown has been changed by user
function defaultCheck(formName){
	//document.getElementById(formName).defaultChecker.value=1;
	//change button text 
	var form = document.getElementById(formName);
	var valueArray = form.defaultChecker.value.split(",");
	var flag = (valueArray.length>1 && form.yearo.selectedIndex == valueArray[0] && form.montho.selectedIndex == valueArray[1]
                && form.dayo.selectedIndex  == valueArray[2] && form.yearf.selectedIndex == valueArray[3]
                && form.monthf.selectedIndex == valueArray[4] && form.dayf.selectedIndex == valueArray[5]
                && form.ppd.selectedIndex == valueArray[6] && form.ext.selectedIndex == valueArray[7]
                && form.filter.selectedIndex == valueArray[8] && form.width.selectedIndex == valueArray[9]
                && form.height.selectedIndex == valueArray[10] );
	if(document.getElementById("moreOption"+formName).innerHTML == "Show more options" ){
		if ( flag )
			form.PlotSelected.value = "Plot Selected";
		else{
                	form.PlotSelected.value = "Update Selected";
                	form.updateSelected.style.visibility = "visible";
        	}

	}
	else {		//more option is expanded
		var flagMore =  flag && form.otherFilter.selectedIndex == valueArray[11]
                && form.renderType.selectedIndex == valueArray[12] && form.linecolor.selectedIndex == valueArray[13]
                && form.fillcolor.selectedIndex == valueArray[14] && form.foregroundColor.selectedIndex == valueArray[15]
                && form.backgroundColor.selectedIndex == valueArray[16] && form.format.selectedIndex == valueArray[17];
		if (flagMore )
			form.PlotSelected.value = "Plot Selected";
		else{	
			form.PlotSelected.value = "Update Selected";
			form.updateSelected.style.visibility = "visible";
		}
	}
}

function clearSelectedPlots(formName) {
	field = document.getElementById(formName).param;
	if(field.checked == true){
		document.getElementById("plot"+formName+"-1-v0").innerHTML="Plot";
                toggleclearbelow(0, formName+"-1-v0");
	}
	else{
		for (var i = 0; i < field.length; i++){
			if(field[i].checked){
				document.getElementById("plot"+formName+"-"+(i+1)+"-v0").innerHTML="Plot";
                                toggleclearbelow(0,formName+"-"+(i+1)+"-v0");
			}
		}
	}
}

function showError(catid, displayStr) {
	document.getElementById("error"+catid).style.visibility="visible";
	document.getElementById("error"+catid).innerHTML=displayStr;
}

function getElementsByClass(node, searchClass,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
