//
// Copyright (c) 2007  TigerMe LLC. All rights reserved
// Identification:   "TigerMe" -0008-2007-0000-youi
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  1. A license agreement from TigerMe LLC
//

var _URI_=document.location.protocol+
  "\057\057"+document.location.hostname+":"+document.location.port;

var _XMIME_="/sys/xlib/mime/";
var _AGENT_="";

if(navigator.userAgent.indexOf("iPhone")>0) 
   _AGENT_="iPhone";




// DOCUMENTATION: (mimelink)
// this section deals with file naming conventions for mime resolution: 
// a file argument is resovled to its mime and a correponding object 
// return (icon). _tbl_ is a preconceived list of accepted icons: default

function mimelink(obj) {
  var _ic_="folder";

  if(obj[0]=="*") _ic_="share";

  return "<img style=\"height:32px\" src=\""+_XMIME_+_ic_+".png\"/>"; 
}

// DOCUMENTATION: (mimeicon)
// this section deals with file naming conventions for mime resolution: 
// a file argument is resovled to its mime and a correponding object 
// return (icon). _tbl_ is a preconceived list of accepted icons: default

_tbl_="doc pdf gif ppt xls txt jpg";

function mimeicon(obj) {
  var _ic_="data";

  var _xt_= 1+obj.lastIndexOf("."); 
  if(_xt_>0) _ic_=obj.substr(_xt_).toLowerCase(); 

  if(_tbl_.indexOf(_ic_) <0) 
    _ic_="data";

  return "<img style=\"height:32px\" src=\""+_XMIME_+_ic_+".png\"/>";
}

_PWD_="";

// DOCUMENTATION: (resolvex)
// This function supports a simple role of extracting the path from
// a full url. It assumes a url starts with an http://.. which adds 
// up to 8 characters. Find first / right after. That is the path

function resolvex(url) {
  var _pt_=url.indexOf("/", 8);

  if(_pt_>0) 
    return url.substr(_pt_); return "";
}

// DOCUMENTATION: (makexdir)
// Build trivially a directory on the server, if permission are 
// allowed does not check for return code or anything. Systematically 
// app should make sure path is correct before executing function. 

function makexdir(obj) {

  xmlxhttp.open("MKCOL", obj, false);   
  xmlxhttp.send(null);  return xmlxhttp.status;
}


// DOCUMENTATION: (loadfile) 
// Load log entry and parse it out in accordance to the binning of
// time: Today, Last Week, Last Month... Since it is asynchronous
// loading might take time as logs are loaded one by one to browser

function loadfile(obj) {

  xmlxhttp.open("GET", obj, false);  xmlxhttp.send(null);
  
  if(xmlxhttp.status==200) 
    return xmlxhttp.responseText; 

  return ""; 
}

// DOCUMENTATION: (savefile) 
// Savefile is basic routine to submit files to server. PUT Method 
// is used. THis action will run in versioning mode. This function
// will save file in file specified by doc. txt is the content. 

function savefile(doc,
		  txt) {

  xmlxhttp.open("PUT", "/"+doc, false);  
   xmlxhttp.send(txt);   return xmlxhttp.status;
}

// DOCUMENTATION (xxxxLoad)
// Functions to load stubs in the page asynchronously for the footer
// and mainbody. Schemas may be need to be followed for proper outpt

function fileLoad(obj, 
		  doc) {

  document.getElementById(obj).innerHTML=loadfile(doc); 
}

function bodyHTML(obj,
		  txt) {

  document.getElementById(obj).innerHTML=txt;
}

// DOCUMENTATION: (propfind)
// Execute propfind method on an XDB server and thread out the next
// steps needed to deal with the output. Mainly capture _PWD_ the
// present working directory from url, parse the propfind output. 
// Since propfind is executed often, update the available user list

function propfind(url) {

  xmlxhttp.open("PROPFIND",
                   url, false); xmlxhttp.send(null);

  if(xmlxhttp.status!=207) 
    return xmlxhttp.status;

  _PWD_=resolvex(url); listprop(url);  return xmlxhttp.status;
}

// DOCUMENTATION: (listprop)
// Parse out a propfind result and display files in accordance to 
// their  data type. Isolate folders from files into separate 
// containers. The mahor component component is how to keep track

function listprop(url) {


  _pvd_=url.substr(0, url.lastIndexOf("/"));

  _DAV_="<dav><table><tr><th style=\"width:44px\"></th><th style=\"width:100%\"></th></tr>";

  if(_PWD_!="")
    _DAV_+="<tr onclick='propfind(\""+_pvd_+"\")'><td>"+mimelink(0)+"</td><td>../</td></tr>";

// We split the propfind out on DAV specifications. This will
// separate the records we need to parse out. We avoid a DOM model

  _hit_=xmlxhttp.responseText.split("<D:response>");

  for(i=1; i<_hit_.length; i++) {

    _url_=findpath(_hit_[i], "D:href"); _dec_=unescape(_url_.substr(_url_.lastIndexOf("/")+1));

    _tim_=findpath(_hit_[i], "D:getlastmodified");
    _inf_=Math.round(findpath(_hit_[i], "D:getcontentlength")/1000)+1;

    _mim_=_dec_.substr(_dec_.lastIndexOf(".")).toLowerCase();

    if(_mim_==".txt") 
      _url_="/pub/apps/edit/edit.html?"+resolvex(_url_);

// do extract url-link + fullname of files and dirsf or relative 
// path use the following syntax regexp search(/[0-9.-]\//) build
// div(s) over here for either dir or file section

    if(_hit_[i].indexOf("D:collection")>0)

      _DAV_+="<tr onclick='propfind(\""+_url_+"\")'><td>"+mimelink(_dec_)+"</td><td><x>"+_dec_+
	"</x><y>"+_tim_+"</y></td></tr>";

// Do the media files now After Foders. We do not process ranking
// here. Sorting should be a separate thing. 


    if(_hit_[i].indexOf("D:collection")<0)

      _DAV_+="<tr onclick='window.open(\""+_url_+"\")'><td>"+mimeicon(_dec_)+"</td><td><x>"+_dec_+
       "</x><y>"+_tim_+"</y><z>"+_inf_+" Kb</z></td></tr>";
  }

  _DAV_+="</table></dav>";  

  if(_hit_.length<2)
    _DAV_+="<div style=\"margin-top:50px; text-align:center; color:#AAA; font-size:24px;\">No Files Found</div>";


  document.getElementById("screen").innerHTML=_DAV_;
}



// DOCUMENTATION: (httpmodx)
// Execute propfind method on an XDB server and thread out the next
// steps needed to deal with the output. Mainly execute a modx query
// and manage the udri component. Run Get and parse the propfind 
// output. 

_udx_="";

function httpmodx(url) {

  if(_udx_!="") 
    url=url+"&udri="+_udx_; 

  xmlxhttp.open("GET", 
		url, false); xmlxhttp.send(null);

  if(xmlxhttp.status!=200) 
    return xmlxhttp.status;

  listmodx(url); return xmlxhttp.status;
}



// DOCUMENTATION: (listmodx)
// Parse out a propfind result and display files in accordance to 
// their  data type. Isolated images into container. Extract pattern
// for similarity search perhaps desired for faster image browsing
 
function listmodx(url) {

  _XDB_="<xdb>"; 

  d=1; if(_udx_!="") d=2;

  _ui_ =xmlxhttp.responseText.lastIndexOf("udrx=");
  if(_ui_>0) 
    _udx_=xmlxhttp.responseText.substr(_ui_+6, 24); 

  _hit_=xmlxhttp.responseText.split("<item>");
   for(i=d; i <_hit_.length ; i++) {

// Do extract url-link + fullname of files. Manager the escape  codes. 
// compute file names to appear in browser to be  fixed

    _url_=findpath(_hit_[i], "link"); 

    _dec_=unescape(_url_.substr(_url_.lastIndexOf("/")+1));
    _thp_=_url_.substr(0, _url_.lastIndexOf("/"))+"/."+_dec_;

    a=_hit_[i].indexOf("img:Model"); 
    b= _hit_[i].indexOf("img:CCD");

    _spc_=_hit_[i].substr(a, b-a-1).replace(/img:/g, "").replace(/\=/g,":").replace(/   /g, "").replace(/\"/g, "");

    if(_dec_.length>14)
      _dec_=_dec_.substr(0, 12)+"..";

// Find pattern matching per Maluf algorithm. Patterns extracted Subset 
// strings are calculated for actual query. 


    a= (_hit_[i].indexOf("<img:Pattern")+13);
    b= (_hit_[i].indexOf("></img:Patte")- 0);   _pat_=_hit_[i].substr(a, b-a).replace(/\"/g, "").replace(/ /g,"");

    _pbt_="";

    for(j=0; j<_pat_.length; j=j+10)
      _pbt_+=_pat_.substr(j, 4)+" "; 

// build div(s) over here for either dir or file sections. Maintain the
// container size for caching, prefetching and scrolling

    _XDB_+=
     "<img onclick='window.open(\""+_url_+"\")' src=\""+_thp_+"\"/><x>"+_dec_+"</x>"+
       "<y>"+_spc_+"<a onclick='_udx_=\"\"; httpmodx(\"/xdb?xgap=1024&modx=%3Cimg:I*%3E%3Cimg:Pattern "+escape(_pbt_)+"%3E&hits=16:1\")'>Similar</a></y>";
  }


  _XDB_+="</xdb>";

  if(_hit_.length<3) 
    _udx_="", _XDB_="<div style=\"margin-top:50px; text-align:center; color:#AAA; font-size:24px;\">No Images Found</div>";

  document.getElementById("screen").innerHTML=_XDB_;
}

