/**
  * FCNYLight Core JavaScript, v3
  * Depends on MochiKit 1.3+
  *
  */

var fcnyl = { "version":"3.0", "dirty":false };

// introspect drops a handy property dump into a popup window
fcnyl.introspect = function( obj ) {
  if ( !obj ) return;
  var result = "introspection of " + String(obj) + " " + obj.id + "<pre>{\n";
  if ( 1 || obj.id ) {
    for (var ix in obj) {
        if ( ix != 'selectionStart' && ix != 'selectionEnd' ) {
          result +=  '.' + ix + " = " + obj[ix] + "\n";
        }
        else {
          result +=  '.' + ix + " = unprintable by introspect() \n";
        }
    }
  }
  
  result = result + "}\n</pre>";
  inspector = window.open("","inspector", "width=420,height=640,resizable,scrollbars");
  if ( !inspector ) {
    alert("Popup windows are blocked!" );
  }
  else {
    inspector.document.writeln( result );
  }
}
introspect = fcnyl.introspect;

// escapes HTML entities
fcnyl.h  = function( mystring ) {
  var div = document.createElement( "div" );
  var text = document.createTextNode( mystring );
  div.appendChild( text );
  return div.innerHTML;
}
h = fcnyl.h;

fcnyl.trim = function( value ) {
  if ( !value || value=="" ) return null;
  var newval = value.replace( /^\s+/, "" );
  return newval.replace( /\s+$/, "" );
}
trim = fcnyl.trim;

// document dirty/clean for onbeforeunload
fcnyl.markDirty = function( e ) {
  if ( e.target && !hasElementClass( e.target(), "clean" ) ) {
    document.dirty = true;
  }
}
fcnyl.markClean = function( ) {
  document.dirty = false;
}
fcnyl.checkDirty = function( e ) {
  if ( document.dirty )  {
    return "If you leave this page you will lose the changes you have made.";
  } 
}
window.onbeforeunload = fcnyl.checkDirty;

// form input double-click and dirty
fcnyl.initFormFields = function() {
  var inputs = getElementsByTagAndClassName('input',null);
  for( i=0; i<inputs.length; i++) {
    if ( inputs[i].type=='text' ) {
      connect( inputs[i], 'ondblclick', function( e ){ e.target().select() } );
      if ( hasElementClass( inputs[i], "tempvalue" ) ) {
        connect( inputs[i], "onfocus", function(e){ 
          var element = e.target(); 
          if ( hasElementClass( element, "tempvalue") ) { 
            element.value=""; 
            removeElementClass( element, "tempvalue" ) 
          } 
        } );
      }
    }
    else if ( inputs[i].name=='cancel' ) {
      continue;
    }
    else if ( inputs[i].type=='submit' || inputs[i].type=='button' || inputs[i].type=='image' ) {
      connect( inputs[i], 'onclick', fcnyl, 'markClean' );
    }
    if ( !hasElementClass( inputs[i], "clean" ) ) {
      connect( inputs[i], 'onchange', fcnyl, 'markDirty' );
    }
  }
  var tas = getElementsByTagAndClassName('textarea',null);
  for( i=0; i<tas.length; i++) {
    if ( !hasElementClass( tas[i], "clean" ) ) {
      connect( tas[i], 'onchange', fcnyl, 'markDirty' );
    }
  }
  var sels = getElementsByTagAndClassName('select',null);
  for( i=0; i<sels.length; i++) {
    sels[i].defocus = function( e ) {
      if ( e.target().parentNode.id==this.id ) return;
      log( this.id,"defocused by", e.target() ); 
      disconnect( this.clicklistener );
    }
    connect( sels[i], 'onfocus', function(e){ 
      var me = e.target();
      var parent = me.parentNode;
      log("Focused", me);
      me.clicklistener = connect( window, "onclick", me, "defocus" );
      });
    connect( sels[i], 'onblur', function(e){ 
      var me = e.target();
      log("Blurred", me);
      disconnect( me.clicklistener );
      });
    if ( !hasElementClass( sels[i], "clean" ) ) {
      connect( sels[i], 'onchange', fcnyl, 'markDirty' );
    }
  }
  var obrowsers = getElementsByTagAndClassName('img','objectbrowser');
  for( i=0; i<obrowsers.length; i++) {
    connect( obrowsers[i], "onclick", fcnyl, "obrowserclick" );
  }
  log("Form fields tweaked.");
}
connect( window,'ondomload',fcnyl,'initFormFields' );

// selectron otherselect check
fcnyl.otherselect = function(obj) {
  log("otherselect for",obj,"#",obj.id);
  var otherid = getNodeAttribute( obj, "otherid" );
  var otherselected = false;
  if ( !obj.multiple ) {
    if ( obj.value=='+' ) {
      otherselected = true;
    }
  }
  else {
    var options = obj.options;
    for ( i=0; i<options.length; i++) {
      if ( options[i].value=="+" && options[i].selected==true ) {
        otherselected = true;
      }
      //log(obj.id,"option",i,"value is",options[i].value,"selected:",options[i].selected);  
    }
  }
  if ( otherselected ) {
    $( otherid ).style.width = ( obj.offsetWidth - 10 ) + "px";
    $( otherid ).style.display = "block";
    $( otherid ).focus();
  }
  else {
    $( otherid ).style.display = "none";
  }
}


fcnyl.initDraggables = function() {
  var divs = getElementsByTagAndClassName('div','draggable');
  for( i=0; i<divs.length; i++) {
    new Draggable( divs[i] ); 
  }
  log(i,"draggable objects found");
}
if ( typeof Draggable != undefined ) {
  connect( window,'ondomload',fcnyl,'initDraggables' );
}


fcnyl.initActiveObject = function() {
  if ( window.location.hash ) {
    var hash = window.location.hash.substr( 1 );
    log( "Hash is", hash );
    if ( $(hash) ) {
      addElementClass( $(hash), "requested" );
    }
  }
  else {
    log( "No location hash." );
  }
}
connect( window,'ondomload',fcnyl,'initActiveObject' );


// fill an element with contents of http request
fcnyl.httpfill = function(url, id) {
  d = doSimpleXMLHttpRequest( url );
  d.addBoth( bind( function(xhr) {
    if ( xhr.readyState==4 ) {
      $(id).innerHTML = xhr.responseText;
    }
  }, id ) );
}
httpfill = fcnyl.httpfill;
httpFill = fcnyl.httpfill;

// dirname function
fcnyl.dirname = function ( path ) {
  // match the subpattern to remove trailing slash
  return path.match( /(.*)\// )[1];
}

// justName function strips a code: or http: off the front of some pathname
fcnyl.justName = function ( code ) {
  var colpos = code.indexOf(':');
  if ( colpos > -1 ) {
    return code.substr( colpos+1 );
  }
  else {
    return code;
  }
}

// tinymce filebrowser callback
// http://wiki.moxiecode.com/index.php/TinyMCE:Custom_filebrowser
fcnyl.mcebrowser = function( field_name, url, type, win ) {
  var field_value = win.document.getElementById( field_name ).value;
  log("mcebrowser field_name:",field_name,"field_value:",field_value,"url:",url,"type:",type,"win:",win);
  var cmsURL = window.location.pathname;
  var searchString = window.location.search;
  if (searchString.length < 1) {
    searchString = "?";
  }
  var defaultString = "";
  if (field_value) {
    var justname = fcnyl.justName(field_value);
    if ( justname.substr(0,1)=='/' && justname.substr(0,2)!='//' ) {
      var pathname = fcnyl.dirname( justname );
      var basename = justname.substr(pathname.length+1);
      var basenameNoExt = basename.substr(0, basename.indexOf('.'));
//      logDebug(justname, pathname, basename, basenameNoExt);
      //if ( justname.substr(-4)=='icon' || justname.substr(-9)=='thumbnail' || justname.substr(-7)=='preview' ) {
      // take into account that it now has the extension attached to it!
      if ( basenameNoExt=='icon' || basenameNoExt=='thumbnail' || basenameNoExt=='preview' ) {
        pathname = fcnyl.dirname( pathname );
      }
      //log("pathname.substr(-9)",pathname.substr(-9));
      defaultString = "&default="+escape( pathname );
    }
  }
  tinyMCE.openWindow({
      file : cmsURL + searchString + "&mode=" + type + "&action=sideindex"  + defaultString,
      title : "Object Browser",
      width : 420,  // Your dimensions may differ - toy around with them!
      height : 400,
      close_previous : "no"
    }, {
      window : win,
      input : field_name,
      resizable : "yes",
      inline : "yes", 
      editor_id : tinyMCE.getWindowArg("editor_id")
    });
  return false;
}
mcebrowser = fcnyl.mcebrowser;

window.obrowserClose = false;
fcnyl.obrowserclick = function( e ) {
  if ( window.obrowserClose ) {
    window.obrowserClose();
    return;
  }
  var button = e.src();
  var field_name = getNodeAttribute( button, "field_name" );
  log( "obrowser by click", button, button.id, "field_name", field_name );
  var obrowser = createDOM( 'IFRAME', { "id":button.id+"_obrowser", "name": field_name+"_browser", "src": "?action=sideindex&mode=obrowser", "width": 500, "height": 320, "scrolling": "no", "frameborder": 0, "style": "border: 1px solid #444; margin: 6px 0;" } );
  window.obrowser_fieldname = field_name;
  window.obrowserClose = function () {
    button.parentNode.removeChild( obrowser );
    window.obrowserClose = false;
  }
  button.parentNode.appendChild( obrowser );
}

// declick stops the bubbling of onclick events
function declick( obj, e ) {
  if ( !e ) e = window.event;
  e.cancelBubble = true;
  //alert('click stopped at '+obj.id);
}

// toggle style.display between block and none (show/hide)
function toggle( id ) {
  myobj = $( id );
  if ( myobj && ( myobj.style.display == 'none' || myobj.style.display == '' ) ) {
    myobj.style.display = 'block';
  }
  else if ( myobj ) {
    myobj.style.display = 'none';
  }
}

function restyle( selector, rule ) {
  if( !document.styleSheets ) return -1;
  if( document.styleSheets.length <= 0 ) return -1;
  var css = document.styleSheets[document.styleSheets.length-1];
  if ( css.cssRules.length ) {
    var index = css.cssRules.length;
    css.insertRule( selector+' {'+rule+'}', index );
  }
  else {
    var index = css.rules.length;
    css.addRule( selector, '{'+rule+'}', index );
  }
}

/* 
    a wrapper for MochiKit's getElementsByTagAndClassName that calls func( elements. index ) for each element found
    returns the processed elements
    example: 
      var navSections = iterateElementsByTagAndClassName( "div", "section", $("Navigation"), function( elements, i ) { log( "Found section",elements[i].id ); } );
*/
function iterateElementsByTagAndClassName ( element, classname, parent, func ) {
  var elements = getElementsByTagAndClassName( element, classname, parent );
  //log("Found",elements,element+"(s)","in","#"+parent.id);
  for ( var i=0; i < elements.length; i++ ) {
    func.apply( this, [ elements, i ] );
  }
  return elements;
}