// ========================================================================
// howie@buk1.com:                                                       //
// 2/5/2004: Created BuidFolderDirectory.js                              //
//           BuildGalleryDirectory.htm is the test file.                 //
//           for owner & viewer both.                                    //
// 2/6/2004: Generate tree hierarchy in selection box                    //
// 2/11/2004: Expand/Collapse tree hierarchy based on <li></li> structure//
// 2/13/2004: tested for Netscape also                                   //
// 10/5/2004: maintain tree state, keep current folder path expanded only//
// 10/14/2004: maintain the whole tree (any node's open/close status)    //
//             document.all['1'] == document.all[1]                      //
//             first part of guid if digits causes wrong indexing        //
// 10/25/2004: too large content (149 guids) blow up cookie              // 
// ========================================================================
// need the following global variables defined:
// 2-dimentional array ar
// ar[3][0]= 'this is a really really long folder name';  folder_name
// ar[3][1]= 'fab43e0f-e9b3-4605-9277-9c89f77bd100';      folder_id
// ar[3][2]= 1;	                                          image_count
// ar[3][3]= '60fee319-0462-4cc5-9f7d-30c51a24a14e';      parent_id
// ar[3][4]= '10/21/2003';                                gdate
// ar[3][5]= '1';                                         order
// ar[3][6]= '5';                                         indent, added by program
// var iCampId = 5854;
// var blcart = false; (optional)
// var cfn='fab43e0f-e9b3-4605-9277-9c89f77bd100'
// start the process of build directory tree;
var stree = '';
var __arr = new Array();
var __arr_index = 0;

//call for testing
//the following functions called outside:
//bldFolderDirectory( 0 );
//bldFolderDirectory( 3 );
//bldParentFolder(make);
//bldFolderReordering();
//clickTree( __fdhandle.parentNode );
//bldFolderBrowsing();

// main entry function:
// bldFolderDirectory( outputMode), support 0/3 mode
function bldFolderDirectory( modeOutput ) {
  stree = '<table border="0" cellspaceing="0" cellpadding="0">';
  if ( modeOutput==0 )
    outputNode('Newest Photos', 1, 0, 0, 0, 0);
  bldTree(null, 0, modeOutput);
  stree += '</table><br>';
  document.open();
  document.write(stree);
  document.close();
} 

// recursive function to generate tree directory in arbitrary hierarchy
// from array or table contained { id, parent_id }
function bldTree( id, indent, modeOutput ) {
  var i = 0;
  while ( i<ar.length ) {
    if (ar[i][3]==id) {
      // output indent to represent hierarchy
      outputNode( ar[i][0], ar[i][1], ar[i][2], indent, i, modeOutput);      
      bldTree(ar[i][1], indent+1, modeOutput);
    }
    i++;
  }
} // end of bldTree

// generate level information into aray ar[][5];
function genLevelInfo( id, indent ) {
  var i = 0;
  while ( i<ar.length ) {
    if (ar[i][3]==id) {
      // record level info;
      ar[i][5] = indent;
      genLevelInfo(ar[i][1], indent+1 );
    }
    i++;
  }
} // end of genLevelInfo

// generate level information into aray ar[][];
function genOrderDirectory( id, indent ) {
  var i = 0;
  while ( i<ar.length ) {
    if ( ar[i][3]==id ) {
      // write into __arr;
      // copy the entire array in one statement, works? YES!
      __arr[__arr_index] = ar[i];
      __arr[__arr_index][ar[i].length] = indent;
      __arr_index++;
      // call recursively;
      genOrderDirectory(ar[i][1], indent+1 );
    }
    i++;
  }
}

// outputNode
function outputNode( folderName, folderId, count, indent, index, modeOutput )
{
  var sFontColor, sCount;
  if ( count > 0)
    sCount = ' (' + count + ')';
  else
    sCount = '';
  if ( modeOutput==0 ) {// for reviewing photo gallery
    if ( typeof(blcart)=='boolean' ) {
      if ( blcart )
        sFontColor = '#336699';
      else
        sFontColor = '#ffffff';
    }
  }
  var surl;
  stree += '<tr><td nowrap=true>';
  // 3 blanks per one level;
  for (var i=0; i<indent; i++)
    stree += '&nbsp;&nbsp;&nbsp;';
  if (indent>0)
    stree += '<img src="/msgboard/icon_bar.gif" border="0" WIDTH="15" HEIGHT="15">&nbsp;';
  else
    stree += '<img src="/msgboard/icon_folder.gif" border="0" WIDTH="15" HEIGHT="15">&nbsp;';
  // 3 option choice to display tree hierarchies
  // stree += '<img src="/template/images/transparent.gif" border="0" WIDTH="15" HEIGHT="15">&nbsp;';
  // stree += '<img src="/msgboard/icon_folder.gif" border="0" WIDTH="15" HEIGHT="15">&nbsp;';
  switch ( modeOutput ) {
    case 0:
      surl = 
        '<a href="gallery_photo_album.asp?form_camp_id=' + iCampId +'&cfn=' + folderId + '&pageno=1&rec=0&nextpage=1" target="mainFrame">' + 
        '<font face="Arial" size="1" color="' + sFontColor + '">' + folderName + '</font></a>' + 
        '<font face="Arial" size="1" color="' + sFontColor + '">' + sCount + '</font>'
      stree += surl + '</td></tr>';
      break;
    case 3: // for owner with ftp facility;
      surl = 
        '<a href="javascript:OpenWin('+ index +');">' + folderName + '</a>'+ sCount;
      // BUG: no constant link here, use javascript;
      var cart;
      if (icampid==8677 || icampid==6232 || icampid==6233 || icampid==6234)
	    cart = '<a href="javascript:openUploader(\'' + 'make=' + folderId + '&sn=' + unquote(folderName) + '\');">' +
	      '<font face="Arial" size="2">Add Pics(cart)</font></a>&nbsp;&nbsp;&nbsp;';
	  else if (icampid==5854)
		cart = '<a href="javascript:openMultiUploader(\'' + 'make=' + folderId + '&sn=' + unquote(folderName) + '&cid=' + icampid + '\');">' +
	      '<font face="Arial" size="2">Add Pics(beta)</font></a>&nbsp;&nbsp;&nbsp;';	  
	  else
	    cart = '';
	    
	  stree += 
	    '<font face="Arial" size="2">' + surl +'</font></td>' +
	    '<td width="20"></td>' +
	    '<td>' + 
	    '<a href="javascript:openUploaderTall(\'' + 'make=' + folderId + '&sn=' + unquote(folderName) + '\');">' +  
	    '<font face="Arial" size="2">Add Pics</font></a>&nbsp;&nbsp;&nbsp;' +
	    cart +  
	    '<a href="javascript:DeleteFolder(\'' + folderId + '\',\'' + unquote(folderName) + '\');">' +
	    '<font face="Arial" size="2">Delete</font></a></td></tr>';   
      break;
  }
} // end of outputNode

// create folder directory in drop-down list, option list
// parameter obj: drop-down object, for outside using
function bldParentFolder( obj ) {
  if ( typeof(obj) != 'object' ) {
    document.write('Need select box object!');
    return ;
  }
  // __arr = ar; __arr only get a ref to ar, not the copy. 
  __arr_index = 0;
  for (var k=0; k<ar.length; k++)
    __arr[k] = new Array(ar[0].length+1);
  // _arr & _arr_index shouldn't participate in recursion,
  // if so, complexity!
  genOrderDirectory( null, 0 );

  obj.length = 0;
  obj.options[0] = new Option('Select a Folder', '');
  // load into drop-down box's option list;
  // work on arr[][6] -- indent;
  if ( __arr.length>0 ) {
    for (var i=0; i<__arr.length; i++) {
      var s = '';
      for (var k=0; k<__arr[i][6]; k++)
        // for Netscape;
        s += '...' ;
      if ( __arr[i][6]>0 )
        s +=  '<' + (__arr[i][6]+1) + '> ';
      if ( __arr[i][2]>0 ) 
        s += __arr[i][0] + ' (' + __arr[i][2] +')';
      else
        s += __arr[i][0];
	  obj.options[i+1] = new Option( s , __arr[i][1] );
	}
  } else {
	obj.length = 0;
	obj.options[0] = new Option('No Folders Created', '')
  }
  obj.selectedIndex = 0;
}

// Create folder structure for folder reordering
function bldFolderReordering() 
{
  __arr_index = 0;
  for (var k=0; k<ar.length; k++)
    __arr[k] = new Array(ar[0].length+1);
  // _arr & _arr_index shouldn't participate in recursion,
  // if so, complexity!
  genOrderDirectory( null, 0 );
  // generate form
  document.write('<input type=hidden name=strfd><input type=hidden name=strod>');

  // indent info in arr[][6];
  var surl, last_indent, next_indent, icon;
  icon = '<img align="absmiddle" border=0 src="/msgboard/icon_folder.gif">';
  stree = '<ul class="root">' +
    '<li><a id="__fdhandle" onclick="return treeClick(this.parentNode);" href="" class="fdhandle">' + icon + '</a> <span style="vertical-align:middle">My Photo Gallery Folder</span>' +
    '<ul><li>';
  for (var k=0; k<__arr.length; k++) {
    var indent, sCount, surl;
    if (__arr[k][2]>0)
      sCount = ' (' + __arr[k][2] + ')';
    else
      sCount = '';
    indent = __arr[k][6];
    (k>0)? (last_indent=__arr[k-1][6]) : (last_indent=0) ;
    (k<__arr.length-1)? (next_indent=__arr[k+1][6]) : (next_indent=0) ;
    if (indent<next_indent) 
      // substree found;
      surl = '<a onclick="return treeClick(this.parentNode);" href="" class="fdhandle">' + icon + '</a> ';
    else
      surl = '<span class="fakelink">' + icon + '</span> ';
    surl +=    
        '<input style="display:none" size="2" maxlength="2" name="order" value="' + __arr[k][5] + '">' + 
		'<input type="hidden" name="folderid" value="' + __arr[k][1] + '"> ' +
		'<span style="vertical-align:middle">' +  __arr[k][0] + sCount + '</span>';
    stree += surl;
    // start a new layer in <li>
    if (indent < next_indent)
      stree += '<ul><li>';
    // a test here!
    if (indent >= next_indent) {
      for (var j=0; j<indent-next_indent+1; j++)
        stree += '</li></ul>';
      if (k<__arr.length-1)
        stree += '<ul><li>';
    }
  } // end for  
  stree += '</li></ul></li></ul>';
  document.write( stree );
}

// Create folder structure for photo browsing
// only expand for first level
function bldFolderBrowsing() 
{
 if (ar.length==0) return;
  __arr_index = 0;
  for (var k=0; k<ar.length; k++)
    __arr[k] = new Array(ar[0].length+1);
  // _arr & _arr_index shouldn't participate in recursion,
  // if so, complexity!
  genOrderDirectory( '', 0 );
  // shrink empty folder
  if ( is.v>10 ) {
	// no matter IE or Netscape, if version great than 5;
    for (var k=__arr.length-1; k>=0; k--)
      if ( !needShow(k) ) __arr.splice(k, 1);
    bldTreeFromArray( __arr );
  } else {
    var ___arr = new Array();
    var index = 0;
    for (var k=0; k<__arr.length; k++ )
      if ( needShow(k) )
         ___arr[index++] = __arr[k];
    bldTreeFromArray( ___arr );
  }
}

function bldTreeFromArray( arr )
{      
  var surl, indent, next_indent, sFontColor;
  var cmd;
  if ( typeof(blcart)=='boolean' )
      sFontColor = '#336699';
  else
    sFontColor = '#000000';
  surl = getCookieItem('tree', 'treestatus');
  if (surl==null || surl=='')
    cmd = "Hide Sub Folders";
  else
    cmd = "Show Sub Folders";
  //if ( iCampId != 5854 )
  //{
	  stree = 
		'<ul class="root">' +
		'<li><span class="fakelink"> </span><a onclick="javascript:return expand(this);" href="#">' + cmd + '</a>' +
		'<ul class="root" id="newest"><li><span class="fakelink">-</span> ' +
		'<a href="javascript:opTree(\'1\')">' + 
		'<font color="' + sFontColor + '">Newest Photos</font></a></li></ul>'
  //}
  // real folders
  for (var k=0; k<arr.length; k++) {
    var sCount, surl;
    if ( arr[k][2]>0 )
      sCount = ' (' + arr[k][2] + ')';
    else
      sCount = '';
    indent = arr[k][6];
    (k<arr.length-1)? (next_indent=arr[k+1][6]) : (next_indent=0) ;
    if ( indent<next_indent )
      // substree found;
      surl = '<a onclick="javascript:toggleSection(this.parentNode)" href="#" class="fdhandle">-</a> ';
    else
      surl = '<span class="fakelink">-</span> ';
    if ( arr[k][2]>0 )
        // '<a href="gallery.aspx?cfn=' + arr[k][1] + '">' +
      surl +=
        '<a href="javascript:opTree(\'' + arr[k][1] + '\')">' + 
        '<font color="' + sFontColor + '">' + arr[k][0] + '</font></a>' + 
        '<font color="' + sFontColor + '">' + sCount + '</font>'
    else
      surl += 
        '<a onclick="javascript:return toggleSection(this.parentNode)" href="#">' + 
		'<font color="' + sFontColor + '">' + arr[k][0] + '</font></a>';
    // start a new layer in <ul><li> anyway
	// stree += (indent==0)? '<ul class="root" id="' + arr[k][1] + '"><li>' : '<ul id="' + arr[k][1] + '"><li>';
    // using short name: if folder structure changed, caused problem;
    // stree += (indent==0)? '<ul class="root" id="_t' + k + '"><li>' : '<ul id="_t' + k + '"><li>';
	stree += (indent==0)? '<ul class="root" id="' + arr[k][1].substring(0,8) + '"><li>' : '<ul id="' + arr[k][1].substring(0,8) + '"><li>';

    stree += surl;
    // start a new layer in <li>
    if (indent >= next_indent) {
      for (var j=0; j<indent-next_indent+1; j++)
        stree += '</li></ul>';
    }
  } // end for  
  stree += '</li></ul></li></ul>';
  //
  if (is.ie)
    document.all['folder_tree'].innerHTML = stree;
  else if (is.ns) // Netscape
    document.getElementById('folder_tree').innerHTML = stree;
  resTreeStatus( false ); 
}

// Decide if this folder will show based on image count recursivly;
// __arr[][2] -- image count
// __arr[][6] -- indent
function needShow( idx )
{
  if (__arr[idx][2] > 0 )
    return true;
  else {
    var indent = __arr[idx][6];
    var nxt = idx+1;
    while ( nxt<__arr.length && indent<__arr[nxt][6] && __arr[nxt][2]==0 ) 
      nxt++ ;
    if (nxt>=__arr.length || indent>=__arr[nxt][6])
      return false;
    else
      return true;
  }
}

// toggle expand/collapse!
var __last_element;
function treeClick( parent )
{
  if ( parent==__last_element ) 
    return false;
  if (typeof(__last_element)=='object')
    toggleSect( __last_element, false, false );
  __last_element = parent;
  toggleSect( parent, true, false );
  return false;
}
// collapse only to first level
function expand( obj )
{
  var nodeArray, isExpand, str;
  // innerText is IE feature!
  str = obj.parentNode.childNodes[1].firstChild.nodeValue;
  isExpand = (str=='Show Sub Folders')? true: false;
  str = (str=='Show Sub Folders')? 'Hide Sub Folders': 'Show Sub Folders';
  nodeArray = obj.parentNode.childNodes;
  for (var i=0; i<nodeArray.length; i++) {
    if (nodeArray[i].tagName && nodeArray[i].tagName.toLowerCase()=='ul')
	  allNodes( nodeArray[i].childNodes[0], isExpand );
  }
  obj.parentNode.childNodes[1].firstChild.nodeValue = str;
  opTree('');
  return false;
}
function allNodes( obj, isExpand )
{   
    var node, nodeArray = obj.childNodes;
    for (var i=0; i<nodeArray.length; i++) {
      node = nodeArray[i];
	  if (node.tagName && node.tagName.toLowerCase()=='a')
	    // optimized for Netscape
	    if (node.firstChild.nodeValue=='-' || node.firstChild.nodeValue=='+')
	      node.firstChild.nodeValue = (isExpand)? '-': '+';
	  if (node.tagName && node.tagName.toLowerCase()=='ul') {
	    node.style.display = (isExpand)? 'block': 'none';
	    allNodes( node.childNodes[0], isExpand );
	  }
	}
	return false;
}
// set tree status
var f_tree_cnds = '';
function setTreeStatus( obj, isExpand )
{   
    var node, nodeArray = obj.childNodes[0].childNodes;
    for (var i=0; i<nodeArray.length; i++) {
      node = nodeArray[i];
	  if (node.id && node.tagName.toLowerCase()=='ul') {
	    if (node.style.display=='none' && !isExpand )
		  f_tree_cnds += node.id + ',';
	    if (node.style.display!='none' && isExpand )
		  f_tree_cnds += node.id + ',';
		setTreeStatus( node, isExpand);	   
	  }  
	}
	return false;
}
// rebuild tree status
function resTreeStatus( isExpand )
{   
  var i=0;
  var cfn;
  var cnds = getCookieItem('tree', 'treestatus');
  if (cnds==null) cnds="";
  var folder_tree;

  while (true) {
	i = cnds.indexOf(',');
    if (i>0) {
	  cfn = cnds.substring(0, i);
	  cnds = cnds.substring(i+1, cnds.length);
    } else 
      break;	
    // get current node;
	if (is.ie) // IE
		folder_tree = document.all.item(cfn);
	else if (is.ns) // Netscape
		folder_tree = document.getElementById(cfn)
	if (folder_tree.tagName.toLowerCase()=='ul') {
		folder_tree.style.display = (isExpand)?'block':'none';
		folder_tree.parentNode.childNodes[0].firstChild.nodeValue = (isExpand)?'-':'+';
	} else
		break;
  }
  f_tree_cnds = '';
  // set current node;
  cfn = getCookieItem('tree', 'folderid');
  if (cfn==null || cfn=='' || cfn=='1')	
	cfn = 'newest' 
  else 
    cfn=cfn.substring(0,8);
  if (is.ie) // IE
	folder_tree = document.all.item(cfn);
  else if (is.ns) // Netscape
	folder_tree = document.getElementById(cfn);
  if (folder_tree!=null  && folder_tree.tagName.toLowerCase()=='ul') {
    // tree-format related
    folder_tree = folder_tree.childNodes[0].childNodes[2];
	folder_tree.style.fontStyle = 'italic';
	// folder_tree.style.fontVariant = 'small-caps';
	folder_tree.style.fontSize = '13px';
	folder_tree.style.fontWeight = 'bolder';
	folder_tree.style.backgroundColor = '#fafafa';
	// disable toggle after round trip 
	// if (document.f_tree.expand.value=="1") toggleSection( folder_tree.parentNode );
  }
}

// show (expand) to-cfn path
function shwToRoot()
{
  var first=true;
  var folder_tree;
  if (is.ie)
    folder_tree = document.all['folder_tree'];
  else if (is.ns) // Netscape
    folder_tree = document.getElementById('folder_tree');
  // collapse to first level: <ul><li><a>
  expand( folder_tree.childNodes[0].childNodes[0].childNodes[0]	);

  while (true) {
    // get current node;
	if (is.ie) // IE
		folder_tree = document.all.item(cfn);
	else if (is.ns) // Netscape
		folder_tree = document.getElementById(cfn)
	if (folder_tree.tagName.toLowerCase()=='ul') {
		if (first) {
			first = false;
			folder_tree.style.fontSize = '12px';
			folder_tree.style.fontWeight = 'bolder';
			folder_tree.style.backgroundColor = '#fafafa';
			toggleSect( folder_tree.childNodes[0], true, true );
			// folder_tree.style.backgroundColor = 'white';
		} else 
			toggleSect( folder_tree.childNodes[0], true, true );
		cfn = folder_tree.parentNode.parentNode.id;
		if (cfn=="") break;
	} else
		break;
  }   
}
// request a folder's picture;
function opTree( id )
{
	// if (id>'') obj.cfn.value = id;
	// gathering all closed node ids
	var folder_tree;
	if (is.ie)
		folder_tree = document.all['folder_tree'];
	else if (is.ns) // Netscape
		folder_tree = document.getElementById('folder_tree');
	f_tree_cnds = '';
	setTreeStatus(folder_tree.childNodes[0], false);
	// set cookies;
	// setCookieItem('tree', 'treestatus', obj.cnds.value);
	if (id>'') {
		delCookie('tree');
		setCookie('tree', 'folderid='+id+'&treestatus='+f_tree_cnds );    
		document.location = 'gallery.aspx?op=1&opstring='+id;
	} else 	{
		id = getCookieItem('tree', 'folderid'); 
		delCookie('tree');
		setCookie('tree', 'folderid='+id+'&treestatus='+f_tree_cnds );
		// document.location = 'gallery.aspx?op=1&opstring='+id;
		// setCookieItem('tree', 'treestatus', f_tree_cnds );
	}
    return;
}
function toggleSection( parent ) 
{
  toggleSect( parent, true, true );
  opTree('');
  return false;
}   
function toggleSect( parent, shw, isToggle ) 
{
  var nodeArray = parent.childNodes;
  for (var i=0; i<nodeArray.length; i++) {
    node = nodeArray[i];
	if (node.tagName && node.tagName.toLowerCase()=='ul') {
      if (isToggle)
        node.style.display = (node.style.display=='none') ? 'block' : 'none';
      else
        // tree nested as <li>parent_level<ul><li>child_1 ....</li></ul></li>;
        // deal with order input box;
        shwChildBox( node.childNodes[0], shw );
    }
	if (node.tagName && node.tagName.toLowerCase()=='a' && isToggle) {
	  // modified for stricker condition; optimized for Netscape
	  var h = node.firstChild.nodeValue; 
	  if (h=='-' || h=='+')
	    node.firstChild.nodeValue = (h=='-') ? '+': '-';
	}
  }
  return;
}
function shwChildBox( parent, shw ) 
{
  var nodeArray = parent.childNodes;
  for (var i=0; i<nodeArray.length; i++) {
    node = nodeArray[i];
	if (node.name && node.name.toLowerCase()=='order') {
	  node.style.display = (shw)? 'inline' : 'none';
	  return;
	}
  }
  return;
}

// Gathering folderid & order pairs into input fields;
function chkList( obj )
{
  if (typeof(obj.order.length)=='undefined') {
    alert('Only one folder found, no need for reordering.'); 
    return;
  }
  var str_fd='', str_od='';
  for (var i=0; i<obj.order.length; i++) {
    if (obj.order[i].style.display=='inline') {
      // ==NaN, using isNaN
      if ( isNaN(parseInt(obj.order[i].value)) ) {
        obj.order[i].value = '';
        alert("Use numbers only to issue a clear order!");
        return;
      } else {
        str_od += obj.order[i].value + ';';
        str_fd += obj.folderid[i].value + ';';
      }
    }
  }
  obj.strfd.value = str_fd;
  obj.strod.value = str_od;
  obj.submit();
}

function unquote (str) {
  // unquote ' & "
  re = /'/g;
  str = str.replace(re, "%2C");
  re = /"/g;
  return str.replace(re, "%22");
}
