
var adv, advbox, cent, whore, mainform, prev, codearea, codetype = -1;

var format = -1, ttype = -1, logo = -1, w, biglogo = false, ctext = "";

var fd = [
{key: 'leader', w: 728, h: 90},
{key: 'banner', w: 468, h: 60},
{key: 'minibar', w: 300, h: 31},
{key: 'square', biglogo: true, w: 250, h: 250, wfixed: true},
{key: 'minisquare', biglogo: true, w: 125, h: 125, wfixed: true},
{key: 'button', w: 88, h: 31, wfixed: true},
{key: 'userbar', w: 350, h: 19}
];
var formatlabels = ["Hueg Banner", "Normal Banner", "Mini Banner",
                    "Square", "Mini Square", "Mini Button", "Userbar"];

function linkyload()
{
   cent = document.getElementById("cent");
   whore = document.getElementById("whore");
   clearps(whore);

   whore.appendChild(el("P",
 ["Generate your own link to ", el("EM", "Numbcast"),
  ", and copy the code at the bottom to your web page. Or don't, we can't " +
  "really force you..."]));

   var formatchoice = whore.appendChild(choices(formatlabels, setformat));

   mainform = whore.appendChild(el("DIV"));
   advbox = whore.appendChild(el("DIV"));

   var advlink = el("SPAN", "advanced", {class_: "pluslink fakelink"});
   whore.firstChild.insertBefore(advlink, whore.firstChild.firstChild);
   aEL(advlink, "click", toggleadv);

   prev = el("IMG", null, {src: getimageurl(), alt: "Numbcast"});
   cent.appendChild(numbbox("Preview", "linkprev")).appendChild(el("P", prev));

   var codebox = cent.appendChild(numbbox("Code", "linkcode"));
   var codeopts = ["HTML", "BBCode"];
   var codechoice = codebox.appendChild(choices(codeopts, setcodetype));
   codearea = el("TEXTAREA", "Oops.", {rows:4, cols:60, readonly:"readonly"});
   codebox.appendChild(el("P", codearea));
   codebox.appendChild(el("P", ["Thanks for supporting ",
                                el("EM", "Numbcast"), "!"]));

   setchoice(formatchoice, 1);
   setchoice(codechoice, 0);
}

function clearps(parent)
{
   var ps = parent.getElementsByTagName("P");
   while(ps.length) parent.removeChild(ps[0]);
}

function el(tag, stuff, attr)
{
   var c = document.createElement(tag);

   if(stuff && !isarray(stuff)) stuff = [stuff];

   if(stuff)
      for(var i = 0; i < stuff.length; ++i)
      {
         if(typeof stuff[i] == "string")
            stuff[i] = document.createTextNode(stuff[i]);
         c.appendChild(stuff[i]);
      }

   if(attr)
      for(i in attr)
         if((i.replace("_", "")) == "class") // IE weirdness.
            c.className = attr[i];
         else
            c.setAttribute(i.replace("_", ""), attr[i]);

   return c;
}

function isarray(x)
{
   return x && (typeof x == "object") && (x.constructor == Array);
}

function numbbox(title, id)
{
   return el("DIV", el("H2", title), id ? {id: id} : null);
}

function toggleadv()
{
   adv = !adv;
   if(adv)
   {
      advbox.appendChild(el("P", "Custom text may contain some HTML-like " +
       "tags: <br>, <b></b>, and <i></i> should be self-explanatory."));

      var wset = el("SPAN", "set a custom width", {class_: "fakelink"});
      aEL(wset, "click", cwidthset);

      var wdef = el("SPAN", "reset width", {class_: "fakelink"});
      aEL(wdef, "click", cwidthdef);

      advbox.appendChild(el("P", ["For banner formats, you can ", wset,
                                  " or ", wdef, " to default. Putting silly " +
                                  "tiny values in is likely to break it."]));

      advbox.appendChild(el("P", "If you know what you're doing, you can " +
                                 "base64-decode the data and mess with it."));
   }
   else
      clearps(advbox);
}

function cwidthset()
{
   w = prompt("Custom width:", w ? w : fd[format].w);
   updatenow();
}

function cwidthdef()
{
   w = null;
   updatenow();
}

function choices(list, func)
{
   var ci;
   var c = el("P", null, {class_: "choice"});
   c.choicefunc = func;
   c.choicecurrent = -1;
   for(var i = 0; i < list.length; ++i)
   {
      ci = c.appendChild(el("SPAN", list[i]));
      c.appendChild(document.createTextNode(" "));
      ci.choiceindex = i;
      aEL(ci, "click", onchoiceclick);
   }
   return c;
}

function onchoiceclick(e)
{
   var src = (e.target ? e.target : e.srcElement);
   setchoice(src.parentNode, src.choiceindex);
}

function setchoice(c, index)
{
   var choices = c.getElementsByTagName("SPAN");
   if(c.choicecurrent != -1)
      choices[c.choicecurrent].className = "";

   if(index != -1)
      choices[index].className = "current";

   c.choicecurrent = index;
   c.choicefunc(index);
}

function setformat(index)
{
   format = index;

   clearps(mainform);

   var textopt = ["No Caption", "Random Slogan", "Show Info", "Custom Text..."];
   var logoopt;
   if("biglogo" in fd[format])
      logoopt = ["Small Corrosive", "Small Tube", "Big Corrosive", "Big Tube"];
   else
      logoopt = ["Corrosive Logo", "Tube Logo"];

   var textc = mainform.appendChild(choices(textopt, settext));
   var logoc = mainform.appendChild(choices(logoopt, setlogo));

   // todo: persist these properly!
   setchoice(textc, 2);
   if(logo == -1) logo = 0;
   setchoice(logoc, ("biglogo" in fd[format]) ? logo : logo & 1);

}

function settext(index)
{
   ttype = index;
   if(ttype == 3)
   {
      ctext = prompt("Custom Text:", ctext);
      if(!ctext) ctext = "";
   }

   updatenow();
}

function setlogo(index)
{
   logo = index;

   updatenow();
}

function getimageurl()
{
   if((logo == -1) || (ttype == -1) || (format == -1))
      return "http://img.rdmsoft.com/numb80err.png";

   // defaults are: show info, no biglogo, logo a

   var url = "http://numbcast.com/linkimg/" + fd[format].key;
   var stuff = [];

   if((logo & 2) && ("biglogo" in fd[format]))
      stuff.push("biglogo");

   if(logo & 1)
      stuff.push("logo=b");

   if(ttype != 2)
      stuff.push("tt=" + ttype);

   if(ttype == 3)
      stuff.push("slog=" + ctext);

   if(w && (fd[format].w != w) && !("wfixed" in fd[format]))
      stuff.push("w=" + w);

   if(stuff.length)
      url += "/" + btoa(stuff.join("\n"));

   return url + ".png";
}

function updatenow()
{
   var url = getimageurl();
   prev.src = url;
   updatecode(url);
}

function setcodetype(index)
{
   codetype = index;
   updatecode();
}

function updatecode(url)
{
   if(!url) url = getimageurl();
   var src = "";
   switch(codetype)
   {
   case 0:
      var tw = ((w && !("wfixed" in fd[format])) ? w : fd[format].w);
      src = '<a href="http://numbcast.com/"><img src="' + url +
            '" alt="Numbcast" height="' + fd[format].h +
            '" width="' + tw + '" border="0"></a>';
   break;
   case 1:
      src = '[url=http://numbcast.com/][img]' + url + '[/img][/url]';
   break;
   }
   codearea.value = src;
}

/*
// this is from when i was going to have an INPUT for the text,
// and didn't want to update on every keystroke. might need it later.
function updatesoon()
{
   if(updatetimer) clearTimeout(updatetimer);
   updatetimer = setTimeout(updatenow, 5000);
}
*/

function aEL(node, eventName, func)
{
   if(node.addEventListener)
      node.addEventListener(eventName, func, false);
   else if(node.attachEvent)
      node.attachEvent("on" + eventName, function() { func(window.event); });
}

// blatently stolen from http://snipplr.com/view.php?codeview&id=702
if(typeof btoa == "undefined")
{
var b64ec = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
   var btoa = function( str ) {
      var out = "", i = 0, len = str.length;
      while( i < len ) {
      var c1 = str.charCodeAt( i++ ) & 0xff;
      if( i == len ) {
         out += b64ec.charAt( c1 >> 2 )
            + b64ec.charAt( ( c1 & 0x3 ) << 4 )
            + "==";
         break;
      }
      var c2 = str.charCodeAt( i++ );
      if( i == len ) {
         out += b64ec.charAt( c1 >> 2 )
            + b64ec.charAt( ( ( c1 & 0x3 ) << 4 ) | ( ( c2 & 0xF0 ) >> 4 ) )
            + b64ec.charAt( ( c2 & 0xF ) << 2 )
            + "=";
         break;
      }
      var c3 = str.charCodeAt( i++ );
      out += b64ec.charAt( c1 >> 2 )
         + b64ec.charAt( ( ( c1 & 0x3 ) << 4 ) | ( ( c2 & 0xF0 ) >> 4 ) )
         + b64ec.charAt( ( ( c2 & 0xF ) << 2 ) | ( ( c3 & 0xC0 ) >> 6 ) )
         + b64ec.charAt( c3 & 0x3F );
      }
      return out;
   }
}

aEL(window, "load", linkyload);

