// ********************************************************************
// ocPortal Javascript code. By Chris Graham, with marked contributions
// ********************************************************************

// Bootstrap

function scriptLoadStuff()
{
   if (document.getElementById) // We'll be needing DOM support for everything we do
   {
      forumFrame();
      expandImages();
      fixImages();
      //fixObjectTags();
      doColorChooser();
      doMenuExpansion();

      // Tell ocPortal we have Javascript, so don't degrade things for reasons of compatibility
      document.cookie='js_on=1';
      
/*      // Do a wait (re-render)...
      window.setTimeout("scriptLoadStuff2()",1000);*/
   }
}

/*function scriptLoadStuff2()
{
}*/

// ==========================
// INTERNAL SUPPORT FUNCTIONS
// ==========================

// Found from a site, guessed originally author is Netscape
function SetCookie(cookieName,cookieValue,nDays)
{
   var today = new Date();
   var expire = new Date();
   if (nDays==null || nDays==0) nDays=1;
   expire.setTime(today.getTime()+3600000*24*nDays);
   document.cookie=cookieName+"="+escape(cookieValue)+";expires="+expire.toGMTString();
}

function newLine()
{
   return "\n";
}

function isInteger(val)
{
   if (isBlank(val)) return false;
	for(var i=0;i<val.length;i++)
		if(!isDigit(val.charAt(i))) return false;
	return true;
}

function toggleSectionInline(id)
{
   // Try and grab our item
   var itm=document.getElementById(id);
   var pic=document.getElementById('e_'+id);

   if (itm.style.display=='none')
   {
      itm.style.display='block';
      if (pic) pic.src="http://elizabeth.betterthansuck.com/themes/default/images/contract.png";
   }
   else
   {
      itm.style.display='none';
      if (pic) pic.src="http://elizabeth.betterthansuck.com/themes/default/images/expand.png";
   }
   if (pic)
   {
      fixImage(pic);
   }
}

function changeClass(box,theId,to,from)
{
   if (document.getElementById)
   {
      var cell = document.getElementById(theId);
      if (box.checked)
      {
         cell.className=to;
      }
      else
      {
         cell.className=from;
      }
   }
}

function getMouseX(event)
{
   return event.pageX?event.pageX:event.clientX+getWindowScrollX();
}

function getMouseY(event)
{
   return event.pageY?event.pageY:event.clientY+getWindowScrollY();
}

function getWindowWidth()
{
   if (window.innerWidth) return window.innerWidth-18;
   if ((document.documentElement) && (document.documentElement.clientWidth)) return document.documentElement.clientWidth;
   if ((document.body) && (document.body.clientWidth)) return document.body.clientWidth;
   return 0;
}

function getWindowHeight()
{
   if (window.innerHeight) return window.innerHeight-18;
   if ((document.documentElement) && (document.documentElement.clientHeight)) return document.documentElement.clientHeight;
   if ((document.body) && (document.body.clientHeight)) return document.body.clientHeight;
   return 0;
}

function getWindowScrollX()
{
  	if (window.pageXOffset) return window.pageXOffset;
  	if ((document.documentElement) && (document.documentElement.scrollLeft)) return document.documentElement.scrollLeft;
  	if ((document.body) && (document.body.scrollLeft)) return document.body.scrollLeft;
  	if (window.scrollX) return window.scrollX;
   return 0;
}

function getWindowScrollY()
{
  	if (window.pageYOffset) return window.pageYOffset;
  	if ((document.documentElement) && (document.documentElement.scrollTop)) return document.documentElement.scrollTop;
  	if ((document.body) && (document.body.scrollTop)) return document.body.scrollTop;
  	if (window.scrollTop) return window.scrollTop;
   return 0;
}

function activateTooltip(event,tooltip,width)
{
   if (tooltip=='') return;

   if (event.tooltipId)
   {
      var tooltipElement=document.getElementById(this.tooltipId);
   } else
   {
      var tooltipElement=document.createElement("div");
      tooltipElement.className="ocf_tooltip";
      tooltipElement.innerHTML=tooltip;
      tooltipElement.style.zIndex=1;
      tooltipElement.style.width=width;
      tooltipElement.style.position='absolute';
      tooltipElement.id=Math.floor(Math.random()*1000);
      this.tooltipId=tooltipElement.id;
      document.body.appendChild(tooltipElement);
   }
   tooltipElement.style.display='block';

   repositionTooltip(event);
}

function repositionTooltip(event)
{
   var tooltipElement=document.getElementById(this.tooltipId);
   if (tooltipElement)
   {
      var x=getMouseX(event)+10;
      var y=getMouseY(event)+10;
      var x_excess=x-getWindowWidth()-getWindowScrollX();
      if (x_excess>0) x-=x_excess;
      var y_excess=y-getWindowHeight()-getWindowScrollY;
      if (y_excess>0) y-=y_excess;
      tooltipElement.style.left=x+'px';
      tooltipElement.style.top=y+'px';
   }
}

function deactivateTooltip(event)
{
   var tooltipElement=document.getElementById(this.tooltipId);
   if (tooltipElement)
      tooltipElement.style.display='none';
}

// ===========
// ATTACHMENTS
// ===========

var numAttachments=-1;
function addAttachment(addTo,startNum)
{
   if (numAttachments==-1) numAttachments=startNum;

   numAttachments++;

   // innerHTML won't work, due to table being read-only :(

   var newRow1=addTo.insertRow(-1);
   var newCell11=newRow1.insertCell(-1);
   newCell11.innerHTML="<strong>Attachment "+numAttachments+"</strong>";
   var newCell12=newRow1.insertCell(-1);
   newCell12.innerHTML='Upload';
   var newCell13=newRow1.insertCell(-1);
   newCell13.innerHTML='<input type="file" style="width: 100%" onchange="Javascript: setAttachment('+numAttachments+')" name="file'+numAttachments+'" />';

   var newRow2=addTo.insertRow(-1);
   var newCell21=newRow2.insertCell(-1);
   newCell21.innerHTML="";
   var newCell22=newRow2.insertCell(-1);
   newCell22.innerHTML='Caption';
   var newCell23=newRow2.insertCell(-1);
   newCell23.innerHTML='<input style="width: 100%" type="text" name="caption'+numAttachments+'" />';
}

function setAttachment(number)
{
   var post=document.getElementById('post');
   var done=(post.value.indexOf('[attachment]new_'+number+'[/attachment]')!=-1);
   if ((!done) && (post.value.indexOf('[attachment]new_'+number+'[/attachment]')==-1))
   {
      post.value+='\n\n[attachment]new_'+number+'[/attachment]';
   }
}

// ===========
// Multi-field
// ===========

function _ensureNextField()
{
   ensureNextField(this);
}

function ensureNextField(thisField)
{
   var mid=thisField.name.indexOf('_');
   var nameStub=thisField.name.substring(0,mid+1);
   var thisNum=thisField.name.substring(mid+1,thisField.name.length)-0;

   var nextNum=thisNum+1;
   var nextField=document.getElementById('multi_'+nextNum);
   var name=nameStub+nextNum;
   var thisId=thisField.id;
   if (!nextField)
   {
      var nextNum=thisNum+1;
      var thisField=document.getElementById(thisId);
      var newChild=document.createElement('input');
      newChild.setAttribute('size',50);
      newChild.setAttribute('className','input_line');
      newChild.setAttribute('id','multi_'+nextNum);
      newChild.onkeypress=_ensureNextField;
      newChild.setAttribute('type','text');
      newChild.setAttribute('value','');
      newChild.setAttribute('name',nameStub+nextNum);
      thisField.parentNode.appendChild(newChild);
      var br=document.createElement('br');
      thisField.parentNode.appendChild(br);
   }
}

// ==============================================
// MARKING THINGS (TO AVOID ILLEGAL NESTED FORMS)
// ==============================================

function addFormMarkedPosts(work_on,prefix)
{
   var elements=document.getElementsByTagName('input');
   var i;
   var append='';
   for (i=0;i<elements.length;i++)
   {
      if ((elements[i].type=='checkbox') && (elements[i].name.substring(0,prefix.length)==prefix) && (elements[i].checked))
      {
         append+='&'+elements[i].name+'=1';
      }
   }
   work_on.action+=append;
}

// ====================
// COMCODE UI FUNCTIONS
// ====================

function doInput_html()
{
   insertTextbox(document.getElementById('post'),"[html][/html]");
}

function doInput_code()
{
   insertTextbox(document.getElementById('post'),"[code][/code]");
}

function doInput_list()
{
   var post=document.getElementById('post');
   var va;
   insertTextbox(post,"\n");
   do
   {
      va=window.prompt("Enter the next list entry (or press enter or cancel to finish list)",'');
      if ((va!=null) && (va!='')) insertTextbox(post," - "+va+"\n");
   }
   while ((va!=null) && (va!=''));
}

function doInput_hide()
{
   var va=window.prompt("Enter the warning that is shown in place of the text",'');
   if (va!=null) vb=window.prompt("Enter the text that is only shown if you choose to view it",''); else return;
   if (vb!=null) insertTextbox(document.getElementById('post'),"[hide=\""+va+"\"]"+vb+"[/hide]");
}

function doInput_thumb()
{
   var va="";
   var broken;
   do
   {
      broken=false;
      va=window.prompt("Enter the URL",va);
      if ((va!=null) && (va.indexOf('://')==-1))
      {
         window.alert("This was not a valid URL (URL's contain ://)");
         broken=true;
      }
   }
   while ((va!=null) && (broken));

   if (va!=null) insertTextbox(document.getElementById('post'),"[thumb]"+va+"[/thumb]");
}

function doInput_attachment()
{
   var va=window.prompt("Enter the attachment number (the new attachment you want to be placed at this position)",'');
   if (!isInteger(va))
   {
      window.alert("This is not a valid attachment number");
      return;
   }
   insertTextbox(document.getElementById('post'),"[attachment]new_"+va+"[/attachment]");
}

function doInput_url()
{
   var va="";
   var broken;
   do
   {
      broken=false;
      va=window.prompt("Enter the URL",va);
      if ((va!=null) && (va.indexOf('://')==-1))
      {
         window.alert("This was not a valid URL (URL's contain ://)");
         broken=true;
      }
   }
   while ((va!=null) && (broken));

   var vb;
   if (va!=null) vb=window.prompt("Enter the link name",''); else return;
   if (vb!=null) insertTextbox(document.getElementById('post'),"[url=\""+vb+"\"]"+va+"[/url]");
}

function doInput_email()
{
   var va="";
   var broken;
   do
   {
      broken=false;
      va=window.prompt("Enter the e-mail address",va);
      if ((va!=null) && (va.indexOf('@')==-1))
      {
         window.alert("This was not a valid e-mail address (e-mail addresses contain @)");
         broken=true;
      }
   }
   while ((va!=null) && (broken));

   var vb;
   if (va!=null) vb=window.prompt("Enter the caption",''); else return;
   if (vb!=null) insertTextbox(document.getElementById('post'),"[email=\""+vb+"\"]"+va+"[/email]");
}

function doInput_private_message()
{
	var va=window.prompt("Enter the recipient",'');
	if (va!=null) insertTextbox(document.getElementById('post'),"[private=\""+va+"\"][/private]");
}

function doInput_invite()
{
	var va=window.prompt("Enter the recipient",'');
	if (va!=null) var vb=window.prompt("Enter the chatroom name",'');
	if (vb!=null) insertTextbox(document.getElementById('post'),"[invite=\""+va+"\"]"+vb+"[/invite]");
}

function doInput_new_room()
{
	var va=window.prompt("Enter the chatroom name",'');
	if (va!=null) var vb=window.prompt("Enter the allow list",'');
	if (vb!=null) insertTextbox(document.getElementById('post'),"[newroom=\""+va+"\"]"+vb+"[/newroom]");
}
function insertTextbox(element,text)
{
   element.focus();

   if (document.selection) // IE style
   {
      var sel=document.selection;
      var ourRange=sel.createRange();
      ourRange.text=ourRange.text+text;
      return;
   }
   if (element.selectionEnd) // Mozilla style
   {
      var from=element.selectionStart;
      var to=element.selectionEnd;
      
      var start=element.value.substring(0,from);
      var end=element.value.substring(to,element.value.length);

      if (to>from)
      {
         element.value=start+element.value.substring(from,to)+text+end;
      } else
      {
         element.value=start+text+end;
      }
      return;
   }

   // :(
   element.value+=text;
}

function doInput_b()
{
   insertTextboxWrapping(document.getElementById('post'),"b","");
}

function doInput_i()
{
   insertTextboxWrapping(document.getElementById('post'),"i","");
}

function doInput_font()
{
   var face=document.getElementById('posting_form')._face;
   var size=document.getElementById('posting_form')._size;
   var colour=document.getElementById('posting_form')._colour;
   if ((face.value=='') && (size.value=='') && (colour.value==''))
   {
      window.alert('You must select at least one font option');
      return;
   }
   insertTextboxWrapping(document.getElementById('post'),'[font=\"'+face.value+'\" color=\"'+colour.value+'\" size=\"'+size.value+'\"]','[/font]');
}

function setFontSizes(list)
{
   var i=0;
   for (i=1;i<list.options.length;i++)
   {
      list.options[i].style.fontSize=list.options[i].value+"em";
   }
}

function desetFontSizes(list)
{
   var i=0;
   for (i=1;i<list.options.length;i++)
   {
      list.options[i].style.fontSize="";
   }
}

function insertTextboxWrapping(element,beforeWrapTag,afterWrapTag)
{
   element.focus();

   if (afterWrapTag=="")
   {
      var afterWrapTag="[/"+beforeWrapTag+"]";
      var beforeWrapTag="["+beforeWrapTag+"]";
   }

   if (document.selection) // IE style
   {
      var sel=document.selection;
      var ourRange=sel.createRange();
      ourRange.text=beforeWrapTag+ourRange.text+afterWrapTag;
      return;
   }
   if (element.selectionEnd) // Mozilla style
   {
      var from=element.selectionStart;
      var to=element.selectionEnd;

      var start=element.value.substring(0,from);
      var end=element.value.substring(to,element.value.length);

      if (to>from)
      {
         element.value=start+beforeWrapTag+element.value.substring(from,to)+afterWrapTag+end;
      } else
      {
         element.value=start+beforeWrapTag+afterWrapTag+end;
      }
      return;
   }

   // :(
   element.value+=beforeWrapTag+afterWrapTag;
}

// ===========
// FORUM FRAME
// ===========

var priorFrameLocation='';
function forumFrame()
{
   var forumframe=document.getElementById('forumframe');
   if (forumframe)
   {
      setInterval('resizeForumFrame()',500);
   }
}

function resizeForumFrame()
{
   var forumframe=document.getElementById('forumframe');
   if (top.frames['forumframe'].document.location.href!=priorFrameLocation)
   {
      forumframe.style.height=top.frames['forumframe'].document.body.offsetHeight+'px';
      forumframe.scrolling='no';
      priorFrameLocation=top.frames['forumframe'].document.location.href;
      bumpResize1('force_resize_hack');
   }
}

// ================================================
// RESIZE BUMPING, to ensure no blank space on page
// ================================================

function bumpResize1(name)
{
   var forceResizeHack=document.getElementById(name);
   if (forceResizeHack)
   {
      forceResizeHack.style.display='inline';
      window.setTimeout("bumpResize2('"+name+"')",500);
   }
}

function bumpResize2(name)
{
   var forceResizeHack=document.getElementById(name);
   forceResizeHack.style.display='none';
}

// ==================
// THUMBNAIL FUNCTION
// ==================

// ////
/*
Gradual-Highlight Image Script II-
By J. Mark Birenbaum (birenbau@ugrad.cs.ualberta.ca)
Permission granted to Dynamicdrive.com to feature script in archive
For full source to script, visit http://dynamicdrive.com
*/

nereidFadeObjects=new Object();
nereidFadeTimers=new Object();

/* object - image to be faded (actual object, not name);
 * destop - destination transparency level (ie 80, for mostly solid)
 * rate   - time in milliseconds between trasparency changes (best under 100)
 * delta  - amount of change each time (ie 5, for 5% change in transparency)
 */

function nereidFade(object, destOp, rate, delta)
{
   if (!document.all) return;

   if (object!="[object]")
   {  //do this so I can take a string too
      setTimeout("nereidFade("+object+","+destOp+","+rate+","+delta+")",0);
      return;
   }

   clearTimeout(nereidFadeTimers[object.sourceIndex]);

   if (!object.filters.alpha) return;

   diff = destOp-object.filters.alpha.opacity;
   direction=1;
   if (object.filters.alpha.opacity>destOp)
   {
      direction=-1;
   }
   delta=Math.min(direction*diff,delta);
   object.filters.alpha.opacity+=direction*delta;

   if (object.filters.alpha.opacity!=destOp)
   {
      nereidFadeObjects[object.sourceIndex]=object;
      nereidFadeTimers[object.sourceIndex]=setTimeout("nereidFade(nereidFadeObjects["+object.sourceIndex+"],"+destOp+","+rate+","+delta+")",rate);
   }
}
// ^^^^

// ==============================
// DYNAMIC TREE CREATION FUNCTION
// ==============================

// Creates a tree from a compressed format
function splurgh(key_name,url_stub,range_a,range_b,level, data, chain)
{
   if (range_b==-1) range_b=data.length;
   if ((range_b-range_a)<2) return;

   var to=data.indexOf(",",range_a);
   if ((to==-1) || (to>range_b)) to=range_b;
   var thisdata=data.substring(range_a,to);
   var thisdata2;
   var repspace='';
   var i;
   for (i=0;i<level;i++)
   {
      repspace=repspace+"&nbsp;&nbsp;&nbsp;&nbsp;";
   }
   for (i=0;i<thisdata.length;i++)
   {
      if (thisdata.charAt(i+1)=="!")
      {
         thisdata2=thisdata.substring(0,i+1);
         thisdata=thisdata.substring(i+2,thisdata.length);
         break;
      }
   }

   document.writeln(repspace+"<a name=\""+thisdata2+"\"></a><a href=\""+url_stub+"&amp;chain="+chain+"&amp;"+key_name+"="+thisdata2+"\">"+thisdata+"</a><br />");
   if (to+1<data.length)
   {
      var a=to+1,b=range_b;
      if (data.charAt(to+1)=="[")
      {
         var tutu=to+1,balance=0;
         do
         {
            if (data.charAt(tutu)=="[") balance++;
            if (data.charAt(tutu)=="]") balance--;
            tutu++;
         }
         while (balance!=0);
         a=to+2;
         b=tutu-1;
         splurgh(key_name,url_stub,a,b,level+1,data,chain+"~"+thisdata2);
         a=b+2;
         b=range_b-1;
      }
      splurgh(key_name,url_stub,a,b,level,data,chain);
   }
}

function changeStubbed(theStub,value)
{
   var i,j,theForm,theElement;
   for (i=0;i<document.forms.length;i++)
   {
   	theForm=document.forms[i];
      for (j=0;j<theForm.elements.length;j++)
      {
         theElement=theForm.elements[j];
         if (theElement.name.substring(0,theStub.length+1)==theStub+'_')
         {
      		theElement.disabled=!value;
         }
      }
   }
}

// =========================
// FORM VALIDATION FUNCTIONS
// =========================

function checkFieldForBlankness(field)
{
   if ((field.value=='') || (field.value=="Make your post civil and relevant"))
   {
      return errorNotFilledIn();
   }
   return true;
}

function confirmDelete()
{
   return window.confirm("Are you sure you want to delete this?");
}

function errorNotFilledIn()
{
   window.alert("You did not fill in all required fields on the form correctly");
   return false;
}

function errorNotInteger()
{
   window.alert("A field that was supposed to be an integer (whole number) was not");
   return false;
}

function errorNotFloat()
{
   window.alert("A field that was supposed to be a decimal number was not");
   return false;
}

function checkForm(theForm)
{
   var j,theClass,theElement,required;
   for (j=0;j<theForm.elements.length;j++)
   {
      theElement=theForm.elements[j];

      if (theElement.type=='hidden')
      {
         if (theElement.name=='js_on') theElement.value='1';
      }

      theClass=theElement.className;

      if ((theElement.name=='delete') && (theClass=='input_tick') && (theElement.checked)) return confirmDelete();

      required=theClass.indexOf('_required');
      myValue=theElement.value;
      if ((required!=-1) && (theElement.value==''))
      {
         return errorNotFilledIn();
      }
      if (((theClass=='input_integer') || (theClass=='input_integer_required')) && (myValue!='') && (parseInt(myValue)!=myValue-0))
      {
         return errorNotInteger();
      }
      if (((theClass=='input_float') || (theClass=='input_float_required')) && (myValue!='') && (parseFloat(myValue)!=myValue-0))
      {
         return errorNotFloat();
      }
   }

   document.getElementById('form_submit').disabled=true;

   return true;
}

// ===========
// OBJECT HACK
// ===========

/*

Doesn't work :(

function fixObjectTags()
{
   var tags=document.getElementsByTagName('object');
   for(var i=0;i<tags.length;i++)
   {
      if (tags[i].getAttribute('classid'))
      {
         tags[i].removeAttribute('classid');
      }
   }
}*/

// ========
// PNG HACK
// ========

// This is VERY LOOSLY based on Erik Arvidsson's work (http://webfx.eae.net/dhtml/pngbehavior/pngbehavior.html)
// Pretty much none of it except the browser and PNG checks remain.
// UPDATE: Now based on PieNG (http://dynarch.com/mishoo/articles.epl?art_id=430)

function isBrokenAlphaIE()
{
   return ((/MSIE ((5\.5)|[6789])/.test(navigator.userAgent)) && (navigator.platform=="Win32"));
}

function fixImages()
{
   if (isBrokenAlphaIE())
   {
      for(var i=0;i<document.images.length;i++)
      {
         var img = document.images[i];
         fixImage(img);
      }
   }
}

function fixImage(img)
{
   var imgName = img.src.toUpperCase();
   if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
   {
      var imgClass = (img.className) ? "class='" + img.className + "' " : "";
      if ((img.className) && (img.className=='blend'))
      {
         srcURL=img.src;
         img.src="http://elizabeth.betterthansuck.com/data/images/blank.gif";
         img.runtimeStyle.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+srcURL+"',sizingMethod='image'); ";
      }
   }
}

// ===================
// EXPANDED THUMBNAILS
// ===================

function expandImages()
{
   var te_pos=document.URL.indexOf('&te_');
   if (te_pos==-1) return;
   var a=document.URL.indexOf('=1',te_pos);
   var b=document.URL.indexOf('=0',te_pos);
   if (((b<a) && (b!=-1)) || (a==-1)) return;
   var to_do=document.URL.substring(te_pos+4,a);

   if (to_do=='all')
   {
      var i;
      var posts=document.getElementsByTagName('td');
      for (i=0;i<posts.length;i++)
      {
         if (posts[i].id.substring(0,3)=='pe_')
         {
            expandPost(posts[i]);
         }
      }
   } else expandPost(document.getElementById('pe_'+to_do));
}

function expandPost(post)
{
   var i;
   var images=post.getElementsByTagName('img');
   for (i=0;i<images.length;i++)
   {
      var first=2;
      var second=images[i].id.indexOf('_',first+1);
      if (second==-1) continue;
      var pass_id=images[i].id.substring(first+1,second);
      var full_url=images[i].id.substring(second+1);
      images[i].src=full_url;
      images[i].thumb_expanded=1;
   }
}

// ===============
// EXPANDING MENUS
// ===============

function doMenuExpansion()
{
   // Go through menu expanders
   menuArr=document.getElementsByTagName('div');
   var i;
   for (i=0;i<menuArr.length;i++)
   {
      if (menuArr[i].id.indexOf('_expand_')!=-1)
      {
         url_expanded=document.URL.indexOf('keep_'+menuArr[i].id);
         if ((url_expanded==-1) && (menuArr[i].style.display=='inline'))
         {
            menuArr[i].style.display='none';
         }
      }
   }
}

function toggleSection(id)
{
   // Try and grab our item
   var itm=document.getElementById(id);

   if (itm.style.display=='none')
      itm.style.display='block';
   else itm.style.display='none';

   //bumpResize1('force_resize_hack_menu');
}

// ================
// TRANSLATION PAGE
// ================

// Call the hidden 'hack_form' to go run the translation site upon our language string, and direct into our personal iframe
function translate(name,old)
{
   toggleSection('exp_'+name);

   var form=document.getElementById('hack_form');
   form.target='iframe_'+name;
   var input_text=document.getElementById('hack_input');
   input_text.value=old;
   form.submit();
}

// ==============
// COLOUR CHOOSER
// ==============

function decToHex(number)
{
   var hexbase="0123456789ABCDEF";
   return hexbase.charAt((number>>4)&0xf)+hexbase.charAt(number&0xf);
}

function hexToDec(number)
{
   return parseInt(number,16);
}

var last_cc=new Array();
var last_cc_i=new Array();
function doColorChange(e)
{
   // Find our colour element we clicked on
   if (!e) var e=window.event;
   var targ;
	if (e.target) targ=e.target;
	else if (e.srcElement) targ=e.srcElement;

   // Find the colour chooser's ID of this element
   var _id=parseInt(targ.id.substring(targ.id.lastIndexOf('#')+1));

   // Show a white line over the colour we clicked
   targ.setAttribute('bgColor','#FFFFFF');

   // Get the ID of the element we clicked (format: cc_col_<0-2>_<0-255>#<chooser-id>)
   var id=targ.id;

   var b=id.lastIndexOf('_');

   var d=parseInt(id.substring(7,b)); // Get the colour row (0-2)
   var i=parseInt(id.substring(b+1,id.indexOf('#'))); // Get the colour (0-255)

	var rgb=new Array;
	rgb[0]=0; rgb[1]=0; rgb[2]=0;
	rgb[d]=last_cc_i[d+_id*3];
	last_cc[d+_id*3].setAttribute('bgColor','#'+decToHex(rgb[0])+decToHex(rgb[1])+decToHex(rgb[2]));
   last_cc[d+_id*3]=targ;
   last_cc_i[d+_id*3]=i;

   var element=document.getElementById('cc_target_'+_id);
   var bgColor=element.getAttribute('bgColor');

   var _rgb=new Array;
   _rgb[0]=bgColor.charAt(1)+bgColor.charAt(2);
   _rgb[1]=bgColor.charAt(3)+bgColor.charAt(4);
   _rgb[2]=bgColor.charAt(5)+bgColor.charAt(6);
   _rgb[d]=decToHex(i);
   element.setAttribute('bgColor','#'+_rgb[0]+_rgb[1]+_rgb[2]);
   element.style.color='#'+decToHex(255-hexToDec(_rgb[0]))+decToHex(255-hexToDec(_rgb[1]))+decToHex(255-hexToDec(_rgb[2]));

   var finality=document.getElementById('color-'+_id);
   finality.setAttribute('value','#'+_rgb[0]+_rgb[1]+_rgb[2]);
}

function doColorChooser()
{
	var elements=document.getElementsByTagName('td');
	var ce,a=0,my_elements=new Array;
	for (ce=0;ce<elements.length;ce++)
	{
		if (elements[ce].id.substring(0,10)=='cc_target_')
      {
      	my_elements[a]=elements[ce];
      	a++;
      }
	}
	for (ce=0;ce<a;ce++)
	{
   	doColorChooserElement(my_elements[ce]);
	}
}

function doColorChooserElement(element)
{
   var id=element.id.substring(10);

   var source=document.getElementById('cc_source_'+id);
   var s_rgb=source.getAttribute('bgColor');
   var rgb=new Array;
   rgb[0]=hexToDec(s_rgb.charAt(1)+s_rgb.charAt(2));
   rgb[1]=hexToDec(s_rgb.charAt(3)+s_rgb.charAt(4));
   rgb[2]=hexToDec(s_rgb.charAt(5)+s_rgb.charAt(6));
   rgb[0]=Math.round(rgb[0]/4)*4;
   rgb[1]=Math.round(rgb[1]/4)*4;
   rgb[2]=Math.round(rgb[2]/4)*4;
   if (rgb[0]>=256) rgb[0]=252;
   if (rgb[1]>=256) rgb[1]=252;
   if (rgb[2]>=256) rgb[2]=252;

   element.style.color='#'+decToHex(255-rgb[0])+decToHex(255-rgb[1])+decToHex(255-rgb[2]);
   source.style.color=element.style.color;

	var c=new Array;

	c[0]=document.getElementById('cc_0_'+id);
	c[1]=document.getElementById('cc_1_'+id);
	c[2]=document.getElementById('cc_2_'+id);

	var d,i,_rgb=new Array,col;
	for (d=0;d<=2;d++)
	{
//   	for (i=0;i<256;i++)
   	for (i=0;i<256;i+=4)
   	{
   		col=document.createElement('td');
         if (i!=rgb[d])
         {
      		_rgb[0]=0; _rgb[1]=0; _rgb[2]=0;
         	_rgb[d]=i;
         } else
         {
      		_rgb[0]=255; _rgb[1]=255; _rgb[2]=255;
      		last_cc[d+id*3]=col;
      		last_cc_i[d+id*3]=i;
         }
   		col.setAttribute('bgColor','#'+decToHex(_rgb[0])+decToHex(_rgb[1])+decToHex(_rgb[2]));
//   		col.setAttribute('width','2');
   		col.setAttribute('width','8');
   		col.setAttribute('height','15');
   		col.setAttribute('id','cc_col_'+d+'_'+i+'#'+id);
   		col.onclick=doColorChange;
   	   c[d].appendChild(col);
   	}
	}
}



