/*
  Cut It Out! - a jQuery project
  k.douglass, bulletproofpixels.com

*/

$(document).ready(function(){

var cutitout = {

/* ------------------------------------------------------------------------------------------
   Begin Configuration
------------------------------------------------------------------------------------------ */

  // This is the color the text of the selected element will
  // change to (keeps user oriented to their starting point
  // if they navigate in the modal window)  - deprecated after adding the contrast toggle
  //selectedElemColorActive: "#090",

  // (kin to the "visited" anchor link state)
  selectedElemColorVisited: "#00C",

  // Color of the dotted outline on hover of marked elements
  outlineColor: "#000",

  // Color of the background on hover of marked elements
  // (for IE only, which does not support outline on div
  //  elements)
  bgcolor: "#FFFCCC",

  // Color of the overlay
  overlayBgColor: "#0f5b96",

  // Add an icon marker on each marked element in the UI
  // true / false
  addMarker: true,


  // not yet added to site documentation page  ----add-------add-------add------add-----add------add-------add-------add---------

  // Vertical pixel offset for modal window i.e. how far from the top of the
  // viewport do you want the modal window to be positioned?
  modalVertOffset: 44,


/* ------------------------------------------------------------------------------------------
   End Configuration
------------------------------------------------------------------------------------------ */

  CIOcontrast: false,
  numof: $(".cutitout").length,
  selectedElem: '',
  currentEl: '',
  

  /* Initiate CutItOut
  ---------------------------------------------------------------------------------------- */
  cio:function () {
    // Add the overlay and modal window container to the document
    //$('body').append("<div id='op'></div><div id='cutoutbox'><div id='cutdiv' class='divsm'><div id='cutdivint'><div class='cutnavT'><a class='tlt' href='#' id='resize'>Size [s]</a><a class='tlt' href='#' id='contrast'>Contrast [c]</a><a class='trt' href='#' id='cutdivx'>Close [x, Esc]</a></div><div id='cuttext'><div id='cuttextint'></div></div><div class='cutnavB'><a class='tlt' href='#' id='cutdivP'>Prev [<-, p]</a><a class='trt' href='#' id='cutdivN'>Next [->, n]</a></div></div></div></div>");

    $('body').append("<div id='op'></div><div id='cutdiv' class='divsm'><div id='cutdivint'><div class='cutnavT'><a class='tlt' href='#' id='resize'>Size [s]</a><a class='tlt' href='#' id='contrast'>Contrast [c]</a><a class='trt' href='#' id='cutdivx'>Close [x, Esc]</a></div><div id='cuttext'><div id='cuttextint'></div></div><div class='cutnavB'><a class='tlt' href='#' id='cutdivP'>Prev [<-, p]</a><a class='trt' href='#' id='cutdivN'>Next [->, n]</a></div></div></div>");

    // Add the markers to marked elements on page
    cutitout.addElmarkers();

    // Apply hover effects (browser dependent) to marked elements on page
    cutitout.applyEleffects();
    
    // Make ready the Cut It Out! UI
    cutitout.setupUI();

  },


  /* Check configuration for icon setting on marked elements
  ---------------------------------------------------------------------------------------- */
  addElmarkers:function() {
    if(cutitout.addMarker) {$(".cutitout").addClass('iconmarker').attr('title','Cut It Out');}
  },


  /* IE does not support the outline property on all elements, so we give it a bg color
  ---------------------------------------------------------------------------------------- */
  applyEleffects:function() {
    if($.browser.msie){
      $(".cutitout").hover(
        function () {
          $(this).css('backgroundColor',cutitout.bgcolor);
        },
        function () {
          $(this).css('backgroundColor','transparent');
        }
      );
    } else {
      $(".cutitout").hover(
        function () {
          var outcolor = '1px dashed'+cutitout.outlineColor;
          $(this).css('outline',outcolor);
        },
        function () {
          $(this).css('outline','none');
        }
      );
    }
  },


  /* Pause before moving forward
  ---------------------------------------------------------------------------------------- */
  pause:function(mils) {
    var date = new Date();
    curDate = null;
    do { var curDate = new Date(); }
    while ( curDate - date < mils);
  },


  /* getPageSize() by quirksmode.com 
  ---------------------------------------------------------------------------------------- */
  getPageSize:function() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
      xScroll = window.innerWidth + window.scrollMaxX;
      yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
      if(document.documentElement.clientWidth){
        windowWidth = document.documentElement.clientWidth;
      } else {
        windowWidth = self.innerWidth;
      }
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
      pageHeight = windowHeight;
    } else {
      pageHeight = yScroll;
    }
    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
      pageWidth = xScroll;
    } else {
      pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
    return arrayPageSize;
  },
  

  /* getPageScroll() by quirksmode.com
  ---------------------------------------------------------------------------------------- */
  getPageScroll:function() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    arrayPageScroll = new Array(xScroll,yScroll);
    return arrayPageScroll;
  },


  /* ----------------------------------------------------------------------------------------
      Keyboard Events Captured
  ---------------------------------------------------------------------------------------- */
  setUpKeyNav:function() {
    $(document).keydown(function(objEvent) {
      cutitout.actOnKeyEvent(objEvent);
    });
  },


  abortKeyNav:function() {
    $(document).unbind();
  },


  /* Keys harnessed: "<-" for Previous; "->" for Next;
     "Esc" and "x" for Close; "T" for Toggle Size
  ---------------------------------------------------------------------------------------- */
  actOnKeyEvent:function(objEvent) {

    // IE
    if(objEvent == null) {
     var keycode = event.keyCode;
     var escapeKey = 27;
    // Mozilla
    } else {
      var keycode = objEvent.keyCode;
      var escapeKey = 27;
    }

    // Grab key in lower case form
    var key = String.fromCharCode(keycode).toLowerCase();

    // Close the Cutout
    if( (key == 'x') || (keycode == escapeKey) ) {cutitout.closeCutOut();}

    // Previous Paragraph
    if( (key == 'p') || (keycode == 37) ) {
      if(cutitout.currentEl != 0) {
        cutitout.prevElem(cutitout.currentEl-1);
      }
    }

    // Next Paragraph
    if( (key == 'n') || (keycode == 39) ) {
       if(cutitout.currentEl+1 != cutitout.numof) {
         cutitout.nextElem(cutitout.currentEl+1);
       }
    }

    // Toggle Size
    if(key == 's') {cutitout.toggleSize();}
    
    // Toggle Contrast
    if(key == 'c') {cutitout.toggleContrast();}

  },


  /* 'Next' button navigation
  ---------------------------------------------------------------------------------------- */
  nextElem:function(nextEl) {

    cutitout.currentEl = nextEl;

    $("#cuttextint").html('');
    var checkElem =  $($(".cutitout").get(nextEl)).prev();
    $($(".cutitout").get(nextEl)).clone().appendTo("#cuttextint").attr('title','');
    if( $(checkElem).is(":header") ) {$(checkElem).clone().prependTo("#cuttextint");}

    $("#cuttextint *").removeClass('cutitout iconmarker').css({'outline':'none','cursor':'text','line-height':'1.4em'});
    
    var currBG = $("#cuttext").css("backgroundColor");

    if(currBG == 'rgb(235, 235, 235)') {
      $("#cuttextint *").css({'color':'#222'});
    } else {
      $("#cuttextint *").css({'color':'#EBEBEB'});
    }

    cutitout.setNavigation(nextEl);
    return false;

  },


  /* 'Previous' button navigation
  ---------------------------------------------------------------------------------------- */
  prevElem:function(prevEl) {

    cutitout.currentEl = prevEl;

    $("#cuttextint").html('');
    var checkElem =  $($(".cutitout").get(prevEl)).prev();
    $($(".cutitout").get(prevEl)).clone().appendTo("#cuttextint").attr('title','');
    if( $(checkElem).is(":header") ) {$(checkElem).clone().prependTo("#cuttextint");}

    $("#cuttextint *").removeClass('cutitout iconmarker').css({'outline':'none','cursor':'text','line-height':'1.4em'});
    
    var currBG = $("#cuttext").css("backgroundColor");

    if(currBG == 'rgb(235, 235, 235)') {
      $("#cuttextint *").css({'color':'#222'});
    } else {
      $("#cuttextint *").css({'color':'#EBEBEB'});
    }

    cutitout.setNavigation(prevEl);
    return false;

  },


  /* Set / reset button navigation
  ---------------------------------------------------------------------------------------- */
  setNavigation:function(elemIn) {

    if((elemIn == 0) && (cutitout.numof != 1)) {

      $("#cutdivP").hide();
      $("#cutdivN").show();

      var nextEl = elemIn+1;

      $("#cutdivN").unbind("click.cutitout").bind("click.cutitout", function(){
        cutitout.nextElem(nextEl);
        return false;
      });

    } else if(cutitout.numof == 1) {

      $("#cutdivN,#cutdivP").hide();

    } else if(elemIn+1 == cutitout.numof) {

      $("#cutdivN").hide();
      $("#cutdivP").show();

      var prevEl = elemIn-1;

      $("#cutdivP").unbind("click.cutitout").bind("click.cutitout",function(){
        cutitout.prevElem(prevEl);
        return false;
      });

    } else {

      $("#cutdivN,#cutdivP").show();

      var nextEl = elemIn+1;

      $("#cutdivN").unbind("click.cutitout").bind("click.cutitout", function(){
        cutitout.nextElem(nextEl);
        return false;
      });

      var prevEl = elemIn-1;

      $("#cutdivP").unbind("click.cutitout").bind("click.cutitout",function(){
        cutitout.prevElem(prevEl);
        return false;
      });

    }

  },



  /* ----------------------------------------------------------------------------------------
      Set Up UI
  ---------------------------------------------------------------------------------------- */

  setupUI:function() {
    $(".cutitout").click(function () {

      // Hide problematic IE elements
      $('embed, object, select').css({ 'visibility' : 'hidden' });

      // Capture the current index
      var initEl = $(".cutitout").index(this);

      cutitout.currentEl = initEl;

      cutitout.selectedElem = $(this);
      
      // Color the text clicked on - deprecated after adding the contrast toggle
      //$(this).css({'color':cutitout.selectedElemColorActive});

      var dimensions = cutitout.getPageSize();
      var thescroll = cutitout.getPageScroll();

      var scrollY = thescroll[1];
      var initY = scrollY+cutitout.modalVertOffset;

      var windowWidth = dimensions[2];
      var boxWidth = $("#cutdiv").width();
      
      var initX = (windowWidth - boxWidth)/2;

      // Intitialize the overlay and modal window
      $("#op").css({'width':dimensions[0],'height':dimensions[1],'backgroundColor':cutitout.overlayBgColor,'opacity':0.9}).fadeIn('slow');
      // $("#cutoutbox").css({'top': initY});
      
      $("#cutdiv").css({'top': initY, 'left': initX});

      // $("#cutoutbox,#cutdiv").fadeIn('slow');
      
      $("#cutdiv").fadeIn('slow');

      // Clone the selected content and append to modal window interior
      $(this).clone().appendTo("#cuttextint").attr('title','');

      // Check for a header - prepend if exists
      if( $(this).prev().is(":header") ) {
        $("#cuttextint").prepend( $(this).prev().clone() );
      }

      // Reset some of the styling
      $("#cuttextint *").removeClass('cutitout iconmarker').css({'backgroundColor':'transparent','color':'#222','outline':'none','cursor':'text','line-height':'1.4em'});

      $("#cuttextint").attr('tabindex','100').focus();

      // Set up the Previous and Next links:
      cutitout.setNavigation(initEl);

      // Add the keyboard actors
      cutitout.setUpKeyNav();

      // If the user resizes the window, we want to adjust the overlay and modal
      $(window).resize(function() {

        var Rdimensions = cutitout.getPageSize();
        var Rthescroll = cutitout.getPageScroll();

        var RscrollY = thescroll[1];
        var RinitY = scrollY+cutitout.modalVertOffset;
        
        var RwindowWidth = Rdimensions[2];
        var RboxWidth = $("#cutdiv").width();
      
        var RinitX = (RwindowWidth - RboxWidth)/2;

        var currWidth = $("#cutdiv").width();

        $("#op").css({'width':Rdimensions[0],'height':Rdimensions[1]});
        // $("#cutoutbox").css({'top': RinitY});
        
        $("#cutdiv").css({'top': RinitY, 'left': RinitX});

        if(currWidth > 810) {
          if(Rdimensions[0] > 1400) {
            $('#cuttextint').css({'fontSize': '1.5em'});
          } else {
            $('#cuttextint').css({'fontSize': '1em'});
          }
        }


      });

      return false;

    });

    cutitout.setupClose();
    cutitout.setSizeToggle();
    cutitout.setContrastToggle();

  },


  /* What happens when Cut It Out is closed
  ---------------------------------------------------------------------------------------- */
  closeCutOut:function() {
    // Pleasant effect
    $("#op").fadeOut('slow');
    //$("#cutoutbox,#cutdiv").fadeOut('slow');
    
    $("#cutdiv").fadeOut('slow');

    // Ensure the content is emptied
    $("#cuttextint").html('');
    
    // Reset contrast
    $("#cuttext").css({'backgroundColor':'#EBEBEB'});
      $("#cuttextint *").css({'color':'#222'});

    // Set the color of the clicked on element in the native content to 'visited'
    $(cutitout.selectedElem).css({'color':cutitout.selectedElemColorVisited});

    // Restore problematic IE elements
    $('embed, object, select').css({ 'visibility' : 'visible' });

    // Remove the key events
    cutitout.abortKeyNav();

    return false;

  },


  /* Setting up close
  ---------------------------------------------------------------------------------------- */
  setupClose:function() {
    // $("#op, #cutoutbox, #cutdivx").click(function () {
      
    $("#op, #cutdivx").click(function () {
      cutitout.closeCutOut();
      return false;
    });

    // Void the above onclick for the content container
    // since we need to be able to click inside the box
    //$("#cutdiv").click(function () {return false;});
  },



  /* From a fixed width to 'almost' full width and height window
  ---------------------------------------------------------------------------------------- */
  toggleSize:function() {

    // dimensions = [pageWidth,pageHeight,windowWidth,windowHeight]
    var dimensions = cutitout.getPageSize();

    var windowWidth = dimensions[2];

    var currWidth = $("#cutdiv").width();
    var currHeight = $("#cutdiv").height();

    if(dimensions[3] > 468) {
      var expHt = dimensions[3]-100;
      var intHt = expHt-100;
    } else {
      var expHt = 468;
      var intHt = 368;
    }

    if(currWidth == 810) {  // 810x464 is the initial/default window size

      var newWidth = windowWidth*.9;
      var newX = (windowWidth - newWidth)/2;

      $('#cutdiv').animate({ width: '90%', height: expHt, left: newX },400);

      $('#cuttext').animate({ width: '100%', height: intHt },400).addClass('divlg');  //alert('added?');

      if(dimensions[0] > 1400) {
        $('#cuttextint').css({'fontSize': '1.5em'});
      } else {
        $('#cuttextint').css({'fontSize': '1em'});
      }

    } else {
      
      var newX = (windowWidth - 810)/2;

      $('#cutdiv').animate({ width: '810px', height: '468px', left: newX },400);
      $('#cuttext').animate({ width: '788px', height: '368px' },400).removeClass('divlg');
      $('#cuttextint').css({'fontSize': '1em'});
    }

  },

  setSizeToggle:function() {
    $("#resize").click(function () {
      cutitout.toggleSize();
      return false;
    });
  },
  
  toggleContrast:function() {

    var currBG = $("#cuttext").css("backgroundColor");

    if(currBG == 'rgb(235, 235, 235)') {
      $("#cuttext").css({'backgroundColor':'#222'});
      $("#cuttextint *").css({'color':'#EBEBEB'});
      
      cutitout.CIOcontrast = false;

    } else {
      $("#cuttext").css({'backgroundColor':'#EBEBEB'});
      $("#cuttextint *").css({'color':'#222'});
      
      cutitout.CIOcontrast = true;
    }
    
  },
  
  setContrastToggle:function() {
    $("#contrast").click(function () {
      cutitout.toggleContrast();
      return false;
    });
  }

} // END of cutitout object


// DO it! :-)
cutitout.cio();



});
