/*
fcnyweb interface Javascript
Copyright 2008, Fund for the City of New York
All rights reserved.

This source file is distributable subject to the terms of the
FCNY Open Source License.
License: http://fred.fcny.org/fcny-ossl.txt
*/

// fcnyweb object
var fcnyweb = { "version":"1.0" }

var hiding = new Array();
var closing = new Array();
var sticky = new Array();

function showMenu( id ){
  // obj is the menudrop id
  var obj = document.getElementById( id );
  if ( !obj ) return;
  // if there is a timeout set to hide this menudrop, destroy it
  if ( hiding[id] ){
    clearTimeout( hiding[id] );
    log('showMenu cleared hiding timeout '+id+' '+hiding[id]);
    hiding[id]=false;
  }
  // display the menudrop
  obj.style.display = 'block';
  // if menudrop is not positioned, position it
  if ( !obj.menupos ) {
    var pixel = $( 'menupixel'+id.substr( 8 ) );
    var sitenav = $('SiteNav')
    var sitenavplace = elementPosition( sitenav );
    var pixelplace = elementPosition( pixel );
    //introspect( pixel );
    var dropsize = elementDimensions( obj );
    obj.style.left = ( ( pixelplace.x - sitenavplace.x ) - ( dropsize.w - 18 ) ) + 'px';
    obj.style.top = ( ( pixelplace.y - sitenavplace.y ) + 15 ) + 'px';
    log("showMenu for", obj, obj.id, "SiteNav", sitenavplace, "pixelplace", pixelplace, "dropsize", dropsize,"obj.left", obj.style.left, "obj.top", obj.style.top );
    obj.menupos = true;
  }
  // hide other open menus

  iterateElementsByTagAndClassName( "div", "menudrop", $("SiteNav"), function( drops, i ) {
    if ( drops[i].id==obj.id ) {
      return;
    }
    if ( drops[i].style.display!="none" ) {
      drops[i].style.display="none";
      log("Closing stray menu", drops[i].id );
    }
  });

  // end showMenu
}

function hideMenu( id ){
  if ( sticky[id] ){
    log( "hideMenu called on sticky menu", id );
    return;
  }
  // id is menudrop
  var obj = document.getElementById( id );
  if ( !obj ) return;
  // if not already hiding, request hiding timeout
  if ( !hiding[id] ) {
    hiding[id] = setTimeout('timedHide("'+id+'")', 300);
    log('hideMenu created hiding timeout for'+id+' '+hiding[id]);
  }
}

function cancelHide( id ) {
  if ( hiding[id] ){
    clearTimeout( hiding[id] );
    log('cancelHide hiding canceled for'+id+' '+hiding[id]);
    hiding[id]=false;
  }
}

function stickMenu( id ){
  var obj = document.getElementById( id );
  if ( !obj ) return;
  if ( sticky[id] ){
    sticky[id] = false;
    obj.style.display = 'none';
  }
  else {
    sticky[id] = true;
    obj.style.display = 'block';
  }
}

function timedHide( id ){
  var obj = document.getElementById( id );
  if ( !obj ) return;
  obj.style.display = 'none';
  hiding[ id ] = false;
}

function timedClose( id ){
  var obj = document.getElementById( id );
  if ( !obj ) return;
  obj.style.display = 'none';
  closing[ id ] = false;
}

function showContents( id ) {
  $('section'+id).origZ = $('section'+id).style.zIndex;
  $('section'+id).style.zIndex = 90;
  $('contents'+id).style.visibility='visible';
}

function hideContents( id ) {
  $('contents'+id).style.visibility='hidden';
  $('section'+id).style.zIndex = $('section'+id).origZ;
}

// mouseover handlers
fcnyweb.menuTriggerEnter = function( e ) {
  log( e.type(), e.src().id );
  e.stop();
  var trigger = e.src().id;
  var dropid = trigger;
  if ( trigger.substr( 0, 10 ) == 'menutarget' ) {
    dropid = 'menudrop' + trigger.substr( 10 );
  }
  log( "trigger enter for", dropid, "source", e.src().id, "target", e.target().id );
  showMenu( dropid );
}
fcnyweb.menuTriggerLeave = function( e ) {
  log( e.type(), e.src().id );
  e.stop();
  var trigger = e.src().id;
  var dropid = trigger;
  if ( trigger.substr( 0, 10 ) == 'menutarget' ) {
    dropid = 'menudrop' + trigger.substr( 10 );
  }
  log( "trigger leave for", dropid, "source", e.src().id, "target", e.target().id );
  if ( !closing[ dropid ] ) {
    hideMenu( dropid );
  }
}
fcnyweb.menuCloserEnter = function( e ) {
  log( e.type(), e.src().id );
  e.stop();
  var closer = e.src().id;
  var dropid = false;
  if ( closer.substr( 0, 10 ) == 'menucloser' ) {
    dropid = 'menudrop' + closer.substr( 10 );
  }
  log( "closer enter for", dropid, "source", e.src().id, "target", e.target().id );
  if ( dropid ) {
    showMenu( dropid );
    closing[ dropid ] = setTimeout('timedClose("'+dropid+'" )', 300);
  }
}
fcnyweb.menuCloserLeave = function( e ) {
  log( e.type(), e.src().id );
  e.stop();
  var closer = e.src().id;
  var dropid = false;
  if ( closer.substr( 0, 10 ) == 'menucloser' ) {
    dropid = 'menudrop' + closer.substr( 10 );
  }
  log( "closer leave for", dropid, "source", e.src().id, "target", e.target().id );
  if ( dropid ) {
    if ( closing[ dropid ] ) {
      clearTimeout( closing[ dropid ] );
      log("Showing menu again from",closing[dropid]);
      closing[ dropid ] = false;
      showMenu( dropid );
    }
  }
}


// MediaViews Code
fcnyweb.activeViewer = false;
fcnyweb.activeSlide = false;
fcnyweb.viewers = [];

// show the MediaViews, show a viewer, hide others
fcnyweb.showViewer = function ( id ) {
  if ( !this.mv ) return;
  if ( this.mv.style.display=='none' ) {
    this.mv.style.display = 'block';
    log("Showing MediaViews");
  }
  if ( id ) {
    // parse id for slide reference
    var slidemarker = id.indexOf( ':' );
    log("Slidemarker for",id,'is',slidemarker);
    if ( slidemarker > 0 ) {
      var slideid = id;
      id = id.substr( 0, slidemarker );
      nextSlide = $( slideid );
      log("Id is now",id,"and slideid is",slideid);
      if ( nextSlide && hasElementClass( nextSlide, "slide" ) ) {
        if ( this.activeSlide ) {
          this.activeSlide.style.display = 'none';
          this.activeSlide = false;
        }
        this.activeSlide = nextSlide;
      }
      //log("Here",id,"and",$(id));
    }

    // no slide reference, but this is a slideshow, show first slide
    else if ( $(id) && hasElementClass( $(id), "show" ) ) {
      var slides = getElementsByTagAndClassName( "div", "slide", $(id) );
      if ( slides.length ) {
        if ( this.activeSlide ) {
          this.activeSlide.style.display = 'none';
          this.activeSlide = false;
        }
        this.activeSlide = slides[0];
      }
    }
    // no slide ref, decativate current slide
    else if ( this.activeSlide ) {
      this.activeSlide.style.display = 'none';
      this.activeSlide = false;
    }
    
    // set up view
    var nextViewer = $( id );
    log("Id is",id,"and next viewer is",nextViewer);
    if ( nextViewer && hasElementClass( nextViewer, "viewer" ) ) {
      if ( this.activeViewer ) {
        this.activeViewer.style.display = 'none';
        this.activeViewer = false;
      }
      this.activeViewer = nextViewer;
    }
  }
  if ( !this.activeViewer ) {
    log("No active viewer");
    this.closeAll();
    return;
  }
  log("Active viewer",this.activeViewer.id);
  this.activeViewer.style.display = 'block';
  if ( this.activeSlide ) {
    log("Active Slide",this.activeSlide.id);
    this.activeSlide.style.display = 'block';
  }
}

// click handler
fcnyweb.controlClick = function ( e ) {
  e.stop();
  var viewerid = e.src().hash.substr(1);
  window.location.hash = e.src().hash;
  this.showViewer( viewerid );
  var videoid = getNodeAttribute( $(viewerid), "videoid" );
  if ( videoid ) {
    log("Playing",videoid);
    window.setTimeout( "$('flowplayer"+videoid+"').DoPlay()", 1000 );
  }
}

// close button
fcnyweb.closeAll = function ( e ) {
  if ( this.activeViewer ) {
    this.activeViewer.style.display = 'none';
    this.activeViewer = false;
  }
  if ( this.activeSlide ) {
    this.activeSlide.style.display = 'none';
    this.activeSlide = false;
  }
  if ( this.mv ) {
    this.mv.style.display = 'none';
  }
}

// init handler
fcnyweb.init = function() {
  // set parent
  this.mv = $('MediaViews');
  if ( this.mv ) {
    this.mv.style.display = 'none';
  }

  // set up mediaviews closer
  if ( $('MediaViewsClose') ) {
    connect( $('MediaViewsClose'),'onclick',this,'closeAll' );
  }

  // find viewers and links
  iterateElementsByTagAndClassName ( "div", "viewer", this.mv, function( viewers, i ) {
    fcnyweb.viewers.push( viewers[i] );
  });

  iterateElementsByTagAndClassName ( "a", "viewlink", $('Media'), function( links, i ) {
    connect( links[i], "onclick", fcnyweb, "controlClick" );
  });

  iterateElementsByTagAndClassName ( "a", "slidenav", $('MediaViews'), function( links, i ) {
    connect( links[i], "onclick", fcnyweb, "controlClick" );
  });

  // check hash and display viewer
  var hashval = false;
  if ( window.location.hash ) {
    hashval = window.location.hash;
    if ( hashval.substr( 0, 1 )=="#" ) {
      hashval = hashval.substr( 1 );
    }
  }
  if ( hashval ) {
    log("Showing viewer",hashval);
    this.showViewer( hashval );
  }
  log("Media Views init finished");

  // wire menu targets and drops
  var triggers = iterateElementsByTagAndClassName( "div", "menutrigger", $("SiteNav"), function( triggers, i ) {
    connect( triggers[i], "onmouseenter", fcnyweb, "menuTriggerEnter" );
    connect( triggers[i], "onmouseleave", fcnyweb, "menuTriggerLeave" );
  });
  var closers = iterateElementsByTagAndClassName( "div", "menucloser", $("SiteNav"), function( closers, i ) {
    connect( closers[i], "onmouseenter", fcnyweb, "menuCloserEnter" );
    connect( closers[i], "onmouseleave", fcnyweb, "menuCloserLeave" );
  });
  log( "Triggers found", triggers );
}
connect(window,"ondomload",fcnyweb,"init");



// lightbox for previews
var lightbox = { "version": "1.0", "counter": 0 }

lightbox.iconClick = function( e ) {
  e.stop();
  var preview = e.src();
  var lb_id = getNodeAttribute( preview, "lightbox_id" );
  var rawimage = $( "lightbox_" + lb_id );
  if ( rawimage.lightbox===undefined ) {
    if ( !rawimage.width ) {
      var dim = elementDimensions( rawimage )
      var width = dim.w
      var height = dim.h
    }
    else {
      var width = rawimage.width;
      var height = rawimage.height;
    }
    rawimage.lightbox = { "w": width, "h": height };
  }
  else {
    var width = rawimage.lightbox.w;
    var height = rawimage.lightbox.h;
  }
  // get viewport size, and resize image (reduce only) to fit
  var winsize = getViewportDimensions();
  // take 16 off for scrollbars
  winsize.w = winsize.w - 16;
  if ( winsize.w < 1024 ) {
    winsize.h = winsize.h - 16;
  }
  var targetw = winsize.w - 20;
  var targeth = winsize.h - 20;
  if ( width > targetw ) {
    var ratio = targetw / width;
    width = targetw;
    height = Math.floor( height * ratio );
  }
  if ( height > targeth ) {
    var ratio = targeth / height;
    height = targeth;
    width = Math.floor( width * ratio );
  }
  // set position in window
  if ( window.pageYOffset===undefined ) {
    var scrolledto = document.documentElement.scrollTop;
  }
  else {
    var scrolledto = window.pageYOffset;
  }
  var posx = ( winsize.w - width ) / 2;
  if ( posx < 10 ) posx = 10;
  var posy = ( winsize.h - height ) / 3;
  if ( posy < 10 ) posy = 10;
  posy = posy + scrolledto;
  log( "Winsize", winsize, "scrolled to", scrolledto, "rawimage size", rawimage.lightbox.w,"x",rawimage.lightbox.h,"final position", posx,"x",posy, "final size",width,"x",height );
  rawimage.style.left = posx+"px";
  rawimage.style.top = posy+"px";
  rawimage.style.width = width+"px";
  rawimage.style.height = height+"px";
  if ( rawimage && hasElementClass( rawimage, "loaded" ) ) {
    addElementClass( rawimage, "active" );
    addElementClass( $("top"), "lightbox" );
    //ScrollTo( rawimage );
    log("click",preview,"lb_id", lb_id);
  }
  else {
    log( "no rawimage or not loaded" );
  }
}

lightbox.rawimageClick = function( e ) {
  e.stop();
  var rawimage = e.src();
  var origid = getNodeAttribute( rawimage, "original_id" );
  var orig = $( origid );
  removeElementClass( $("top"), "lightbox" );
  //ScrollTo( orig );
  removeElementClass( rawimage, "active" );
}

lightbox.rawImageLoad = function( e ) {
  e.stop();
  var rawimage = e.src();
  if ( !rawimage.complete ) {
    // not complete
    window.setTimeout('lightbox.rawImagePostLoad("'+rawimage.id+'")', 1000);
  }
  else {
    lightbox.rawImagePostLoad( rawimage.id );
  }
}

lightbox.rawImagePostLoad = function( rawimageid ) {
  var rawimage = $( rawimageid );
  if ( !rawimage.width ) {
    if ( window.isIE ) {
      removeElementClass( rawimage, "rawimage" );
    }
    var dim = elementDimensions( rawimage )
    var width = dim.w
    var height = dim.h
     if ( window.isIE ) {
      addElementClass( rawimage, "rawimage" );
    }
  }
  else {
    var width = rawimage.width;
    var height = rawimage.height;
  }
  // check to see that rawimage is bigger than original in width or height
  var origid = getNodeAttribute( rawimage, "original_id" );
  var orig = $( origid );
  if ( !getNodeAttribute( orig, "title" ) ) {
    setNodeAttribute( orig, "title", window.lbClickToEnlarge );
  }
  addElementClass( rawimage, "loaded" );
  connect( rawimage, "onclick", lightbox, "rawimageClick" );
}

lightbox.attach = function( ele ) {
  // make sure preview is last namepart
  var names = ele.src.split( "/" );
  var lastname = names.pop();
  if ( !hasElementClass(ele, "nolightbox") && !hasElementClass(ele.parentNode, "quote") ) {
    // connect onclick and add lightbox class
    lightbox.counter ++;
    if ( !ele.id ) {
      ele.id = "lightbox_original_" + lightbox.counter;
      //log("Assigned id to images",i,",",ele.id);
    }
    ele.lightboxclick = connect( ele, "onclick", lightbox, "iconClick" );
    addElementClass( ele, "lightbox" );
    setNodeAttribute( ele, "lightbox_id", lightbox.counter );
    var rawname = names.join("/") + "/poster.jpg";
    var rawimage = IMG( { "id": "lightbox_"+lightbox.counter, "src": rawname, "class": "rawimage", "title": window.lbClickToClose, "original_id": ele.id } );
    connect( rawimage, "onload", lightbox, "rawImageLoad" );
    $("top").appendChild( rawimage );
  }
}

lightbox.init = function() {
  iterateElementsByTagAndClassName ( "img", null, $("MediaViews"), function( images, i ) {
    if ( images[i].src.indexOf( "preview" ) > -1 ) {
      lightbox.attach( images[i] );
    }
    else if ( images[i].src.indexOf( "thumbnail" ) > -1 ) {
      if ( !hasElementClass(images[i].parentNode, "slideclick") ) {
        lightbox.attach( images[i] );
      }
    }
    else if ( images[i].src.indexOf( "icon" ) > -1 ) {
      lightbox.attach( images[i] );
    }
  });
  log("Lightbox set up for",lightbox.counter,"images");
}

connect( window, "onload", lightbox, "init" );