/*****************************************
* File: refrigerator.js
* Created: August something
* 
* I interface with server-side load/store functions.
*
==========================================
Modified 9-12 by Hawkeye

FINALLY resolved popupwindow bug!  Hoorah!
==========================================
Modified 9-20 by Hawkeye

* Moved windowing functions to kitchen.js
* Added SaveAs and Load madori functions.
* Save, saveAs, and object save use a common server interface function.

==========================================
Modified 9-24 by Hawkeye

* HTTP POST functionality is completed.

==========================================
******************************************/

/******************************************
 *	
 * Object Request
 * 
 ******************************************/
function requestAnObject( ){
  debug("Requesting...");

  windowPlease( "./index.cfm?type=requestObjectList", "objects", "menubar=no,height=400,width=600,status=yes,scrollbars=yes,resizable=yes", false );
}

function addPart( textData, id, label ){

  var DOMData;

  debug("data recieved...");

  if (textData != null){
    var DOMData = document.embeds[0].window.parseXML(textData, svgDoc);
    // wrapNode( DOMData );
		wrapGroup(DOMData);
    drawingGroup.appendChild( DOMData );
  }
  useTool( selectTool );
}

/*****************************************
 * CREATE A PART - (SAVE A GROUP TO THE DB)
 *****************************************/
function savePart(){
  //  debug("SAVING PART...");
  if ( !selectList.length ){alert("no selection"); return 0;}
  var group = this.selectList[0].group;
  // make sure objects are grouped
  if ( !group || group.svgGroup == drawingGroup){
    alert("Objects must be grouped first.");
    return 0;
  }
  // make sure only one group is selected
  for ( var i=1; i<this.selectList.length; i++ ) {
    if ( this.selectList[i].group != group ) { 
      alert("multiple groups"); 
      return 0;
    }
  }
  // make sure entire group is selected
  for ( var i=0; i<group.objectList.length; i++ ){
    if ( !group.objectList[i].selected ){
      alert("non-selected members");
      return 0;
    }
  }


  selectTool.deselectAllObjects();
  // clone entire group.  Add wrapper to clone.
  var groupCopy = gTool.copyconstructor( group.svgGroup.cloneNode( true ) );
  wrapNode( groupCopy.svgGroup, groupCopy );

	//groupCopy.svgGroup.parentNode.removeChild( groupCopy.svgGroup );
//	drawingGroup.removeChild( groupCopy.svgGroup );
	groupCopy.svgGroup.setAttribute("visibility", "hidden");
	groupCopy.svgGroup.setAttribute("pointer-events", "none");
  

  // translate selection to origin.
  var minx=null, miny=null;
  for ( var i=0; i<groupCopy.objectList.length; i++ ){
    for ( var j=0; j<groupCopy.objectList[i].handles.length; j++ ){
      if ( groupCopy.objectList[i].handles[j].point.x < minx || minx === null ){
	minx = groupCopy.objectList[i].handles[j].point.x;
      }
      if ( groupCopy.objectList[i].handles[j].point.y < miny || miny === null ){
	miny = groupCopy.objectList[i].handles[j].point.y;
      }
    }
  }
  var delta = new Point2D( minx * -1 , miny * -1 );
  for ( var i=0; i<groupCopy.objectList.length; i++ ){
      groupCopy.objectList[i].move( delta );
  }


  	groupCopy.svgGroup.setAttribute("visibility", "visible");
	groupCopy.svgGroup.setAttribute("pointer-events", "");
    var tempstr = '&quot;';
    var objData = document.embeds[0].window.printNode( groupCopy.svgGroup ).replace( /["]/g , tempstr );
	groupCopy.svgGroup.setAttribute("visibility", "hidden");
	groupCopy.svgGroup.setAttribute("pointer-events", "none");


//  drawingGroup.appendChild( groupCopy.svgGroup );
  var winwrite = '<html>';
  winwrite += '<script>var saveObject=null;</script>\n';
  winwrite += '<body>\n';
  winwrite += '<form action="index.cfm" method="POST">\n';
  winwrite += '  <div style="font-size:large;font-weight:bold;">Create a part</div>\n';
  winwrite += '<hr>\n';
  winwrite += '<span style="font-weight:bold">Please give a descriptive label for this object.</span>\n';
  winwrite += '<br>\n';
  winwrite += '<form action="index.cfm" method="POST">\n';
  winwrite += '    <input type="text" name="label" size="20">\n';
  winwrite += '    <input type="submit" value="Go!" onclick="">\n';
  winwrite += '    <input type="hidden" name="data" value="' +objData + '">\n';
  winwrite += '    <input type="hidden" name="type" value="part">\n';
  winwrite += '</form>\n';
  winwrite +='</body></html>\n';

  windowPlease( null, "whatever", "menubar=no,height=20,width=350,status=yes,scrollbars=no,resizable=yes", winwrite);
  popupwin.saveObject = groupCopy;
}

function gogoPostObject( object, label, type ) {    
  object.svgGroup.setAttribute("visibility", "visible");
  object.svgGroup.setAttribute("pointer-events", "");
  var objectSVGString =  document.embeds[0].window.printNode( object.svgGroup );
//  REMOVE THE THING
  object.svgGroup.parentNode.removeChild( object.svgGroup );
  object.destructor();
  gogoGadgetRequest( objectSVGString, label, type);
}
/**************************************************
 *
 *   POST SVG DATA STRING TO SERVER
 *
 *************************************************/
function gogoGadgetRequest( objectSVGString, label, type){
/*
  winString = "./index.cfm?type=" + type + "&label=" + label + "&data=" + objectSVGString;
  windowPlease( winString, "testo", "menubar=no,height=400,width=600,status=yes,scrollbars=yes,resizable=yes", "");
  return 0;
*/

  //var str= /'/g; //'
  //objectSVGString = objectSVGString.replace( str , "%25");
  var httpPost = new ActiveXObject("Microsoft.XMLHTTP");
  httpPost.open("post", "./index.cfm?type="+ type + "&label=" + label, false);
  httpPost.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  httpPost.send("data="+ objectSVGString );
  if (!confirm( "Save operation complete.  Skip debug data?") ){
    alert( "Server Response:\n"+ httpPost.responseText  );
  }
}
/*********************************************
*
*  SAVE Madori
*
**********************************************/
function saveMadori( label, stringOnly ){
  //  debug("save madori please...m_l:"+madori_label);
  // Run a save or a save as...?
  if (label) {
    madori_label = label;
  } else if ( !madori_label ){
    saveAsMadori();
    return 0;
  }
  
  // deselect stuff before saving...
  if (selectList.length > 0){
    selectTool.deselectAllObjects();
  }
  var TEMPCOPY = rootElement.cloneNode(true);

  for (var i=TEMPCOPY.firstChild ; i ; ) {
    if ( i.nodeType == 3 || i.getAttribute("id") != "drawGroup") {
      j=i.nextSibling;
      TEMPCOPY.removeChild(i);
      i=j;
    } else {
      i=i.nextSibling;
    }
  }
  TEMPCOPY.firstChild.setAttribute("id", "madori");
  var madoriString =  document.embeds[0].window.printNode( TEMPCOPY );
  //  alert(madoriString);

  if ( !stringOnly ){
    gogoGadgetRequest( madoriString , madori_label , "saveMadori" );
  }
  return madoriString;
}

function saveAsMadori(){
  windowPlease("./index.cfm?type=saveAsMadori","window","menubar=no,height=400,width=600,status=yes,scrollbars=yes,resizable=yes","");
}

/*********************************************
*
*  LOAD Madori
*
**********************************************/
function loadMadori(){
  // debug("load madori please...");
  windowPlease("./index.cfm?type=listMadori", "load", "menubar=no,height=400,width=600,status=yes,scrollbars=yes,resizable=yes","");
}
function runLoadMadori(madori_data, id, label){
  if (!madori_data){
    alert("no data!");
    return 0;
  }
  //  debug("madori load label:"+label);
  madori_label = label;

  //  alert("returned SVG:\n"+madori_data );

  // get saved drawing data.  
  // replace current drawing with saved data.
  var DOMData = document.embeds[0].window.parseXML(madori_data, svgDoc);
  var drawing = DOMData.firstChild.firstChild;
  drawing.setAttribute("id","drawGroup");
  rootElement.removeChild(drawingGroup);
  rootElement.appendChild(drawing);
  drawingGroup=drawing;

  // remove current Wall Masks.
  for ( var d = wallMask.objectList.pop() ; d ; d = wallMask.objectList.pop() ){
    d.destructor();
  }
  // apply custom methods to SVG objects.
  // wrapNode( drawing );
	wrapGroup(drawing);	
  
	useTool( selectTool );
}
