/*
** we're using the jQuery based javascript, but our design pattern will be
** the Yui object paradigm which is much better at stability and 
** expandability.
*/
var Remax = (("undefined" == typeof Remax) || (!Remax)) ? {} : Remax;

/**
*
*  Javascript sprintf
*  http://www.webtoolkit.info/
*
*
**/
Remax.sprintfWrapper =
{
    
  gexp:
    new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g)

, init : function ()
  {
    if (typeof arguments == "undefined")  { return null; }
    if (1 > arguments.length)		  { return null; }
    if (typeof arguments[0] != "string")  { return null; }
    if (typeof RegExp == "undefined")	  { return null; }

    var exp		= Remax.sprintfWrapper.gexp
      , convert		= Remax.sprintfWrapper.convert
      , string		= arguments[0]
      , matches		= new Array()
      , strings		= new Array()
      , convCount	= 0
      , stringPosStart	= 0
      , stringPosEnd	= 0
      , matchPosEnd	= 0
      , newString	= ''
      , match		= null
      , neg		= false
      , arg		= ''
      , code		= null
      , i		= null
      ;
    while (match = exp.exec(string))
    {
      if (match[9]) { convCount += 1; }

      stringPosStart	      = matchPosEnd;
      stringPosEnd	      = exp.lastIndex - match[0].length;
      strings[strings.length] = string.substring( stringPosStart,
						  stringPosEnd);
      neg = (0 > parseInt(arguments[convCount])) ? true : false;
      arg = String(arguments[convCount])


      matchPosEnd	      = exp.lastIndex;
      matches[matches.length] = { match:      match[0]
				, left:	      match[3] ? true : false
				, sign:	      match[4] || ''
				, pad:	      match[5] || ' '
				, min:	      match[6] || 0
				, precision:  match[8]
				, code:	      match[9] || '%'
				, negative:   neg
				, argument:   arg
				};
    }
    strings[strings.length] = string.substring(matchPosEnd);

    if (matches.length == 0)		    { return string;  }
    if (convCount > (arguments.length - 1)) { return null;    }

    match = i = null;

    for (i=0; i < matches.length; i++)
    {
      if      ('%' == matches[i].code)	{ substitution = '%' }
      else if ('b' == matches[i].code)
      {
	matches[i].argument =
	  String(Math.abs(parseInt(matches[i].argument)).toString(2));

	substitution = convert(matches[i], true);
      }
      else if ('c' == matches[i].code)
      {
	matches[i].argument =
	  String(
	    String.fromCharCode(
	      parseInt(Math.abs(parseInt(matches[i].argument)))));

	substitution = convert(matches[i], true);
      }
      else if ('d' == matches[i].code)
      {
	matches[i].argument =
	  String(Math.abs(parseInt(matches[i].argument)));

	substitution = convert(matches[i]);
      }
      else if ('f' == matches[i].code)
      {
	matches[i].argument =
	  String(
	    Math.abs(parseFloat(matches[i].argument)		    ).
	    toFixed(matches[i].precision ? matches[i].precision : 6));

	substitution = convert(matches[i]);
      }
      else if ('o' == matches[i].code)
      {
	matches[i].argument =
	  String(Math.abs(parseInt(matches[i].argument)).toString(8));

	substitution = convert(matches[i]);
      }
      else if ('s' == matches[i].code)
      {
	matches[i].argument =
	  matches[i].argument.
	    substring(0,
		      matches[i].precision ?
		      matches[i].precision : matches[i].argument.length);

	substitution = convert(matches[i], true);
      }
      else if ('x' == matches[i].code)
      {
	matches[i].argument =
	  String(Math.abs(parseInt(matches[i].argument)).toString(16));

	substitution = convert(matches[i]);
      }
      else if ('X' == matches[i].code)
      {
	matches[i].argument =
	  String(Math.abs(parseInt(matches[i].argument)).toString(16));
	  
	substitution = convert(matches[i]).toUpperCase();
      }
      else
      {
	substitution = matches[i].match;
      }
      newString += strings[i];
      newString += substitution;
    }
    newString += strings[i];

    return newString;
  }
  
, convert : function (match, nosign)
  {
    if (nosign) { match.sign = '';				  }
    else	{ match.sign = match.negative ? '-' : match.sign; }

    var l = match.min - match.argument.length + 1 - match.sign.length
      ;
    var pad = new Array((l < 0) ? 0 : l).join(match.pad)
      ;
    if (!match.left)
    {
      if (match.pad == '0' || nosign)
      {
	return match.sign + pad + match.argument;
      }
      else
      {
	return pad + match.sign + match.argument;
      }
    }
    else
    {
      if (match.pad == '0' || nosign)
      {
	return match.sign + match.argument + pad.replace(/0/g, ' ');
      }
      else
      {
	return match.sign + match.argument + pad;
      }
    }
  }
}

Remax.System = function ()
{
  /*  
  ******************************************************************
  ** private variables available only to methods of the module.
  */
  var c_do  = false
    , w_do  = false
    , p_do  = false
    , s_do  = false
    , g_do  = false
    , dtop  = null
    ;
  /*  
  ** private shorthand variables to comon YUI/Prototype parts/utilities
  */

  /*  
  ** private shorthand variable for built YUI objects. set in init()
  */
  
  /*  
  ** constants used in this module.
  */

  /*  
  ** module state:
  */
  var once  = false
    , id    = 0
    ;
  /*  
  ** these are Dom refrences that won't change, they are set by direct
  ** calls when needed, and then used freely after that.
  */
  var chalkboard  = null
    ;

  /*  
  ** ******************************************************************
  ** private methods available only to other methods of the module.
  */

  /*
  ** generic page based event handler
  */
  var event_handler = function (ev)
  {
    var el  = null
      , val = 0
      , whc = 0;

    if ((!ev) || (!(el = ev.target)))
    {
      return;
    }
    el = $(el);

    while (el != dtop)
    {
      $('#debug').append('<h1>val = ' + val + ', id: ' + el[0]['id']
                        + '</h1><h2>"Graphics" for id = '
                        + '</h2><h2>"DIV" for tag Name = '
                        + ('DIV' == el[0]['tagName'])
                        + '</h2><h2>el.hasClass() = '
                        + el.hasClass('clickable') + '</h2><ul>'
                        + '<li>tagName: ' + el[0]['tagName'] + '</li>'
                        + '</ul>');
      /*
      ** handle click's
      */
      if (!el)
      {
        break;
      }
      if ('click' == ev.type)
      {
        if (('DIV' == el[0]['tagName']) && (el.hasClass('clickable')))
        {
          if ('clickhere' == el[0]['id'])
          {
            if (c_do)
            {
              $('#debug').append('<h4>here hiding</h4>');
              $('#show, #boxes, #grow1').hide('slow');
            }
            else
            {
              $('#debug').append('<h4>here showing</h4>');
              $('#show, #boxes, #grow1').show('slow');
            }
            c_do = !c_do
            break;
          }
          if (('Graphics'     == el[0]['id']) ||
              ('Web-Design'   == el[0]['id']) ||
              ('Programming'  == el[0]['id']) ||
              ('SEO'          == el[0]['id']))
          {
            $('#grow2, #grow3, #grow4, #grow5').hide('slow');

            if ('Graphics' == el[0]['id'])
            {
              whc = 'g_do';

              if (!(val = g_do))
              {
                $('#grow2').show('slow');
              }
            }
            else if ('Web-Design' == el[0]['id'])
            {
              whc = 'w_do';

              if (!(val = w_do))
              {
                $('#grow3').show('slow');
              }
            }
            else if ('Programming' == el[0]['id'])
            {
              whc = 'p_do';

              if (!(val = p_do))
              {
                $('#grow4').show('slow');
              }
            }
            else
            {
              whc = 's_do';

              if (!(val = s_do))
              {
                $('#grow5').show('slow');
              }
            }
            g_do = w_do = p_do = s_do = false;

            eval(whc + '  = !val');
            break;
          }
        }
      }
      else if ('change' == ev.type)
      {
      }
      else if ('keyup' == ev.type)
      {
      }
      val++;

      el = $(el).parent();
      if ((!(val % 10)) && (confirm('quit')))
      {
        break;
      }
    }
  };

  var that =
    /*
    ** publicly accessible variables where we store AJAX results by
    ** evaluating valid js pointing to these arrays.
    */
    { translations: [] // Remax.System.translations[]

      /*
      ** Public Remax.System.erudiate()	- Erudiate means to instruct or
      **				  teach us.  Here we mean teaching
      **    us about the contents of some obscure object in an easy to use
      **    jQuery dialog.  This function builds the dialog, or resets it.
      **
      **  @param mixed obj    - The object to display.
      **  @param string name  - The name of the object we will display.
      **  @param bool wide    - If true, build fully expanded.
      **  @return null
      **  @side-effect	- Opens a dialog filled with information about the
      **		  object item.
      */
    , erudiate:	function (obj, name, wide)
      {
	var content = null
	  ;
	if (!chalkboard) // Remax object private scope item.
	{
	  chalkboard = $('<div id="tic_sys_chalkboard"></div>');

	  $(document).append(chalkboard);
	  $(chalkboard).dialog( { autoOpen: false 
				, modal:    true 
				, width:    539 
				, height:   254 
				});
	}
	content = that.imbue(obj, name, wide);

	$(chalkboard).html(content.html());
	$(chalkboard).dialog('open');
      }

      /*
      ** Public Remax.System.imbue() -- Imbue is another word for 'to teach'
      **				or 'instuct'.  In this case we mean
      **    to show us the contents of some obscure object in an html layout
      **    that we ajaxify to expand on sub items by click.
      **
      **  @param mixed obj    - The object to display.
      **  @param string name  - The name of the object we will display.
      **  @param bool wide    - If true, build fully expanded.
      **  @return object      - The jQuery HTML object for display.
      */
    , imbue:  function (obj, name, wide)
      {
	var fieldset  = null
	  , legend    = null
	  , div	      = null
	  , index     = null
	  , item      = null
	  , ul	      = null
	  , part      = null
	  , d_id      = 'tic_sys-d-' + id
	  , click     = null
	  , b_id      = null
	  , o_id      = null
	  , l_id      = null
	  , expand    = null
	  ;
	click = function ()
	{
	  alert('clicking [' + d_id + ']');
	  $('#' + d_id).toggle();
	};
	id++;

	l_id	  = 'tic_sys-l-' + id;
	fieldset  = $('<fieldset></fieldset>');
	legend	  = $('<legend id="' + l_id + '">' + name + '</legend>');
	div	  = $('<div id="' + d_id + '"></div>');

	id++;

	// Interior contents

	ul = $('<ul>' + (typeof obj) + ' contents:<br /></ul>');

	if (('object' == typeof obj) || ('array' == typeof obj))
	{
	  for (index in obj)
	  {
	    var item  = obj[index]
	      ;
	    if (undefined == item)
	    {
	      part = $('<li><b>.' + index + '</b> = undefined</li>');
	    }
	    else if ('integer' == typeof item)
	    {
	      part = $('<li><b>.' + index + '</b> = ' + item + '</li>');
	    }
	    else if ('string' == typeof item)
	    {
	      part = $('<li><b>.' + index + '</b> = "' + item + '"</li>');
	    }
	    else if ('array' == typeof item)
	    {
	      if (wide)
	      {
		var content = that.imbue(item, index, wide)
		  ;
		html  = '<li><b>' + index + '</b></li>';
		part  = $(html).append(content);
	      }
	      else
	      {
		b_id    = 'tic_sys-b-' + id;
		expand  = function ()
		{
		  alert('expanding [' + b_id + ']');
		  var content = that.imbue(item, index)
		    ;
		  $('#' + b_id).parent().html(content);
		};
		id++;
		html  = '<li><b class="b" id="' + b_id + '">.' + index
		      + '</b> (array click to expand)</li>'
		part  = $(html);
		qual = '#' + b_id;

		$(qual).css({backgroundColor: 'blue'});
		$(qual).click(expand).addClass('ticode_system-processed');
	      }
	    }
	    else if ('object' == typeof item)
	    {
	      if (('nextSibling'    != index) && ('document'	!= index) &&
		  ('parentElement'  != index) && ('namespaces'	!= index) &&
		  ('parentTextEdit' != index) && ('ownerElement'!= index) &&
		  ('ownerDocument'  != index) && ('offsetParent'!= index) &&
		  ('previousSibling'!= index) && ('parentNode'	!= index))
	      {
		if (wide)
		{
		  var content = that.imbue(item, index, wide)
		    ;
		  html  = '<li><i>' + index + '</i></li>';
		  part  = $(html).append(content);
		}
		else
		{
		  o_id    = 'tic_sys-o-' + id;
		  stretch = function ()
		  {
		    alert('stretching [' + o_id + ']');
		    var content = that.imbue(item, index)
		      ;
		    $('#' + o_id).parent().html(content);
		  };
		  id++;
		  html  = '<li><b class="o" id="' + o_id + '">.' + index
			+ '</b> (object click to expand)</li>'
		  part  = $(html);
		  qual = '#' + o_id;

		  $(qual).css({ backgroundColor: 'red'});
		  $(qual).click(stretch).
			    addClass('ticode_system-processed');
		}
	      }
	    }
	    else 
	    {
	      part = $(	'<li><b>.' + index +
			'</b> item type of [' + (typeof item) +
			'] is not explicitly handled by function ' +
			'Remax.System.imbue</li>');
	    }
	    $(ul).append(part);
	  }
	}
	else if ('integer' == typeof obj)
	{
	  $(ul).append('<em>' + obj + '</em>');
	}
	else if ('string' == typeof obj)
	{
	  $(ul).append('<i>"' + obj + '"</i>');
	}
	if (!wide)
	{
	  div.hide();
	}
	div.append(ul);
	$(fieldset).append(legend);
	$(fieldset).append(div);

	if (wide)
	{
	  qual  = '#' + l_id;

	  $(fieldset).append('<b>' + qual + '</b>');

	  $(qual).css({backgroundColor: 'green' });
	  $(qual).click(click).addClass('ticode_system-processed');
	}
	return fieldset;
      }
    };
      /*
      ** for finding .attr('style', 'background:#ee9933');
      */
        //attr('style', 'background:#ee9933');

  return that;

}(); // the parens here cause the anonymous func to execute and return


