/* Copyright 2007 Allurent Inc. 
 *  
 * 
 */ 

var arcEnabled        = true;
var arcDebugEnabled   = false;
var arcTimerEnabled   = false;

if (typeof(arc)=="undefined")
{
        
    var arc = Class.create({


    });
    
    
    Object.extend(arc,{
        version:"2.1",
        setFlashVersionRequired:function(_num){this.config.baseFlashVersion=_num;},
        setDownloadRateRequired:function(_num){this.config.baseDownloadRate=_num;},
        debug:function(str){return},
        _startMode:$([]),
        canvas:null,
        preInitDebugInfo:$A([]),
        start:function (list,arcPageDesc) {
            // off switch
            if (!arcEnabled) return;

            if ( arcPageDesc != undefined ) 
            {
                arc.pageDesc = arcPageDesc;
            }

            // register mode to use during window init
            if ( arc.util.isArray(list) ) 
            {
                $A(list).each(function(item){ arc._startMode.push(item); } );
            } else {
                this._startMode.push(list);
            }
            this._startMode=$(this._startMode).compact().uniq();

            // to debug or not to debug
            if ( arc.util.isDebugEnabled(arcPageDesc) )
            {
                
                Event.observe ( window , "load" , function (event) {
                        if ( $("_arc_debug_area") == null ){
                         arc.util.newDebugConsole(arcPageDesc);
                         arc.util.debugConsoleInit();
                         arc.debug=arc.util.debugConsoleWriter;
                         arc.preInitDebugInfo.each( function(str) { arc.debug( str, "#666666")  } );
                         arc.debug(" === pre debug console initialization info above this line ===   ");
                        }
                    });
                
                arc.debug = function(val) { arc.preInitDebugInfo.push( val ); }
            }
            
        },
        hasInitialized:false,        
        initialize:function() {
                arc.util.timeNote("arc initializing");
                if ( this.hasInitialized ) return;
                arc.debug( " *** intitialize " );
                this.canvas=arc.util.getCanvas();
                this.startSniff();
                arc.debug("start Up complete.\nArc version:" + arc.version + "\n\tstart mode:"+ Object.inspect( arc._startMode ));
                this.hasInitialized=true;
        },
        addEventListener:function(_tag,_callback){
            arc.debug(" *** adding arc EventListener " + _tag + " "+ typeof ( _callback )) ;
            arc.EventMgr.addEventListener(_tag,_callback);
        },
        dispatchEvent:function(_event){
            arc.debug(" *** arc.dispatchEvent " + _event.type , "green");
            arc.util.debugObjInfo(_event);
            switch(arc.sniffState){
            case "complete":
                arc.debug("arc.sniffState is complete");
                arc.ClientMgr.handleEvent(_event);
                break;
            case "failed":
                break;
            default:
                arc.debug("arc.sniffState:default case");
                // sniff is still doing it's thing
                switch(_event.type)
                {
                case "arcSniffFailed":
                    arc.dispatchEvent({type:"arcInitFailed",reason:_event.reason});
                    break;
                case  "arcSniffComplete":
                    arc.EventMgr.clearEventTimer("arcInitFailed");
                    arc.debug("this.sniffState "+ this.sniffState);
                    if(this.sniffState==""){
                        arc.util.setCookie(arc.config.cookies['sniffCookie'],_event.kps );
                        arc.util.judgeDownloadRate(_event.kps);
                    }
                    break;
                case "arcPreloadComplete":
                    if(this.sniffState=="loading"){
                        setTimeout("arc.ClientMgr.preloadNext();",100);
                    }
                    break;
                }
            }
            arc.EventMgr.dispatchEvent(_event);
        },
        ClientMgr:function(){},
        EventMgr:function(){},
        config:function(){},
        util:function(){},
        startMode:function(key){
            arc.debug("start mode testing:"+key+" "+$(arc._startMode).include(key));
            return $(arc._startMode).include(key);
        },
        startPreload:function()
        {
            arc.debug(" *** start preload ");
            arc.dispatchEvent({type:"arcStartComplete"});
            arc.ClientMgr.startPreload();
        }
    }); // end ARC object extend




    // SNIFF
    // SNIFF
    Object.extend(arc ,
                  {
                      sniffState:"",
                      startSniff:function()
                      {
                          arc.debug(arc.config.cookies['sniffCookie']);

                          var downLoadRate = arc.util.getCookie(arc.config.cookies['sniffCookie']);
                          arc.debug( " download rate " + downLoadRate );
                          if ( downLoadRate == null ) 
                          {
                              this.sniffSwf = arc.util.createSwf({id:"sniff2",url:ARC_SNIFF_URL,params:{
                                  height:(arcDebugEnabled==true)?30:1,
                                  width:(arcDebugEnabled==true)?280:1,
                                  backgroundColor:(arcDebugEnabled==true)?"#6699cc":"#ffffff"}});
                              this.sniffSwf.addVariable("versionChecked",true);
                              this.sniffSwf.addVariable("measure","true");
                              this.sniffSwf.addVariable("targetUrl",ARC_MEASURE_URL );
                              this.sniffSwf.addVariable("sufficientBytes",30000);
                              this.sniffSwf.addVariable("timeout",5000);
                              var _arcSnDiv=$(document.createElement("DIV"));
                              Element.setStyle ( _arcSnDiv ,(arcDebugEnabled==true)?{ 
                                      position:'absolute',top:1000,left:0 }:{
                                      position:'absolute',top:-2,left:-2});
                              arc.util.getCanvas().appendChild(_arcSnDiv);
                              var test = this.sniffSwf.write(_arcSnDiv);
                              if(!test){
                                  arc.debug("writing swf failed... " );
                                  this.sniffState="failed";
                                  arc.dispatchEvent({type:"arcInitFailed",reason:"noflash"});
                              }else{
                                  arc.debug("writing swf succeeded");
                                  arc.debug("innerHTML:"+$(_arcSnDiv).innerHTML);
                                  arc.debug("JS access test " + $("sniff2"));
                                  arc.EventMgr.addEventTimer( "arcInitFailed" , window.setTimeout("arc.showFailure('arcInitFailed','noEventDispatched');",15000));
                              }
                          }else{
                              arc.util.judgeDownloadRate(downLoadRate);
                          }
                      },
                      showFailure:function(_type,_reason)
                      {
                          this.sniffState="falied";
                          arc.dispatchEvent({type:_type,reason:_reason});
                      }
                  });

    // CLIENT DESC
    // CLIENT DESC
    Object.extend(arc ,
                  {
                      ClientDesc:function(_id,_url,_params,_launchEvents)
                      {
                          arc.debug("NEW clientDesc ");
                          this.id=_id;
                          this.url=_url;
                          this.params=(_params)?_params:$();
                          this.launchEvents=[];
                          for(i in _launchEvents){
                              this.launchEvents[_launchEvents[i]]=true;
                           }
                          this.swf;
                          this.flashVars;
                          // states
                          this.started=false;
                          this.visible=false;
                          this.preload=true;

                          arc.ClientMgr.addClientDesc(this);
                      }
                  });
    Object.extend(arc.ClientDesc.prototype ,
                  {
                      states:[],
                      handleEvent:function(_event)
                      {
                          // called after swf started
                          arc.debug("ClientDesc.handleEvent " + _event.type + " started = " + this.started);
                          if (this.started && this.swf ) 
                          {
                              arc.debug(" passing event to started swf object type:"+_event.type);
                              
                              var _handled=(this.swf.arcHandleEvent)?this.swf.arcHandleEvent(_event):null;
                              arc.debug(" _handle: " + ( typeof (_handle) ));
                              switch(_handled)
                              {
                              case true:
                                  arc.debug("client handled:true");
                                  break;
                              case false:
                                  arc.debug("client handled:false");
                                  break;
                              default:
                                  arc.debug("Error:swf.arcHandleEvent=ambiguos..(browserBridge initialized?)","red");
                                  //arc.util.debugObjInfo(this.swf);
                                  //alert("ERROR: event not handled");
                              }
                          }
                      },
                      initSwf:function()
                      { 
                          arc.debug(" *** initSwf ");
                          if ( this.swfObj == null )
                          {
                              this.swfObj = arc.util.createSwf( this ) ;
                              this.swfObj.addVariable("clientId", this.id);
                              this.swfObj.addVariable("applicationName", this.applicationName != null ? this.applicationName : this.pendingEvent.type);
                              this.swfObj.addParam("allowScriptAccess", "always");
                              if (this.flashvars != null)
                              {
                                  for (var varName in this.flashvars)
                                  {
                                      if (Object.prototype[varName] === undefined)
                                          this.swfObj.addVariable(varName, this.flashvars[varName]);

                                  }
                              }
                          }
                      },
                      preShow:function(){},
                      showSwf:function()
                      {
                          this.preShow();
                          arc.debug(" *** showSwf ");
                          if ( this.params.parentElement != null ) 
                          {
                              this.swfDiv = this.params.parentElement;
                              if ( this.params.parentElementStyle )
                                  Element.setStyle ( this.swfDiv , this.params.parentElementStyle );
                          } else if ( this.params.anchorElement != null ) {
                              if (!Element.childElements(arc.util.getCanvas()).include( this.swfDiv ) )
                              {
                                  this.swfDiv = $(document.createElement("div"));
                                  arc.util.getCanvas().appendChild( this.swfDiv ) ;
                              }
                             if ( this.params.anchorElementStyle )
                                  Element.setStyle ( this.swfDiv , this.params.anchorElementStyle );

                          } else {

                              if ( ! Element.childElements(arc.util.getCanvas()).include( this.swfDiv ) )
                              {
                                  this.swfDiv = $(document.createElement("div"));
                                  arc.util.getCanvas().appendChild( this.swfDiv ) ;
                              }
                              if ( this.params.elementStyle )
                                  Element.setStyle ( this.swfDiv , this.params.elementStyle );
                          }
                          
                          this.swfObj.write(this.swfDiv);
                          arc.debug(this.swfObj.getSWFHTML());
                          //this.swf=document.getElementById(this.id);
                          this.swf=$(this.id);
                          arc.debug(this.swf);
                          Element.show(this.swfDiv);                          
                          this.postShow();
                      },
                      postShow:function(){},
                      preClose:function(){},
                      handleClose:function()
                      {
                          this.preClose();
                          arc.debug(" *** handleClose ");
                          Element.hide(this.swfDiv);
                          this.visible=false;
                          this.postClose();
                          return false;                          
                      },
                      postClose:function(){},
                      handleStart:function(){
                          arc.debug(" *** handleStart started:" + this.started );
                          if(!this.started){
                              this.started=true;
                              if(!this.visible) this.showSwf();
                          }
                          if(this.pendingEvent!=null){                                
                              arc.debug("pendingEvent:" + this.pendingEvent );
                              this.handleEvent(this.pendingEvent);
                              this.pendingEvent=null;
                          }
                      }
                  });


    // CLIENT MANAGER
    // CLIENT MANAGER
    Object.extend(arc.ClientMgr,
                  {
                      _clients:$A([]),
                      _preloadList:$A([]),
                      startPreload:function()
                      {

                          var _arcPreloadDiv=$(document.createElement("DIV"));
                          _arcPreloadDiv.id="arcPreloadDiv";
                          arc.util.getCanvas().appendChild(_arcPreloadDiv);
                          arc.debug(" *** ClientMgr startPreload ");
                           arc.ClientMgr._clients.each(function(client){
                               arc.debug("client.preload:"+client.preload);
                               if (client.preload) {
                                       arc.ClientMgr._preloadList.push(client.url);
                                       arc.debug(client.url);
                               }
                          });
                          arc.ClientMgr._preloadList = $A(arc.ClientMgr._preloadList).uniq();
                          arc.ClientMgr._preloadList.each(function(item){
                              arc.debug( "preload list item:"+item );
                          });
                          window.setTimeout("arc.ClientMgr.preloadNext();",10);
                      },
                      preloadNext:function(){

                          arc.debug(" *** preloadNext ");
                          var _clientUrl= $A(arc.ClientMgr._preloadList).first() ;
                          
                          arc.debug("preloadList item " + _clientUrl );
                          arc.ClientMgr._preloadList = $(arc.ClientMgr._preloadList).without(_clientUrl);

                          if(_clientUrl==null){
                              this.sniffState="complete";
                              arc.dispatchEvent({type:"arcLoadComplete"});
                          }else{
                              // mimic clientdesc
                              var swfObj = arc.util.createSwf(
                                  {url:ARC_SNIFF_URL,id:'preloadId',params:{height:1,width:1,left:-1,top:-1,backgroundColor:"#990099"},minFlashVersion:7}
                              );
                              swfObj.addVariable("targetUrl", _clientUrl);
                              swfObj.addVariable("measure", false);
                              swfObj.addVariable("timeout", 20000);
                              swfObj.addParam("allowScriptAccess","always");
                              swfObj.addParam("wmode","window");
                              swfObj.addVariable("completeEvent", "arcPreloadComplete");
                              swfObj.write($("arcPreloadDiv"));

                          }
                      },
                      getClientDesc:function(_id)
                      {
                          return this._clients.find(function(client)
                                             {
                                                 //arc.debug(_id+" matching client:"+client.id);
                                                 return  client.id == _id ;
                                             });
                      },
                      addClientDesc:function(_client)
                      {
                          arc.debug("added client "+ _client.id);
                          arc.ClientMgr._clients.push( _client) ;
                          arc.debug(" added client "+ _client );
                          arc.dispatchEvent({type:"arcClientAdded",topic:"client",sourceClientId:_client.id });
                      },
                      handleEvent:function(_event){
                          arc.debug(" *** ClientMgr handleEvent type:"+_event.type);
                          switch(_event.type){
                          case "arcClientStarted":
                              arc.ClientMgr.getClientDesc(_event.sourceClientId).handleStart();
                              break;
                          case "arcCloseClient":
                              window.setTimeout("arc.ClientMgr.closeClient(\""+_event.sourceClientId+"\");",250);
                              break;
                          }
                          var _handled=false;
                          this._clients.each(function( client ) 
                                        {
                                            if ( client.launchEvents[_event.type] )
                                            {
                                                arc.debug("found client with launchEvent " + client.id +":"+_event.type )
                                                arc.ClientMgr.activateClient(client,_event);
                                                _handled=true;
                                            }
                                        });
                          // send event from one client to all others
                          if(!_handled && _event.topic!=null){
                              this._clients.each(function( client ) 
                                        {
                                            if (client.id!=_event.sourceClientId ) 
                                                client.handleEvent(_event);
                                            
                                        });
                          }
                      },
                      activateClient:function(_client,_event){
                          arc.debug("activateClient _client "+ _client + ", _event "+ _event.type );
                          arc.debug("client visible:"+ _client.visible );
                          if(!_client.visible){
                              _client.pendingEvent=_event;
                              _client.initSwf();
                              _client.showSwf();
                              _client.visible=true;
                          }
                          if(_client.started){
                              arc.debug( " passing event to client to handle");
                              _client.handleEvent(_event);
                          }
                      },
                      closeClient:function(_clientId){
                          arc.debug(" closeClient _client "+ _clientId );
                          
                          client = arc.ClientMgr.getClientDesc(_clientId);
                          arc.debug("found client:"+client);
                          if(client != null && client.handleClose()){
                              client.visible=false;
                          }

                      }
                  });
    
    // EVENT MANAGER
    // EVENT MANAGER
    Object.extend(arc.EventMgr,
                 {
                     eventListeners:[],
                     addEventListener:function(_key,_function){

                         arc.debug( "Adding Event Manager listener \"" + _key +"\" with typeOf:"+typeof(_function) );
                         if(this.eventListeners[_key]==null){
                             this.eventListeners[_key]=new Array();
                         }
                         this.eventListeners[_key].push(_function);
                     },
                     dispatchEvent:function(_event){
                         arc.debug(" EventMgr.dispacthEvent = "+ _event.type +":"+_event);
                         var _list=this.eventListeners[_event.type];
                         arc.debug(" EventMgr found "+ (( typeof(_list) == "undefined" ) ? "no registered listeners" : 
                                                        ( _list.length + " registered listeners") )+" for type:"+(_event.type) );
                         if ( _list == null ) return;
                         _list.each( function(f) { 
                             arc.debug ( "calling callback " + typeof(f) );
                             f( _event); 
                         });
                         arc.debug("dispatching completed");
                     },
                     eventTimers:$A(),
                     addEventTimer:function( _key,_timer )
                     {                         
                         arc.debug(" *** event timer ..add:" + _key );
                         arc.EventMgr.eventTimers[_key] = _timer;
                     },
                     clearEventTimer:function(_key)
                     {
                         arc.debug(" *** event timer ..remove:" + _key );
                         if ( arc.EventMgr.eventTimers[_key] != null ) 
                         {
                             arc.debug(" found timer to remove ");
                             window.clearTimeout( arc.EventMgr.eventTimers[_key]);
                         }
                         arc.EventMgr.eventTimers = arc.EventMgr.eventTimers.without(_key);
                     }
                     
                 });
    
    // CONFIG
    // CONFIG
    Object.extend(arc.config,
                  {
                      baseFlashVersion:7,
                      baseDownloadRate:60,
                      cookies:{ sniffCookie:"arcDownloadRate",
                                checkoutFlag:"checkoutFlag"
                              }
                  });
    // UTILITIES
    // UTILITIES


    Object.extend(arc.util,
                  {
                      isReady:function()
                      {
                          // used by sniff to test readiness
                          return true;
                      },
                      getCanvas:function()
                      {              
                          // this should not be called before DOM readiness
                          if ( $(arc.canvas) ) return arc.canvas;
                          if ( $(arc.pageDesc) && $(arc.pageDesc).arcCanvas ) return $(arc.pageDesc).arcCanvas;
                          
                          var _canvasDiv =document.createElement("DIV");
                          _canvasDiv.id="arcCanvas";
                          arc.canvas= $(_canvasDiv);                         
                          document.body.appendChild( _canvasDiv );
                          $("arcCanvas").setStyle({zIndex:1200 });
                          return arc.canvas;
                      },
                      containStartMode:function(compare)
                      {
                          // used in clients window onload method
                          if ( typeof (arc._startMode) == "String")
                              return (compare == arc._startMode);
                          //$(arc._startMode).each(function(iterator){ alert ( this ) ; },arc._startMode);
                      },
                      cookiesAllowed:function() {
                          setCookie('checkCookie', 'test', 1);
                          if (arc.util.getCookie('checkCookie')) {
                              arc.util.deleteCookie('checkCookie');
                              return true;
                          }
                          return false;
                      },
                      setCookie:function(name,value,expires, options) {
                          if (options===undefined) { options = {}; }
                          if ( expires ) {
                              var expires_date = new Date();
                              expires_date.setDate(expires_date.getDate() + expires)
                          }
                          document.cookie = name+'='+escape( value ) +
                              ( ( expires ) ? ';expires='+expires_date.toGMTString() : '')+
                              ( ( options.path ) ? ';path=' + options.path : '' ) +
                              ( ( options.domain ) ? ';domain=' + options.domain : '')+
                              ( ( options.secure ) ? ';secure' : '');
                      },
                      getCookie:function( name ) {
                          var start = document.cookie.indexOf( name + "=");
                          var len = start + name.length + 1;
                          if ( ( !start ) && ( name != document.cookie.substring( 0, name.length))){
                              return null;
                          }
                          if ( start == -1 ) return null;
                          var end = document.cookie.indexOf( ';', len );
                          if ( end == -1 ) end = document.cookie.length;
                          return unescape( document.cookie.substring( len, end ) );
                      },
                      deleteCookie:function( name, path, domain ) {
                          if ( arc.util.getCookie( name ) ) document.cookie = name + '=' +
                              ( ( path ) ? ';path=' + path : '') +
                              ( ( domain ) ? ';domain=' + domain : '' ) +
                              ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
                      },
                      isArray:function(testObject) {
                          return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
                      },
                      createSwf:function(clientDesc)
                      {
                          arc.debug (" *** creating swf ");
                          var _swf=new SWFObject( 
                              clientDesc.url,
                              clientDesc.id,
                              clientDesc.params.width?clientDesc.params.width:"100%",
                               clientDesc.params.height?clientDesc.params.height:"100%",
                              (clientDesc.minFlashVersion)?clientDesc.minFlashVersion:arc.config.baseFlashVersion,
                              clientDesc.params.backgroundColor);
                          _swf.addParam("allowScriptAccess","always");
                          arc.debug(_swf.getSWFHTML() );
                          return _swf;
                      },
                      judgeDownloadRate:function(rate)
                      {
                          arc.debug(" *** judgeDownloadRate " + rate +" vs. "+ arc.config.baseDownloadRate );
                          if ( rate >= arc.config.baseDownloadRate )
                          {
                              arc.startPreload();
                          } else {
                              arc.dispatchEvent({type:"arcInitFailed",reason:"bandwidth required"});
                          }
                      },
                      isDebugEnabled:function(pageDescObj)
                      {
                          if ( pageDescObj && pageDescObj.debug )
                              arcDebugEnabled = pageDescObj.debug;
                          arcDebugEnabled = ( arcEnabled && ( arcDebugEnabled || (document.location.href.indexOf("arcDebug=true") >-1)));
                          return arcDebugEnabled;
                      }
                      ,isTimerEnabled:function(pageDescObj)
                      {
                          if ( pageDescObj && pageDescObj.timer )
                              arcTimerEnabled = pageDescObj.timer;
                          arcTimerEnabled = ( arcEnabled && ( arcTimerEnabled || (document.location.href.indexOf("arcTime=true") >-1)));
                          return arcTimerEnabled;
                      },
                      now:function()
                      {
                         var d = new Date();
                         return d.getTime();
                      }
                  });



    Object.extend ( arc.util , {
                tempNoteTime:0,
                timeNotes:[{label:"javascript initilizing",timeStamp:arc.util.now()}],
                      timeNote:function(pLabel){
                $(arc.util.timeNotes).push( {label: pLabel,timeStamp:arc.util.now()} ) 
                      },
                      debugConsoleWriter:function(str,color)
                      {

                          if ( arc.util.isTimerEnabled() ) {}
                          if ( ! arc.util.isDebugEnabled() ) return;
                          var c = ( color == undefined ) ? "#333333" : color ;
                          
                          if ($("_arc_debug_area"))
                          {

                              var pre = $(document.createElement("div"));
                              Element.setStyle(pre,{ width:'100%',fontFamily:"arial,geneva"});
                              //if (! Prototype.Browser.IE)
                              Element.setStyle(pre , {color:c,fontSize:"10pt" } );

                              var  cellText = document.createTextNode(str+"\n");
                              pre.appendChild(cellText)
                              $("_arc_debug_area").appendChild(pre);
                              $("_arc_debug_area").scrollTop = $("_arc_debug_area").scrollHeight;
                              return pre;

                          }
                      },
                      newDebugConsole:function(pageDescObj)
                      {

                          // dragging
                          arc.util.offset={x:0,y:0};
                          arc.util._dragMethod = function(event) {
                              Element.setStyle( $("_arcDbDiv"), 
                                                { left:Event.pointerX(event)-arc.util.offset.x + "px",
                                                  top:Event.pointerY(event)-arc.util.offset.y + "px"
                                                });
                              Event.stop(event);
                          }

                          var _arcDiv=$(document.createElement("DIV"));
                          _arcDiv.id="_arcDbDiv";

                          var _arcDivTitleBar=$(document.createElement("DIV"));
                          _arcDivTitleBar.id="arcControlBar";
                          Object.extend( _arcDivTitleBar ,{ stamp:0 });

                          var _arc_debug_textarea = document.createElement("div");
                          _arc_debug_textarea.id="_arc_debug_area";
                          _arc_debug_textarea.wrap="hard";

                          _arcDiv.appendChild(_arcDivTitleBar);
                          _arcDiv.appendChild(_arc_debug_textarea);
                          arc.util.getCanvas().appendChild($(_arcDiv));

                          Element.setStyle( _arcDiv, {position:'absolute',width:"320px",top:"60px",left:"5px"});

                          if ( pageDescObj && pageDescObj.debugStyleName ) $(_arcDiv).className=pageDescObj.debugStyleName;

                          Element.setStyle( _arcDivTitleBar,
                                            {textAlign:'left',
                                             width:"100%",top:"0px",left:"0px",
                                             backgroundColor:"#cccccc",
                                             border:"1px solid #000000"});
                          
                          Element.setStyle( $(_arc_debug_textarea), {
                                      paddingLeft:"15px",
                                      height:"500px", 
                                      width:"100%",
                                      maxHeight:"500px",
                                      width:"100%",
                                      top:"-1px",
                                      position:'relative',
                                      left:"0px", 
                                      overflow:'auto', 
                                      textAlign:'left'});

                          Element.setStyle( $(_arc_debug_textarea),{ backgroundColor:"#dedede", border:"1px solid #000000"});
                          
                         
                          Event.observe( _arcDivTitleBar ,"mouseup" , function(event){
                                  Element.setStyle( _arcDivTitleBar,{cursor:''});
                                  Event.stopObserving( document , 'mousemove', arc.util._dragMethod);
                          });
                                 
                          Event.observe( _arcDivTitleBar ,"mousedown" , function(event){

                                  var _d=new Date();
                                  doubleClick=(_d.getTime()-this.stamp);
                                  if ( doubleClick < 600 ){

                                      $(_arc_debug_textarea).setStyle( {
                                              height:(($(_arc_debug_textarea).getStyle("height")!='1500px')? '1500px':'0px')
                                             
                                      });

                                      $(_arcDiv).setStyle( {
                                              height:(($(_arc_debug_textarea).getStyle("display")=='visible')? '90%': 
                                                      $(_arcDivTitleBar).getStyle("height") )
                                                
                                                  });
                                  }
                                  this.stamp = _d.getTime();
                                  Element.setStyle( _arcDivTitleBar,{cursor:'move'});
                                  
                                  var leftOffset = Event.element(event).up().getStyle("left");
                                  leftOffset = Event.pointerX(event) - parseInt ( leftOffset.substr( 0, leftOffset.length-2));
                                  var topOffset = Event.element(event).up().getStyle("top");
                                  topOffset = Event.pointerY(event) - parseInt ( topOffset.substr( 0, topOffset.length-2));
                                  arc.util.offset={x:leftOffset,y:topOffset};
                                  Event.observe( document , 'mousemove',arc.util._dragMethod);
                                  Event.stop(event);
                          });

                      },
                      clearDebugText:function()
                      {
                          Element.descendants($("_arc_debug_area")).each(
                              function(s) {
                                  Element.remove(s);
                              }
                          );
                      },
                      debugTab:function(_label){
                          var _tab=$(document.createElement("span")).setStyle({
                                  paddingLeft:"10px",paddingRight:"10px",
                                  fontSize:"9pt",fontFamily:"arial,geneva",
                                  borderRight:"1px solid  #000000"});
                          _tab.innerHTML=_label;
                          Element.observe(_tab, "mousedown" , function(event) {
                              Element.setStyle(this,{backgroundColor:"#ffffff"}) ;
                              Event.stop(event);
                          });
                          Element.observe(_tab, "mouseup" , function(event) {
                              Element.setStyle(this,{backgroundColor:""});
                              Event.stop(event);
                          });
                          Element.observe(_tab, "mouseout" , function(event) {
                              Element.setStyle(this,{backgroundColor:""});
                              Event.stop(event);
                          });
                          return _tab;
                      },
                      debugConsoleInit:function()
                      {
                          // called after DOM ready 
                          parentObj = $("arcControlBar");
                          Element.setStyle(parentObj,{ paddingTop:2,paddingBottom:0,position:'relative',top:0});
                          // zoom
                          var t=arc.util.debugTab("[&laquo; &raquo;]");
                          parentObj.appendChild(t);
                          Element.observe(t, "mousedown" , function(event) { 
                                  Element.setStyle(this,{backgroundColor:"#dedeff"});
                                  if ( $("_arcDbDiv").getStyle( "width" ) < "780" )
                                      {
                                          this.innerHTML="[&raquo; &laquo;]";
                                          window.setTimeout( function () {
                                                  Element.setStyle ( $("_arcDbDiv") , { width:"90%" });
                                              },10);
                                      } else {
                                      this.innerHTML="[&laquo; &raquo;]";
                                      Element.setStyle ( $("_arcDbDiv") , { width:"300px" } );
                                  }
                              });
                          // clear
                          t=arc.util.debugTab("Clear");
                          Element.observe(t, "mouseup" , function(event) {
                                  Element.setStyle(this,{backgroundColor:""}) ;
                                  Event.stop(event);
                                  arc.util.clearDebugText();
                                  Element.childElements(parentObj).each(function(s) { Element.setStyle(s,{backgroundColor:""}); });
                              });
                          
                          
                          parentObj.appendChild(t);
                          
                          // cookies
                          t=arc.util.debugTab("Cookies");
                          Element.observe(t, "mouseup" , function(event) {
                                  
                                  
                                  Element.setStyle(this,{backgroundColor:""});
                                  Event.stop(event);
                                  for(var i in arc.config.cookies){
                                      if (arc.util.getCookie(arc.config.cookies[i]) != null)
                                          {
                                              linkit =$(arc.debug(arc.config.cookies[i] + ":"
                                                      +arc.util.getCookie(arc.config.cookies[i])+ " (click to delete)"));
                                              linkit.cookieName=arc.config.cookies[i];
                                              Element.setStyle(linkit,{color:"#0000cc"});
                                              Element.observe(linkit,'click',function(event){
                                                      if ( this.cookieName != null) {
                                                          arc.util.deleteCookie( this.cookieName );
                                                          arc.debug ("deleted cookie:"+this.cookieName);
                                                          this.cookieName = null;
                                                      }});
                                          }
                                      else 
                                          {
                                              arc.debug(arc.config.cookies[i] + ":" +arc.util.getCookie(arc.config.cookies[i]));
                                          }
                                  }
                                  
                              });
                          $(parentObj).appendChild(t);
                          // time keeper
                          t=arc.util.debugTab("Time", arc.util.clearDebugText);
                          Element.observe(t, "mouseup" , function(event) {
                                  
                                  
                                  Element.setStyle(this,{backgroundColor:""});
                                  Event.stop(event);
                                  $(arc.util.timeNotes).each( function (o) {
                                     
                                          arc.debug ( $(o).label + ":" + $(o).timeStamp + "  delta:"
                                                      + ( $(o).timeStamp-arc.util.tempNoteTime)  );
                                          arc.util.tempNoteTime =  $(o).timeStamp;
                                      })
                                  
                              });
                          $(parentObj).appendChild(t);
                          // this fails on IE because the clientMgr has not been initialized yet
                          
                          if ( $A(arc.ClientMgr._clients).length > 0 )
                              {
                                  // break
                                  tabBr= document.createElement("br");
                                  $(parentObj).appendChild(tabBr);
                                  tabDiv= document.createElement("div");
                                  Element.setStyle( tabDiv, {height:2,width:"100%",borderBottom:"1px solid  #ffffff",marginBottom:2} );
                                  $(parentObj).appendChild(tabDiv);
                                  Element.setStyle( parentObj , {height:"38px"});

                              }
                          // client tabs
                          $A(arc.ClientMgr._clients).each(function(c,index){ 
                                                              t=arc.util.debugTab("client:"+c.id, arc.util.clearDebugText);
                                                              t.client=c;
                                                              Element.observe(t, "mousedown" , function(event) {
                                                                      parentObj = $("arcControlBar");
                                                                      Element.childElements(parentObj).each (
                                                                              function(s) {
                                                                                  Element.setStyle(s,{backgroundColor:""});
                                                                               }
                                                                      );
                                                                      Element.setStyle(this,{backgroundColor:"#ffffff"});
                                                                      arc.util.debugObjInfo(this.client);
                                                                  });
                                                              parentObj.appendChild(t);
                                                          });
                              
                      },
                      nestedInfo:function(o,d)
                      {
                          if ( ! $(o) ) return;
                          $(o).setStyle({ color:"#0000cc"}); 
                          Object.extend( $(o) , { nestedInfoObject:d, nestedInfoView:null, state:'new' });
                          Event.observe( $(o), 'mousedown' , function(event) 
                               { 

                                  var element = Event.element(event);
                                  switch (  element.state ) 
                                  {
                                  case "new": 
                                      var span = $(document.createElement("span"));                                                
                                      var pre = $(document.createElement("pre"));                                                
                                      Element.setStyle(span,{ fontFamily:"arial,geneva",backgroundColor:"#fefefc",cursor:"pointer"});
                                      var cellText;
                                      
                                      if ( typeof (element.nestedInfoObject ) == "object" ) 
                                      {
                                          cellText = document.createTextNode( arc.util.debugObjInfoData(  element.nestedInfoObject )  );
                                      } else {
                                          cellText = document.createTextNode(Object.inspect( element.nestedInfoObject));
                                      }
                                      pre.appendChild(cellText);
                                      span.appendChild(pre);
                                      element.appendChild(pre);
                                      element.state = "open";
                                      element.nestedInfoView = pre;
                                      break;
                                  case "open":
                                      $(element.nestedInfoView).setStyle ( {display:'none' } );
                                      element.state = "close";
                                      break;
                                  case "close":
                                      $(element.nestedInfoView).setStyle ( {display:'block' } );
                                      element.state = "open";
                                      break;
                                      
                                  }
                                  
                                  
                               });
                          return $(o);
                          
                      },
                      debugObjInfo:function(c)
                      {
                          arc.debug( "=== Object Info ===" , "red");

                          Object.keys(c).each( function(key){ 
                                  if ( typeof ( c[key] ) == "function" ) {
                                       arc.util.nestedInfo( arc.debug( "("+typeof(c[key]) +") " + key ) , c[key] );
                                  }
                          });
                          Object.keys(c).each( function(key){ 
                              if ( typeof ( c[key] ) == "object" )
                              {
                                  
                                  arc.util.nestedInfo( arc.debug( "("+typeof(c[key])+") "+key)  , c[key] );
                                  
                              }
                          });
                          Object.keys(c).each( function(key){ 
                              if ( typeof ( c[key] ) != "function" && typeof ( c[key] ) != "object" )
                                  arc.debug( "("+typeof(c[key]) +") " + key +" : " + c[key] );
                          });

                          arc.debug( "===============","red");
                      },
                debugObjInfoData:function(c)
                {
                    var rStr = "";
                    Object.keys(c).each( function(key){                              

                                  if ( typeof ( c[key] ) != "function" && typeof ( c[key] ) != "object" )
                                       rStr +=  "("+typeof(c[key]) +") "+key +" : " + c[key] +"\n" ;
                                  else
                                       rStr +=  "("+typeof(c[key]) +")" +key +"\n";  

                          });
                    return rStr;

                },
                keepInViewport:function(  clientDiv , anchorElement, overlapFlag  ) { 
                // document.viewport.getDimensions();
                // document.viewport.getScrollOffsets();
                //                    if ( ( clientDiv.getWidth() +  )
                //  {
                left = ( clientDiv.getStyle('left').indexOf("px") ) ? 
                    parseInt ( clientDiv.getStyle('left').sub(0,clientDiv.getStyle('left').indexOf("px")) ) :
                    parseInt (clientDiv.getStyle('left'));

                top = ( clientDiv.getStyle('top').indexOf("px") ) ? 
                    parseInt ( clientDiv.getStyle('top').sub(0,clientDiv.getStyle('top').indexOf("px")) ) :
                    parseInt (clientDiv.getStyle('top'));

                clipLeft = document.viewport.getDimensions().width + document.viewport.getScrollOffsets().left -16;
                clipTop = document.viewport.getDimensions().height + document.viewport.getScrollOffsets().top -16;

                arc.debug( " geo clipLeft:" + clipLeft + " clipTop:"+clipTop , "#990099" );

                arc.debug( " geo left:" + left + " top:"+top , "#990099" );
                if (   ( left+clientDiv.getWidth()) > clipLeft)
                   clientDiv.setStyle ( { left:(left-((left+clientDiv.getWidth())-clipLeft))+"px"});
                if (   ( top+clientDiv.getHeight()) > clipTop)
                    clientDiv.setStyle ( { top:(top -((top+clientDiv.getHeight())-clipTop))+"px"});
                

                arc.debug( " " +  clipLeft ) ;
                        //  }
                        //  }

                }

        });
                      

    
} // end if arc == null 
else
{
    alert (" 'arc' already defined!\n Another library may be using it");
}

arc.util.timeNote("scripts loading");

/*
 * Handle capability test failure.
 */
arc.addEventListener("arcInitFailed", function(_event) {
    arc.debug(" *** arcInitFailed.callback  " + _event.reason);
    arc.util.setCookie(arc.config.cookies['checkoutFlag'], "arcInitFailed");
});


/*
 * Handle successful initialization.
 */
arc.addEventListener("arcStartComplete", function(event) {
    arc.debug(" *** in base arcStartComplete")
    arc.enabled = true;
    arc.sniffState="complete";
    arc.util.setCookie(arc.config.cookies['checkoutFlag'], "arcLoadComplete");
});

/*
 * Handle start of preloading.
 */
arc.addEventListener("arcLoadStarted", function(event) {

});

/*
 * Handle preloading failure.
 */
arc.addEventListener("arcLoadFailed", function(event) {
    arc.debug("arcLoadFailed: "  + event.reason );
    alert(event.reason);   // preload is not expected to fail
    arc.util.setCookie(arc.config.cookies['checkoutFlag'], "arcLoadFailed");
});

