/**
  * 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;

fcnyl.delog = function( obj ) {
  return serializeJSON( obj );
}

// 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._event ) {
    if ( e.target && !hasElementClass( e.target(), "clean" ) ) {
      document.dirty = true;
      //log("Dirty");
    }
  }
}
fcnyl.markMCEDirty = function( inst ) {
  document.dirty = true;
  log("MCE dirty");
}
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' );
    }
    if ( hasElementClass( tas[i], "tempvalue" ) ) {
      connect( tas[i], "onfocus", function(e){ 
        var element = e.target(); 
        if ( hasElementClass( element, "tempvalue") ) { 
          element.value=""; 
          removeElementClass( element, "tempvalue" ) 
        } 
      } );
    }
  }
  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 ) {
    if ( $( otherid ).value ) {
      //$( otherid ).style.width = ( obj.offsetWidth - 10 ) + "px";
    }
    $( otherid ).style.display = "inline";
    $( 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;
  }
}

// converts js Date object to sql date (no time)
fcnyl.sqlDate = function ( jsdate ) {
  var year = jsdate.getFullYear();
  var month = jsdate.getMonth() + 1;
  if ( month < 10 ) {
    month = '0' + month;
  }
  var day = jsdate.getDate();
  if ( day < 10 ) {
    day = '0' + day;
  }
  return year + '-' + month + '-' + day;
}


// 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' || basenameNoExt=='poster' ) {
        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;

fcnyl.mce3browser = function (field_name, url, type, win) {
  var field_value = win.document.getElementById( field_name ).value;
  log("mce3browser field_name:",field_name,"field_value:",field_value,"url:",url,"type:",type,"win:",win);
  var cmsUrl = window.location.toString();    // script URL - use an absolute path!
  //var cmsUrl = '/tm/elementary'; //window.location.pathname;
  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' || basenameNoExt=='poster') {
        pathname = fcnyl.dirname( pathname );
      }
      //log("pathname.substr(-9)",pathname.substr(-9));
      defaultString = "&default="+escape( pathname );
    }
  }
  cmsUrl = cmsUrl + "?type=" + type + "&action=sideindex&mode=tinymce_browser"  + defaultString,
  log("mce3browser cmsUrl",cmsUrl);
  tinyMCE.activeEditor.windowManager.open({
      file : cmsUrl,
      title : 'Object Browser',
      width : 420, 
      height : 400,
      resizable : "yes",
      inline : "yes",  
      close_previous : "no"
  }, {
      window : win,
      input : field_name
  });
  return false;
}
mce3browser = fcnyl.mce3browser;

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';
  }
}

// cross-platform css toolkit (public domain) by Patrick Hunlock
// http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript
// example:
// var jsrule = getCSSRule( ".important" );
// if ( !jsrule ) jsrule = addCSSRule( ".important" );
// jsrule.style.color = "#ff0000";
function getCSSRule(ruleName, deleteFlag) {               // Return requested style obejct
   ruleName=ruleName.toLowerCase();                       // Convert test string to lower case.
   if (document.styleSheets) {                            // If browser can play with stylesheets
      for (var i=0; i<document.styleSheets.length; i++) { // For each stylesheet
         var styleSheet=document.styleSheets[i];          // Get the current Stylesheet
         var ii=0;                                        // Initialize subCounter.
         var cssRule=false;                               // Initialize cssRule. 
         do {                                             // For each rule in stylesheet
            if (styleSheet.cssRules) {                    // Browser uses cssRules?
               cssRule = styleSheet.cssRules[ii];         // Yes --Mozilla Style
            } else {                                      // Browser usses rules?
               cssRule = styleSheet.rules[ii];            // Yes IE style. 
            }                                             // End IE check.
            if (cssRule)  {                               // If we found a rule...
               if (cssRule.selectorText.toLowerCase()==ruleName) { //  match ruleName?
                  if (deleteFlag=='delete') {             // Yes.  Are we deleteing?
                     if (styleSheet.cssRules) {           // Yes, deleting...
                        styleSheet.deleteRule(ii);        // Delete rule, Moz Style
                     } else {                             // Still deleting.
                        styleSheet.removeRule(ii);        // Delete rule IE style.
                     }                                    // End IE check.
                     return true;                         // return true, class deleted.
                  } else {                                // found and not deleting.
                     return cssRule;                      // return the style object.
                  }                                       // End delete Check
               }                                          // End found rule name
            }                                             // end found cssRule
            ii++;                                         // Increment sub-counter
         } while (cssRule)                                // end While loop
      }                                                   // end For loop
   }                                                      // end styleSheet ability check
   return false;                                          // we found NOTHING!
}                                                         // end getCSSRule 
function killCSSRule(ruleName) {                          // Delete a CSS rule   
   return getCSSRule(ruleName,'delete');                  // just call getCSSRule w/delete flag.
}                                                         // end killCSSRule
function addCSSRule(ruleName) {                           // Create a new css rule
   if (document.styleSheets) {                            // Can browser do styleSheets?
      if (!getCSSRule(ruleName)) {                        // if rule doesn't exist...
         if (document.styleSheets[0].addRule) {           // Browser is IE?
            document.styleSheets[0].addRule(ruleName, null,0);      // Yes, add IE style
         } else {                                         // Browser is IE?
            document.styleSheets[0].insertRule(ruleName+' { }', 0); // Yes, add Moz style.
         }                                                // End browser check
      }                                                   // End already exist check.
   }                                                      // End browser ability check.
   return getCSSRule(ruleName);                           // return rule we just created.
} 
// end css toolkit


/* This function only barely works in IE, which doesn't always apply cascading rules :-p */
/* Use the toolkit above */
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 ) {
    var index = css.cssRules.length;
    css.insertRule( selector+' {'+rule+'}', index );
    //log( "Inserted rule", selector, rule, index );
  }
  else {
    var index = css.rules.length;
    css.addRule( selector, '{'+rule+'}', index );
    //log( "Added rule", 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;
}


/* This function takes a number and converts it to well-formatted number to 2 decimal places */
function currency( num ) {
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10) cents = "0" + cents;
  return num+"."+cents;
}