// javascript

//include(jslib_remotefile);

	// TODO: switch saveURL to something else! and check for exists
	// see if build required and copy build down
	//try {saveURL("chrome://unilateralpatch/content/build.xml", "build.xml", null, null, true, null);}
	//catch(e){alert(e);}

	// open, read 
	// write local
	// run ant script (? event handler?)
	// load back to page	

var pl;
function up_init() {
	// set up platform specific temp directory
	var platform = navigator.platform;
	if(/win/i.test(platform)){pl = "c:\\tmp\\";}
	else{pl = "/tmp/";}
}

function mSaveInternal(aURL, aDocument, 
                      aFileName, aFilePickerTitleKey,
                      aShouldBypassCache, aSkipPrompt,
                      aReferrer)
{
  if (aSkipPrompt == undefined)
    aSkipPrompt = false;
  alert('local!');
  var data = {
    url: aURL,
    fileName: aFileName,
    filePickerTitle: aFilePickerTitleKey,
    document: aDocument,
    bypassCache: aShouldBypassCache,
    window: window,
    referrer: aReferrer
  };
  var sniffer = new nsHeaderSniffer(aURL, mFoundHeaderInfo, data, aSkipPrompt);
}

function unilateral_patch() {
	// get document and image ref
	var imw = window._content;
	var imd = window._content.document;
	if (!imd.images || !imd.images.length){alert("No images to patch.");return true;}
	var imageName;
	var imageRefs = new Array(imd.images.length);	
	

	// try get local file read access
	try {a=netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");}
	catch (e) {alert('Local File processing disabled. Remote file processing required..');}

	// save locally.. save file
	// loop
		//imageRef = new File(pl+"image.jpg");
	try {
		//(aURL, aFileName, aFilePickerTitleKey, aShouldBypassCache, aSkipPrompt, aReferrer)
		imageName = imd.images[0].src;
		imageName = getNameFromURL(imageName);
		// if exists, add number and update write images array
		// turn off prompt
		saveURL(imd.images[0].src, imageName, null, false, true, null);
		// update images array
		imageRefs[0]=imageName;
	}
	catch (e) {
		alert(e);
		// todo: consider appending to end message
		// Failure to get an image is non-fatal
	}

	// run ant script (? event handler?)
	//var antArgs='-f /tmp/up/build.xml -l /tmp/up/log -v';
	var antArgs=new Array('-f', '/tmp/up/build.xml', '-l', '/tmp/up/log', '-v');
	startAntProcess(antArgs);
	// or perform javascript regex on data before write?
	
	// TODO: experimenting with rewriting saveDocument.. etc etc to set save as web archive	
	// load back to page
	// loop and write back images
	var saveDir="file:///Users/timplaisted/Desktop/";
	var saveDoc=imw.location.href;
	saveDoc=getNameFromURL(saveDoc);
	try{
		//saveDocument(imw, true);
		mSaveInternal(imw.location.href,imw,false,true);
	} catch (e) {'save error'+alert(e);}
	
	try {
		//var mybasehref = imw.location.href;
		imw.location.href=saveDir+saveDoc;
		//var docbase = imd.getElementsByTagName("base");
		//if (docbase[0]){docbase[0].href = mybasehref;}
	}
	catch (e) {
		alert('Local read failed. '+e);
	}
	//reload images
	alert(saveDir+imageName);
	_content.document.images[0].src = saveDir+imageRefs[0];
	alert("after save+write attempt");

	//for(var i=0; i < imd.images.length; i++) {
	//	imd.images[i].src = saveDir.imageName;
	//}

	// some point.. i should remove them?
	// on time out?
	// for show, maybe not??
}

function getNameFromURL(nURL) {
	return nURL.substring(nURL.lastIndexOf("/")+1,nURL.length);
}

// local overload of contentAreaUtils
function mFoundHeaderInfo(aSniffer, aData, aSkipPrompt)
{
  var contentType = aSniffer.contentType;
  var contentEncodingType = aSniffer.contentEncodingType;

  var shouldDecode = false;
  // Are we allowed to decode?
  try {
    const helperAppService =
      Components.classes["@mozilla.org/uriloader/external-helper-app-service;1"].
        getService(Components.interfaces.nsIExternalHelperAppService);
    var url = aSniffer.uri.QueryInterface(Components.interfaces.nsIURL);
    var urlExt = url.fileExtension;
    if (helperAppService.applyDecodingForExtension(urlExt,
                                                   contentEncodingType)) {
      shouldDecode = true;
    }
  }
  catch (e) {
  }

  var isDocument = aData.document != null && isDocumentType(contentType);
  if (!isDocument && !shouldDecode && contentEncodingType) {
    // The data is encoded, we are not going to decode it, and this is not a
    // document save so we won't be doing a "save as, complete" (which would
    // break if we reset the type here).  So just set our content type to
    // correspond to the outermost encoding so we get extensions and the like
    // right.
    contentType = contentEncodingType;
  }
  
  var file = null;
  var saveAsType = kSaveAsType_URL;
  try {
    file = aData.fileName.QueryInterface(Components.interfaces.nsILocalFile);
  }
  catch (e) {
    var saveAsTypeResult = { rv: 0 };
    file = getTargetFile(aData, aSniffer, contentType, isDocument, aSkipPrompt, saveAsTypeResult);
    if (!file)
      return;
    saveAsType = saveAsTypeResult.rv;
  }

  // If we're saving a document, and are saving either in complete mode or 
  // as converted text, pass the document to the web browser persist component.
  // If we're just saving the HTML (second option in the list), send only the URI.
  // var source = (isDocument && saveAsType != kSaveAsType_URL) ? aData.document : aSniffer.uri;
  var source = aData.document; // amend
  var persistArgs = {
    source      : source,
    contentType : (isDocument && saveAsType == kSaveAsType_Text) ? "text/plain" : contentType,
    target      : makeFileURL(file),
    postData    : aData.document ? getPostData() : null,
    bypassCache : aData.bypassCache
  };
  
  var persist = makeWebBrowserPersist();

  // Calculate persist flags.
  const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
  const flags = nsIWBP.PERSIST_FLAGS_NO_CONVERSION | nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
  if (aData.bypassCache)
    persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_BYPASS_CACHE;
  else 
    persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE;

  if (shouldDecode)
    persist.persistFlags &= ~nsIWBP.PERSIST_FLAGS_NO_CONVERSION;
    
  // Create download and initiate it (below)
  var dl = Components.classes["@mozilla.org/download;1"].createInstance(Components.interfaces.nsIDownload);

  if (isDocument && saveAsType != kSaveAsType_URL) {
    // Saving a Document, not a URI:
    var filesFolder = null;
    if (persistArgs.contentType != "text/plain") {
      // Create the local directory into which to save associated files. 
      filesFolder = file.clone();
      
      var nameWithoutExtension = filesFolder.leafName;
      nameWithoutExtension = nameWithoutExtension.substring(0, nameWithoutExtension.lastIndexOf("."));
      var filesFolderLeafName = getStringBundle().formatStringFromName("filesFolder",
                                                                       [nameWithoutExtension],
                                                                       1);

      filesFolder.leafName = filesFolderLeafName;
    }
      
    var encodingFlags = 0;
    if (persistArgs.contentType == "text/plain") {
      encodingFlags |= nsIWBP.ENCODE_FLAGS_FORMATTED;
      encodingFlags |= nsIWBP.ENCODE_FLAGS_ABSOLUTE_LINKS;
      encodingFlags |= nsIWBP.ENCODE_FLAGS_NOFRAMES_CONTENT;        
    }
    else {
      encodingFlags |= nsIWBP.ENCODE_FLAGS_ENCODE_BASIC_ENTITIES;
    }
    
    const kWrapColumn = 80;
    dl.init(aSniffer.uri, persistArgs.target, null, null, null, persist);
    persist.saveDocument(persistArgs.source, persistArgs.target, filesFolder, 
                         persistArgs.contentType, encodingFlags, kWrapColumn);
  } else {
    dl.init(source, persistArgs.target, null, null, null, persist);
    var referrer = aData.referrer || getReferrer(document)
    persist.saveURI(source, null, referrer, persistArgs.postData, null, persistArgs.target);
  }
}

//new file object factory
const FileFactory = new Components.Constructor("@mozilla.org/file/local;1","nsILocalFile","initWithPath");
function startAntProcess(args) {
//program to start
var str_LocalProgram = "/usr/local/ant/bin/ant";
//try to create file object
try { var obj_Program = new FileFactory(str_LocalProgram); } catch (e) { alert(e) }
//try to create process
try { var obj_Process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess); } catch (e) { alert(e); }
//setup process
obj_Process.init(obj_Program);
//start process
obj_Process.run(false, args, args.length, {});
}
//alert('t');function startAntProcess() {try { var obj_Program = new kFileFactory("/usr/local/ant/bin/ant"); } catch (e) { alert(e) } alert('j');try { var obj_Process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess); } catch (e) { alert(e);}obj_Process.init(obj_Program);args=new Array();args[0]='-l /tmp/log';alert(args.length);obj_Process.run(false, null, 0, {});}startAntProcess();
