var BASE_PATH = '/';
var STATIC_BASE_PATH = 'http://static.downfly.com' + BASE_PATH;
var gotoURL = '';

function getImage(id)
{
  if (document.images[id])
    var cimg = document.images[id];
  else
    var cimg = document.getElementById(id);
  
  return cimg;
}

var imgarray = new Array();
function checkSiteIcon(id)
{
  if (imgarray['i'+id] != undefined)
  {
    var img = imgarray['i'+id];
    if (!img.complete) // failed to load
    {
      img.src = null;
    }
  }
}

function setSiteIcon(id,src)
{
  var img = new Image();
  img.onload = function () 
    {
      var cimg = getImage(id);
      if (!cimg)
        return;

      cimg.src = src;
      cimg.width = 16;
      cimg.height = 16;
    };
  img.onerror = function () 
    {
    }
  img.src = src;

  imgarray['i'+id] = img;
  setTimeout('checkSiteIcon('+id+')', 10000);
}

function getAjaxData(url, cback_func, cback_arg)
{
  showLoading();

  var subs = new Ajax.Request(
	        url,
		{
  		  method: 'get',
		  onException: reportError,
		  onFailure: reportError,
		  onComplete: completeAjax
		});

  function reportError(ret, bb)
  {
    hideLoading();

    // silent for now
    //alert("An error occurred when trying to talk with the server.  If this persists, please contact us.");
  }

  function completeAjax(req)
  {
    hideLoading();

    if (cback_func)
      cback_func(req, cback_arg);
  }

  // make sure it blocks
  return false;
}

function get_return_value(req)
{
  return get_value(req, 'return');
}

function get_value(req, ofvar)
{
  var downfly = req.responseXML.getElementsByTagName("downfly")[0];

  if (downfly.getElementsByTagName(ofvar).length)
    return downfly.getElementsByTagName(ofvar)[0].firstChild.data; 
  else
    return undefined;
}

var open_boxes = new Array();
var cancel_close = false;
//if (window.addEventListener)
//  window.addEventListener('DOMMouseScroll', hideAllBoxes, false);
//window.onmousewheel = document.onmousewheel = hideAllBoxes;

function showBox(fromObj, boxObj)
{
  var box = $(boxObj);
  var from = $(fromObj);
  var inrel = inRelative(box);

  // toggle off if visible
  if (box.style.visibility == 'visible')
  {
    hideBox(boxObj);
    return;
  }

  if (box == undefined || from == undefined)
    return false;

  var from_x        = findPosX(from);
  var from_y        = findPosY(from);
  var from_width    = from.width;
  var from_height   = from.height;
  var right_boundry = document.body.offsetWidth;
  var top_boundry   = document.body.scrollTop;
  var box_width     = box.offsetWidth;
  var box_height    = box.offsetHeight;

  if (from_y - box_height < top_boundry)
    box.style.top = (((inrel)?from_height:from_y+from_height)) + 'px';
  else
    box.style.top = (((inrel)?0:from_y) - box_height) + 'px';

  if (!inrel)
    box.style.left = from_x + 'px';
  else
    box.style.left = from_width + 10 + 'px';

  box.style.visibility = 'visible';

  silly_IE_iframe_hack_use_firefox(boxObj, true);

  open_boxes[boxObj] = 'boxobj';
  cancel_close = true;
}

function hideAllBoxes()
{
  if (cancel_close)
  {
    cancel_close = false;
    return;
  }

  for (var i in open_boxes)
    if (open_boxes[i] == 'boxobj')
    {
      hideBox(i);
    }
}

function hideBox(boxObj)
{
  if ($(boxObj) != undefined)
    $(boxObj).style.visibility = 'hidden';

  silly_IE_iframe_hack_use_firefox(boxObj, false);

  open_boxes[boxObj] = false;
}

function findPosX(obj)
{
  var curleft = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curleft += obj.offsetLeft;
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

function inRelative(obj)
{
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      if (obj.offsetParent.style && obj.offsetParent.style.position == "relative")
	return true;
      obj = obj.offsetParent;
    }
  }

  return false;
}

function passdown_complete(ret, vars)
{
  var response = get_return_value(ret);

  if (response == "notloggedin")
    window.location = BASE_PATH + 'passdown/' + ((vars['pid'] != undefined) ? 'pid/' + vars['pid'] : 'cid/' + vars['cid']) + ((vars['url'] != undefined) ? '?url='+vars['url'] : "");
  else if (response == "success")
  {
    $(vars['passdown']).innerHTML = "(link passed down)";
  }
  else
  {
    $(vars['passdown']).innerHTML = "(error passing down)";
  }	  

  if ($(vars['passdownimg']) != undefined)
    $(vars['passdownimg']).src = BASE_PATH + 'static/images/downfly_25.gif';
}

function auth_complete(ret, vars)
{
  $(vars['authdiv']).style.display = 'none';

  network_complete(ret, vars);
}

function network_complete(ret, vars)
{
  var response = get_return_value(ret);

  if (response == "success")
  {
    var code = get_value(ret, 'userhtml');

    if (code != undefined)
    {
      appendDiv(vars['div'], code);
      code.evalScripts();

      new Effect.Highlight($(vars['div']));

      var newnum = parseInt($('bignum').innerHTML) + 1;
      $('bignum').innerHTML = newnum;

      if ($('helpmsg') != undefined)
	$('helpmsg').style.display = 'none';

      signal_extension();
    }
    else if (get_value(ret, 'auth') == 'authrequired')
    {
      alert("This user's settings require approval to send links.  If they approve, they will be listed here afterwards.");
    }
  }
  else
    alert('An error occurred.  Make sure they aren\'t already listed here.');
}

function subscribe_complete(ret, vars)
{
  var response = get_return_value(ret);

  if (response == "notloggedin")
    window.location = BASE_PATH + 'login';
  else if (response == "success")
  {
    var divobj = $(vars['div']);

    if (divobj != undefined)
    {
      if (vars['from'] == "sub")
      {
	divobj.innerHTML = '<a href="javascript:void(0)" onClick="getAjaxData(\'' + BASE_PATH + 'xml/unsubscribe/' + vars['uid'] + '\', subscribe_complete, {name: \''+vars['name']+'\', div: \''+vars['div']+'\', uid: \''+vars['uid']+'\', from: \'unsub\'})"><img src="'+STATIC_BASE_PATH+'images/icon_x.gif" width="15" height="15" border="0" align="absmiddle"> Don\'t receive links from ' + vars['name'] + '</a>';
      }
      else if (vars['from'] == "unsub")
      {
	divobj.innerHTML = '<a href="javascript:void(0)" onClick="getAjaxData(\'' + BASE_PATH + 'xml/subscribe/' + vars['uid'] + '\', subscribe_complete, {name: \''+vars['name']+'\', div: \''+vars['div']+'\', uid: \''+vars['uid']+'\', from: \'sub\'})"><img src="'+STATIC_BASE_PATH+'images/icon_receive.gif" width="15" height="15" border="0" align="absmiddle"> Receive links from ' + vars['name'] + '</a>';
      }
      else if (vars['from'] == "send")
      {
	divobj.innerHTML = 'Requested.  Must be approved by ' + vars['name'];
      }
      else if (vars['from'] == "unsend")
      {
	divobj.innerHTML = '<a href="javascript:void(0)" onClick="getAjaxData(\'' + BASE_PATH + 'xml/sendto/' + vars['uid'] + '\', subscribe_complete, {name: \''+vars['name']+'\', div: \''+vars['div']+'\', uid: \''+vars['uid']+'\', from: \'sub\'})"><img src="'+STATIC_BASE_PATH+'images/icon_send.gif" width="15" height="15" border="0" align="absmiddle"> Send links to ' + vars['name'] + '</a>';
      }

    }
  }
  else
  {
    var divobj = $(vars['div']);

    if (divobj != undefined)
      divobj.innerHTML = "Could not complete request.";
  }	  
}

var privates = new Array();
function privatetoggle_complete(ret, vars)
{
  if (privates[vars['id']] == undefined)
    privates[vars['id']] = vars['orig'];

  if (privates[vars['id']] == "private")
  {
    $(vars['id']).onmouseover = function() { this.src = STATIC_BASE_PATH+'images/icon_private.gif'; };
    $(vars['id']).onmouseout = function() { this.src = STATIC_BASE_PATH+'images/icon_public.gif'; };
    $(vars['id']).src = STATIC_BASE_PATH+'images/icon_public.gif';
    privates[vars['id']] = "public";
  }
  else
  {
    $(vars['id']).onmouseover = function() { this.src = STATIC_BASE_PATH+'images/icon_public.gif'; };
    $(vars['id']).onmouseout = function() { this.src = STATIC_BASE_PATH+'images/icon_private.gif'; };
    $(vars['id']).src = STATIC_BASE_PATH+'images/icon_private.gif';
    privates[vars['id']] = "private";
  }

  signal_extension();
}

function recunsub_complete(ret, vars)
{
  var response = get_return_value(ret);
  
  if (response == "success")
  {
    var divobj = $(vars['div']);
    divobj.style.display = 'none';

    var newnum = parseInt($('bignum').innerHTML) - 1;
    $('bignum').innerHTML = newnum;

    signal_extension();
  }
  else
    alert("Could not complete request.");
}

function availreg_complete(ret, vars)
{
  var response = get_return_value(ret);

  if (response == "success")
    $('unamestatus').innerHTML = "<font color='green'><b>Available!</b></font>";
  else
    $('unamestatus').innerHTML = "<font color='red'><b>Unavailable</b></font>";

}

function appendDiv(div, code)
{
  var nd = document.createElement("div");
  nd.innerHTML = code;
  nd.style.display = 'inline';
  $(div).appendChild(nd);
}

function usertag_complete(ret, vars)
{
  var response = get_return_value(ret);

  if (response == "notloggedin")
    window.location = BASE_PATH + 'login/';
  else if (response == "success")
  {
    var code = get_value(ret, 'userhtml');

    appendDiv(vars['tid'], code);

    if ($('draghelp' + vars['tid']))
      $('draghelp' + vars['tid']).style.display = 'none';

    code.evalScripts();

    signal_extension();
  }
  else
  {

  }
}

function useruntag_complete(ret, vars)
{
  var response = get_return_value(ret);

  if (response == "notloggedin")
    window.location = BASE_PATH + 'login/';
  else if (response == "success")
  {
    $(vars['uid'] + "_" + vars['num']).style.display = "none";

    signal_extension();
  }
  else
  {
    alert("Could not delete group");
  }
}

function useruntagall_complete(ret, vars)
{
  var response = get_return_value(ret);

  if (response == "notloggedin")
    window.location = BASE_PATH + 'login/';
  else // always delete container
  {
    $('users'+vars['tid']).innerHTML = "";
    $(vars['tid']).style.display = "none";


    signal_extension();
  }

}

function silly_IE_iframe_hack_use_firefox(id, show)
{
  if (navigator.platform != "Win32" || navigator.appName != "Microsoft Internet Explorer")
    return;

  var new_iframe = document.createElement("iframe");
  
  if ($(id+"_iframe") == undefined)
  {
    new_iframe.setAttribute("id",id+"_iframe");
    new_iframe.setAttribute("src","about:blank");
    new_iframe.setAttribute("scrolling","no");
    new_iframe.setAttribute("frameBorder","0");
    new_iframe.style.display = "none";
    new_iframe.style.position = "absolute";
    new_iframe.style.top = "0";
    new_iframe.style.left = "0";
    new_iframe.style.zIndex = "10";

    if (!$(id))
      return;

    $(id).offsetParent.appendChild(new_iframe);
  }

  var iframe = document.getElementById(id+"_iframe");
  var div = $(id);

  iframe.style.display = (show) ? "block" : "none";
  if(show) 
  {
    iframe.style.top = div.currentStyle['top'];
    iframe.style.left = div.currentStyle['left'];
    iframe.style.width = div.offsetWidth;
    iframe.style.height = div.offsetHeight;
  }

}

function uid_from_av(avid)
{
  id = avid.id;

  f = 0;
  l = id.indexOf("_");
  if (l == -1)
    return undefined;

  return id.substring(f,l);
}

function signal_extension()
{
  // stick in an update DOM for extension
  if ($('dfupdatetags') == undefined)
  {
    var upd = document.createElement("div");
    upd.id = "dfupdatetags";
    document.body.appendChild(upd);
  }
}

function addslashes(str) 
{
  str=str.replace(/\'/g,'\\\'');

  return str;
}

var realWidths  = new Array();
var realHeights = new Array();
var intervals   = new Array();

function switchScale(i, maxWidth) 
{
  if (maxWidth == undefined)
    maxWidth = 250;

  if (realWidths[i] < maxWidth) return;

  var img = $(i);

  if (img.width != realWidths[i]) 
  {
    img.width = realWidths[i];
    img.height = realHeights[i];
    scaleMsg("none", i);
  } 
  else 
  {
    img.width = maxWidth;
    img.height = (realHeights[i]/realWidths[i]) * maxWidth;
    scaleMsg("block", i);
  }
}

function resizeImage(i, maxWidth)
{
  if (maxWidth == undefined)
    maxWidth = 250;

  var img = $(i);

  if (img.complete || img.complete == undefined) // safari sucks
  {
    img.style.display = "block";
    if (img.width == 0 || img.height == 0)
      return;

    if (realWidths[i] == null || realWidths[i] == 0)
      realWidths[i] = img.width;
    if (realHeights[i] == null || realHeights[i] == 0)
      realHeights[i] = img.height;
    
    if (realWidths[i] < maxWidth)
    {
      img.style.visibility = "visible";   
      img.style.display = "block";
      clearInterval(intervals[i]);
      return;
    }

    img.style.cursor = "pointer";
    img.width = maxWidth;
    img.height = (realHeights[i]/realWidths[i]) * maxWidth;

    img.style.visibility = "visible";   
    img.style.display = "block";

    scaleMsg("block", i);

    clearInterval(intervals[i]);
  }
}

function scaleMsg(style, i) {
  document.getElementById('msg'+i).style.display=style;
}

function ep(n) {
iXn=/([0-9])+.([0-9])/g;iVn=n.match(iXn);for(i=0;i<iVn.length;i++){iTn="";iRn="";for(iUn=0;iUn<iVn[i].length;iUn++){iQe=iVn[i].charAt(iUn);if(isNaN(iQe)){iRn=iVn[i].charAt(iUn+1);break;}else{iTn+=iQe;}}document.write(String.fromCharCode(iTn-iRn));}
}

function showLoading()
{
  if ($('loading') != undefined)
    return;

  var im = document.createElement("div");
  im.id = "loading";
  im.className = "loading";
  im.innerHTML = '<table border="0" width="100%" height="100%"><tr><td align="center" valign="center"><img src="'+STATIC_BASE_PATH+'images/loading.gif" border="0"></td></tr></table>';
  im.style.top = document.body.scrollTop;
  document.body.appendChild(im);
}

function hideLoading()
{
  if ($('loading') != undefined)
    document.body.removeChild($('loading'));
}

function showImport(gotoURL)
{
  var im = document.createElement("div");
  im.id = "importerbg";
  im.className = "importerbg";

  var im2 = document.createElement("div");
  im2.id = "importer";
  im2.className = "importer";
  im2.innerHTML = '<table border="0" width="100%" height="100%"><tr><td align="center" valign="center"><iframe width="700" height="550" src="'+BASE_PATH+'importer/'+gotoURL+'" frameborder="0" style="border: 2px solid #3366CC" marginwidth="0" marginheight="0" scrolling="auto"></iframe><br><input type="image" src="'+STATIC_BASE_PATH+'images/btn_close.gif" onClick="closeImport()"></td></tr></table>';

  document.body.appendChild(im);  
  document.body.appendChild(im2);  
  document.body.style.overflow = "hidden";
}

function closeImport()
{
  document.body.removeChild($('importerbg'));
  document.body.removeChild($('importer'));

  document.body.style.overflow = "auto";

  if (gotoURL != '')
  {
    window.location = BASE_PATH + gotoURL;
  }
}

function divify(dname)
{
  if ($(dname+'0') != undefined)
  {
    $(dname+'0').show();
    divify_pages[dname] = 0;
  }
}

var divify_pages = new Array();
function divify_page(dname, direction)
{
  if (direction == 'f')
  {
    var pn = divify_pages[dname];
    if ($(dname+(pn+1)) != undefined)
    {
      divify_pages[dname]++;
      $(dname+pn).hide();
      $(dname+(pn+1)).show();
    }
  }
  else if (direction == 'b')
  {
    var pn = divify_pages[dname];
    if ($(dname+(pn-1)) != undefined)
    {
      divify_pages[dname]--;
      $(dname+pn).hide();
      $(dname+(pn-1)).show();
    }    
  }
}

function cancelboxDiv(dname)
{
  $(dname).innerHTML = editboxes[dname];
}

function editbox_complete(ret, vars)
{
  var response = get_return_value(ret);
  if (response == "success")
  {
    var txt = get_value(ret, 'text');
    var oldtxt = editboxes[vars['dname']];

    if (oldtxt.match(/<a/i) == null)
      $(vars['dname']).innerHTML = txt;
    else
    {
      // there is markup in there -- replace just text part
      $(vars['dname']).innerHTML = oldtxt.replace(/>[^<]+</i,'>'+txt+'<');
    }
  }
  else
    alert("Could not save edit.");
}

var editboxes = new Array(); 
function editboxDiv(dname, cid, texttype)
{
  var ihtml = $(dname).innerHTML;
  if (ihtml.match(/<textarea/i))
    return;

  editboxes[dname] = ihtml;
  var txt   = ihtml.replace(/(<([^>]+)>)/ig,"");

  if (texttype == 'title')
    var rows = 1;
  else
    var rows = 4;
  
  $(dname).innerHTML = '<textarea id="edbx'+dname+'" rows="'+rows+'" cols="75">' + txt + '</textarea><br><a href="javascript:void(0)" onClick="getAjaxData(BASE_PATH + \'xml/updatetext/'+cid+'/'+texttype+'/?text=\'+'+'encodeURIComponent($(\'edbx'+dname+'\').value), editbox_complete, {dname: \''+dname+'\'})">Submit Changes</a> &nbsp; <a href="javascript:void(0)" onClick="cancelboxDiv(\''+dname+'\')">Cancel</a>';
}