// namespace function, immediately called
(function () {
  // globals
  var $ = jQuery;
  var lib = hsp;

  // init jquery extension
  $.fn.centerview = function () {};

  // variables
  var c = $.fn.centerview;
  var $header;
  var $cvdiv;
  var $cvcont;
  var $max;
  var opts;
  var ie6 = lib.ie6;
  var ios = lib.ios;
  
  $(document).ready(function() {

    $('#move-all').append(
      '<div id="centerview-header" >'+
      '<div id="centerview-header-left" style="float:left">'+
      ''+
      '</div>'+
      '<div id="centerview-close" style="float:right"><a href="#"></a>'+
      '</div>'+
      '<div id="centerview-max" ><a href="#"></a></div>'+
      '</div>'+
      '<div id="centerview-div" >'+
      '<div id="centerview-content">'+
      '</div></div>'
      );
    // initialize vars
    $header = jQuery('#centerview-header');
    $cvdiv = jQuery('#centerview-div');
    $cvcont = jQuery('#centerview-content');
    $max = jQuery('#centerview-max');
    c.isvisible = false;
    c.navibarheight = $('#navibar').height();
    opts = c.defaults;

    // can be used to show a centerview programmatically
    // the function is defined 'late' on document ready, as its presence is used by the javascript
    //  in page_laod.php
    c.showdiv = function showdiv(divid,cb) {
      if (divid) {
        $('#centerview-content').html($(divid).html());
        $('#centerview-div').scrollTop(0);
      }
      c.show(cb);
    };

  }); // end of document.ready()

  function mergeOpts(options) {
    var res = $.extend({}, c.defaults, options);
    return res;
  }

  if (ios) {
    c.init = function init(options) {
      var opts = mergeOpts(options);
      // reassign cvcont, as it has moved
      $cvcont = $('#centerview-content');

      // leave a margin for the navibar
      $cvcont.css({
        marginTop: c.navibarheight,
        width : 950,
        marginLeft : 'auto',
        marginRight : 'auto'
      });

      c.transition.init(opts);
      $('#navibar-backbutton').click(
        c.defaults.close);
    }

  } else {
    // non-ios
    c.init = function init(options) {
      var opts = mergeOpts(options);

      // ie6 is not able to deal with top:x bottom:x height:auto
      // what works is setting the height, so this is done in a window.resize
      // event handler

      $cvdiv.css({
        display: 'none',
        position: 'absolute',
        zIndex: 1000,
        top: opts.top + opts.headerheight + 'px',
        bottom: ie6 ? 'auto' : opts.bottom + 'px',
        left: '0',
        backgroundColor: '#ffffff',
        height: ie6 ? '600px' : 'auto',
        width: opts.width + 'px'
      });

      $header.css({
        backgroundColor: '#FFFFFF',
        color : '#006600'
      });

      //$('#centerview-content').css({
      //overflow : 'auto'
      //});

      $('#centerview-close').click(c.defaults.close);

      $max.click(function () {
        c.togglemax();
      });

      // on ie6, we must set the centerview height via javascript
      if (ie6) {
        $(window).resize(function () {
          if (!$cvdiv.is(':visible')) {
            return;
          }
          var opts = c.defaults;
          var winH = $(window).height();
          // compute the height
          var spaceAbove = (opts.top * opts.fac) + opts.headerheight;
          var spaceUnder = Math.max((opts.bottom * opts.fac),opts.minbottom);
          var modalH = winH -spaceAbove - spaceUnder - opts.borderheight;
          $cvdiv.height(modalH);
        }).trigger('resize');
      }

      // fix frame height
      $(window).resize(c.fixframe);

      // check if we have to maximize as default
      var winH = $(window).height();
      if (winH < opts.maxi) {
        c.maximize();
      }
    }
  }

  c.adjustCv = function adjustCv() {
    // set the cv to the content height
    $cvdiv.height($cvcont.height());
    var cvh = $cvdiv.height();
    // set the body to the cv height
    $('body').height(cvh);
  }

  if (ios) {
    c.clickClosebutton = function () {
      $('#navibar-backbutton').click();
    };
  } else {
    c.clickClosebutton = function () {
      $('#centerview-close').click();
    }
  }

  if (ios) {
    c.show = function showMobile(cb) {
      if (c.isvisible) {
        cb();
        return;
      }
      c.isvisible = true;
      c.defaults.onshow();
      c.transition.show(function () {
        c.defaults.aftershow();
        cb();
      });
      return;
    };
  } else {
    // not ios
    c.show = function showDesktop(cb) {
      if (c.isvisible) {
        cb();
        return;
      }
      c.isvisible = true;
      c.defaults.onshow();
      $header.fadeIn(c.defaults.duration);
      $cvdiv.fadeIn(c.defaults.duration,function () {
        c.defaults.aftershow();
        cb();
      });

      // if there is an iframe, fade it out:
      var iframe = $('#centerview-iframe');
      if (iframe.length) {
        iframe.fadeOut(c.defaults.duration);
        iframe.remove();
      }
    };

  }

  // called on every window resize:
  // and after iframe creation
  c.fixframe = function fixframe() {
    // we check if the window height is smaller than
    var opts = c.defaults;
    var winH = $(window).height();
    //console.log('window height: '+winH);
    if ((winH < opts.maxi) & (!hsp.ios)) {
      if (opts.fac != 0) {
        c.maximize();
      }
    }
    var iframe = $('#centerview-iframe');
    if (!iframe.length) {
      return;
    }
    // we have an iframe
    // compute the height
    var spaceAbove = (opts.top * opts.fac) + opts.headerheight;
    var spaceUnder = Math.max((opts.bottom * opts.fac),opts.minbottom);
    var modalH = winH -spaceAbove - spaceUnder - opts.borderheight;
    //modalH = winH - ((opts.top * opts.fac) + opts.headerheight) - ((opts.bottom * opts.fac) + opts.minbottom)-opts.borderheight;
    iframe.height(modalH);
  }

  // shows an external url in an iframe
  c.iframe = function iframe(options, url,cb) {
    var opts = $.extend({}, c.defaults, options);

    // the iframe is added dynamically to the page
    $('#move-all').append(
      '<iframe id="centerview-iframe" frameborder="0" src="'+url+'" style="display:none"></iframe>'
      );
    if (ios) {
      // start out maximized on ios
      opts.fac = 0;
    }
    $('#centerview-iframe').css({
      position: 'absolute',
      zIndex: 1000,
      top: ((opts.top * opts.fac) + opts.headerheight) + 'px',
      left: '50%',
      marginLeft: -((opts.width + opts.borderwidth)/2)+'px',
      backgroundColor: '#ffffff',
      width: opts.width + 'px'
    });

    c.fixframe();

    opts.onshow();
    // check if there is a $cvdiv we have to hide
    if (c.normalCvVisible()) {
      c.isvisible=false;
      $cvdiv.fadeOut(opts.duration);
    }
    // show the iframe
    $header.fadeIn(opts.duration);
    $('#centerview-iframe').fadeIn(opts.duration,cb);
  }

  if (ios) {
    c.hide = function hideMobile(cb) {
      if (!c.isvisible) {
        cb();
        return;
      }
      c.defaults.beforehide();
      c.isvisible = false;
      c.transition.hide(function () {
        c.defaults.onhide();
        cb();
      });
    }

  } else {
    // not ios
    c.hide = function hideDesktop(cb) {
      // check if there is something to do
      if (!c.normalCvVisible() && !c.iframevisible()) {
        cb();
        return;
      }
      c.defaults.beforehide();
      // handle the iframe, if present
      var iframe = $('#centerview-iframe');
      if (iframe.length) {
        // we have an iframe
        iframe.fadeOut(opts.duration,function () {
          iframe.remove();
        });
        c.defaults.onhide();
        $header.fadeOut(opts.duration,cb);
        return;
      }
      if (c.normalCvVisible()) {
        $cvdiv.fadeOut(opts.duration);
        c.isvisible = false;
        c.defaults.onhide();
        $header.fadeOut(opts.duration,cb);
        return;
      }
      // we shall not reach this point
      cb(); // to be save we call cb
      lib.error('did expect to find normal cv or iframe');
    };

  }

  c.togglemax = function () {
    var fac = c.defaults.fac;
    if (fac) {
      c.maximize();
    } else {
      c.minimize();
    }
  }

  // maximize the cv
  c.maximize = function () {
    if (ios) {
      lib.error('maximize called on ios device');
    }
    var opts = c.defaults;
    var iframe = c.iframevisible();

    opts.fac = 0;
    $cvdiv.css({
      borderBottomWidth : 0
    });
    opts.borderheight = 0;
    $header.css({
      borderTopWidth : 9
    });
    opts.headerheight = 39;
    var top = opts.headerheight;
    var bottom = opts.minbottom;

    // move up the header to the top
    if (ie6) {
      $header.css({
        top: 0
      });
    }else {
      $header.animate({
        top: 0
      },opts.maxdur);
    }
    
    if (ie6) {
      $cvdiv.css({
        top: top + 'px',
        bottom: 'auto',
        height: '600px'
      });
      $(window).trigger('resize');
      $max.addClass('selected');
    } else {
      // not ie6, we do animation
      $cvdiv.animate({
        top: top,
        bottom: bottom
      },opts.maxdur,
      'swing',
      function () {
        $max.addClass('selected');
      }
      );
    }

    if (iframe) {
      // handle iframe
      var winH = $(window).height();
      var modalH = winH - top - bottom - opts.borderheight;
      //    var beforeH = iframe.outerHeight();
      iframe.css({
        borderBottomWidth : 0
      });
      //    var afterH = iframe.outerHeight();
      iframe.animate({
        top: top,
        height: modalH
      },opts.maxdur,
      'swing',
      function () {
        $max.addClass('selected');
      });
    }
  }

  c.minimize = function () {
    if (ios) {
      lib.error('minimize called on ios device');
    }
    var opts = c.defaults;
    var iframe = c.iframevisible();
    opts.fac = 1;
    $cvdiv.css({
      borderBottomWidth : 5
    });
    opts.borderheight = 5;
    $header.css({
      borderTopWidth : 5
    });
    opts.headerheight = 35;
    $max.removeClass('selected');
    var top = opts.top * opts.fac + opts.headerheight;
    var bottom = opts.bottom * opts.fac + opts.minbottom;
    // handle normal cv
    // move header back in place
    if (ie6) {
      $header.css({
        top: opts.top
      });
    }else {
      $header.animate({
        top: opts.top
      },opts.maxdur);
    }

    if (ie6) {
      $cvdiv.css({
        top: top + 'px',
        bottom: 'auto',
        height: '600px'
      });
      $(window).trigger('resize');
    } else {
      // not ie6
      $cvdiv.animate({
        top: top,
        bottom: bottom
      },opts.maxdur,'swing');
    }

    if (iframe) {
      // handle iframe
      iframe.css({
        borderBottomWidth : 5
      });
      var winH = $(window).height();
      var modalH = winH - top - bottom - opts.borderheight;
      iframe.animate({
        top: top,
        height: modalH
      },opts.maxdur,'swing');
    }
  }

  c.iframevisible = function () {
    var iframe = $('#centerview-iframe');
    if (iframe.length) {
      return iframe;
    }
    return false;
  };

  c.normalCvVisible = function normalCvVisible() {
    return c.isvisible;
  };

  c.setdefault = function (options) {
    var opts = $.extend({}, c.defaults, options);
    c.defaults = opts;
  };

  c.defaults = {
    'navibarClose' : $('#navibar-backbutton'),
    'transition' : 'simple',
    'headerheight' : 35,
    'top' : 140,
    'bottom' : 90,
    'minbottom' : 32,
    'width' : 960,
    'maxi' : 768,
    'fac' : 1,
    'borderwidth' : 10,
    'borderheight' : 5,
    'duration' : 500,
    'maxdur' : 200,
    'onshow' : undefined,
    'aftershow' : undefined,
    'beforehide' : undefined,
    'onhide' : undefined,
    'background-color' : '#FFFFFF',
    'close' : function () {
      lib.error('centerview.close not initialized');
    }
  };

}());
