//lightbox.js
var webpage = {
  scrollSize : function(){
    if( window.innerHeight && window.scrollMaxY ){
      // Firefox
      pageWidth = window.innerWidth + window.scrollMaxX;
      pageHeight = window.innerHeight + window.scrollMaxY;
    }else if( document.body.scrollHeight > document.body.offsetHeight ){
      // all but Explorer Mac
      pageWidth = document.body.scrollWidth;
      pageHeight = document.body.scrollHeight;
    }else{
      // works in Explorer 6 Strict, Mozilla (not FF) and Safari
      pageWidth = document.body.offsetWidth + document.body.offsetLeft; pageHeight = document.body.offsetHeight + document.body.offsetTop;
    }
    return {width: pageWidth, height: pageHeight};
  },
  viewportWidth: function() {
    return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
  },

  viewportHeight: function() {
    return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
  },
  
  viewportSize: function() {
    return { width: this.viewportWidth(), height: this.viewportHeight() };
  }

};

var LightBox = Class.create({
  id : "light_box",
  newWidth : 200,
  newHeight: 200,
  swf_dimensions: {
     'calendar'   : {'width': 794, 'height': 557},
     'photobook' : {'width': 765, 'height': 536},
     'photobook_quality' : {'width': 518, 'height': 395},
     'flickbook' : {'width': 640, 'height': 360},
     'bespokebook' : {'width': 765, 'height': 536},
     'book_of_the_month' : {'width': 800, 'height': 600}
 },
  'initialize': function () {
    /* initialize function, can only be called once.
      it creates the layers and links the page to the
      required CSS to display the lightbox properly */
    if( !$(this.id) ){
      // if the layer has not been created before
      
      // create the layer to cover the whole page
      var screen = document.createElement("div");
      screen.id  = "screen";
      screen.style.display = "none";

      // create the layer which holds the content container
      var light_box  = document.createElement("div");
      light_box.id   = this.id;
      light_box.style.display = "none";

      // create the layer to which we will write the content      
      var content  = document.createElement("div");
      content.id   = this.id + "_content";
      content.style.display = "none";

      /* this layer is created to be able to calculate the size
        of the lightbox */
      var content_sizer = document.createElement("div");
      content_sizer.id  = "content_sizer";
      
      // the close button is at the bottom right of the lightbox
      var close_btn = document.createElement("div");
      close_btn.id  = this.id + "_close";
      close_btn.innerHTML = "close";

      // add the content layer and close button to the lightbox
      light_box.appendChild(close_btn);
      light_box.appendChild(content);
      
      // add the required CSS
      this.add_css("/++resource++bob/css/screen/src/lightbox.css");

      // add the rest to the document body
      document.body.appendChild(screen);
      document.body.appendChild(light_box);
      document.body.appendChild(content_sizer);

      // add the even listeners to the back screen and close button
      $('screen').observe('click', this.off.bindAsEventListener(this));
      $(this.id + '_close').observe('click', this.off.bindAsEventListener(this));

      // clean up the variables used
      light_box = screen = null;
      
      this.apply_handlers();
      
    }else{
      // if the layer already exists this has been called, we don't need to run it
      return false;
    }
  },
  'apply_handlers': function() {
      $$('.lightbox-trigger').each(function(trigger) {
          trigger.observe('click', this.update_content.bindAsEventListener(this));
      }.bind(this));
  },
  'update_content': function(event) {
      event.stop();

      var trigger = event.findElement('a');
      var content_type = trigger.readAttribute('content_type');

      if(content_type == 'swf') {
          var link = trigger.readAttribute('href');
          var vars = trigger.readAttribute('vars');
          
          var swf_size = new Array();
          swf_size[0]   = 765;
          swf_size[1]   = 536;

          var type = trigger.readAttribute('type');

          if( this.swf_dimensions[type] ){
            swf_size[0]   = this.swf_dimensions[type].width;
            swf_size[1]   = this.swf_dimensions[type].height;
          }
          
          if( !trigger.readAttribute("dims") )
              trigger.writeAttribute("dims", swf_size[0] +":"+swf_size[1]);
          
          if(type != 'flickbook') {
              this.set_content('<embed width="' + swf_size[0] + '" height="' + swf_size[1] + '" quality="high" src="' + link + '" type="application/x-shockwave-flash" />', trigger);
          } else {
            this.set_content('', trigger);
            var player = new FlickbookPlayer(
                'light_box_player', {
                  'first_play_video_name' : 'content',
                  'video_path' : link,
                  'loop_video' : true,
                  'container' : 'light_box_content',
                  'width': swf_size[0],
                  'height': swf_size[1],
                  'skin_path' : ''
                }
             );
          }
      
      } else if(content_type == 'img') {
          var link = trigger.readAttribute('href');
          this.set_content('<img src="' + link + '" />', trigger);
      } else if( content_type == 'iframe' ){
          var link = trigger.readAttribute('href');
          trigger.writeAttribute("dims", '780:480');
          this.set_content('<div style="height : 480px; width : 780px"><iframe frameborder="0" scrolling="auto" height="480" width="780" src="http://reorder.photoprintit.de/pageHandler.faces?mode=microsite_usage&keyaccount=18853"></iframe></div>', trigger);
      } else { // assume content is in an element which is referenced by an id
          var id = trigger.readAttribute('target');
          this.set_content_from(id, trigger);
      }
  },
  'visible': function(){
    // checks whether the lighbox is displayed or not
    if( $(this.id).getStyle("display") == "none" )
      return false;
    else
      return true;
  },
  'on': function () {
    $(this.id + '_content').hide();
    if( !this.visible() ){
      // if the lightbox is hidden show it
      Effect.Appear(this.id, {duration : .5});
      Effect.Appear("screen", {to: 0.6, duration : .3});
      // makes sure the screen covers the whole page
      $("screen").setStyle({height: webpage.scrollSize()["width"] + "px"});
    }
  },
  'off': function () {
    if( this.visible() ){
      // if the lightbox is visible it hides it
      Effect.Fade(this.id, {duration : .3});
      Effect.Fade("screen", {duration : .3, delay: .2});
    }
  },
  'loading' : function (){ 
      if( this.visible() )
        Effect.Fade(this.id + "_content", {duration: .2});

      setTimeout(this.load,250);
    
  },
  'load'   : function (){
    // if the lightbox is visible it shows the loading gif
    var img = document.createElement("img");
    img.id  = "light_box_img_load";
    img.src = "/++resource++bob/img/loading.gif";

    $("light_box").appendChild(img);
    img = null;
  },
  'unload' : function (){
    // get rid of the loading gif
    setTimeout('$("light_box").removeChild($("light_box_img_load"))',1250);
  },
  'autoResize' : function (set_width){
      /*  this function looks for the most appropriate dimensions for the
          lightbox to display the content */
      var breaker = 0;
      var ratio = 900;

      while( $("content_sizer").offsetHeight != $("content_sizer").offsetWidth && breaker < 5 && ratio > 80 ){
        
        ratio = $("content_sizer").offsetWidth - $("content_sizer").offsetHeight;
        
        if( ratio > 0 ){

          $("content_sizer").setStyle({width: $("content_sizer").offsetWidth - (ratio / 2) + "px"});

          if( $("content_sizer").clientWidth < $("content_sizer").scrollWidth ){
            $("content_sizer").setStyle({width: $("content_sizer").scrollWidth});
            breaker = 7;
          }
        }
        else
          $("content_sizer").setStyle({width: $("content_sizer").offsetWidth + (ratio / 2) + "px"});

        breaker++;
      }

    if( typeof(set_width) != "undefined" )
        $("content_sizer").setStyle({width: set_width + "px"});

      /*  by now we have the appropriate dimensions but the height could be too small
          we'll set the height to the scroll height, if it's too large it will be
          fixed later on */
      if( $("content_sizer").clientHeight < $("content_sizer").scrollHeight ){
        $("content_sizer").setStyle({height: $("content_sizer").scrollHeight});
      }

      /*  here we make sure that the lightbox is no smaller than 100px
          and not bigger than the user's page */
      if( $("content_sizer").offsetHeight < 100 )
        this.newHeight = 100;
      else if( $("content_sizer").offsetHeight > webpage.viewportHeight() )
        this.newHeight = webpage.viewportHeight - 100;
      else
        this.newHeight = $("content_sizer").offsetHeight;
      
      if( $("content_sizer").offsetWidth < 200 )
        this.newWidth = 200;
      else if( $("content_sizer").offsetWidth > webpage.viewportWidth() )
        this.newWidth = webpage.viewportWidth() - 100;
      else
        this.newWidth = $("content_sizer").offsetWidth;
      
      this.resize(this.newWidth, this.newHeight);

      // clean up after ourselves
      $("content_sizer").setStyle({width: "", height: ""});
      this.newWidth = this.newHeight = 100;
      breaker = ratio = null;
  },
  'resize': function(width, height){
    new Effect.Morph(this.id, {style:'width:' + width + 'px; height:' + height + "px; margin-left:-" + width/2 + "px; margin-top: -" + height/2 + "px"});
  },
  'set_content': function (content, trigger) {
    /* sets the content to be shown in the lightbox
      if the lightbox is hidden it shows it */
      $("content_sizer").innerHTML = '';
      
      this.on();
      // show loading
      this.loading();
      // set the content in the content_sizer
      $("content_sizer").innerHTML = content;

      var dims    = trigger.readAttribute('dims');
      
      if( dims ){
        var items   = dims.split(':');
        var width   = items[0];
        var height  = items[1];
      }

      if( typeof(width) == "undefined" && typeof(height) == "undefined" ){
      // get the adecuate dimensions
        this.autoResize();
      }else if( typeof(width) != "undefined" && typeof(height) == "undefined" ){
        this.autoResize(width);
      }else
        this.resize(width, height);
      
      
      // add the content to the lighbox
      $(this.id + "_content").innerHTML = content;
      // hide the loading gif
      this.unload();
      // show the lightbox content once the gif is hidden
      Effect.Appear(this.id + "_content", {delay: 1.3});
  },
  'set_content_from': function(id, trigger){
  
    // returns the content of the lighbox
    this.set_content($(id).innerHTML, trigger);
  },
  'add_css': function(url, media){
    /* this function should be external, it adds a css
      to the page, with whichever url you provide */
    if( typeof(media) == "undefined" )
    	media = "screen";

    var newStyle    = document.createElement('link');
    newStyle.type   = 'text/css';
    newStyle.href   = url;
    newStyle.rel    = "stylesheet";
    newStyle.media  = media;
    document.getElementsByTagName("head")[0].appendChild(newStyle);
    newStyle = null;
  }
});

// SIFRController.js
var SIFRController = Class.create({
        'sizeOnOnload': false,
        'initialize': function ($target, $node_name) {
            var target = $($target);
            if (target) {
                var h4_titles = target.select($node_name);
                if (h4_titles.length > 0 ) {
                    this.load_titles();
                    var checker = this.checkTextSize.bind(this);
                    this.pe = new PeriodicalExecuter(checker, 0.5);
                    this.checkTextSize();
                }
            }
        },
        'load_titles': function () {
            sIFR.replace(
                glypha, {
                    selector: 'h4',
                    css: [
                        '.sIFR-root { text-align: left; color: #b3b3b3 }',
                        'em {font-style: none; font-weight: bold; color: #808080}'
                    ]
                }
            );
        },
        'checkTextSize': function (){
            var checker = $('textSizeChecker');
            if(!checker){
                // create the layer to check if the text has been resized
                var sizer_reference = document.createElement('div');
                    sizer_reference.id = 'textSizeChecker';
                    sizer_reference.style.fontSize    = '1em';
                    sizer_reference.style.height    = 'auto';
                    sizer_reference.style.position    = 'absolute';
                    sizer_reference.style.left        = '-999px';
                    sizer_reference.innerHTML = 'super';
                document.body.appendChild(sizer_reference);
                sizer_reference = null;
                checker = $('textSizeChecker');
            }
            if (this.sizeOnOnload) {
                /*if( BrowserDetect.browser == 'Firefox' && BrowserDetect.version > 2){
                    var resi = ($('ff3_div_2').offsetX / $('ff3_div_1').offsetX) + 1;

                }*/
                if (this.sizeOnOnload != checker.offsetHeight){
                    var flash_txt = $$('.sIFR-replaced');
                    var txt_flash = $$('.sIFR-alternate');

                    for( var i = 0; i < flash_txt.length; i++){

                        var tag_name    = flash_txt[i].tagName;
                        var parente        = flash_txt[i].parentNode;

                        var redo_title        = document.createElement(tag_name);
                        redo_title.innerHTML= txt_flash[i].innerHTML;
                        parente.insertBefore(redo_title, flash_txt[i]);
                        parente.removeChild(flash_txt[i]);

                    }
                    flash_txt = txt_flash = redo_title = tag_name = parente = null;
                    this.load_titles();
                }
            }
            this.sizeOnOnload = checker.offsetHeight;
        }
    }
);

// Client.js
var Client = Class.create(
  ChasteEnvironment, {
    'initialize': function ($super) {
      $super(false, true);
      var lightbox = new LightBox();
      var sifr_controller = new SIFRController('content', 'h4');
      fire('client:initialized');
    }
  }
);






// closer_look.js
var CloserLook = Class.create({
    'initialize': function() {
        this.chastise();
        this.apply_handlers();
    },
    'chastise': function() {
        this.triggers = $$('.view-trigger');
        this.descriptions = $$('.view-description');
        this.instructions = $('view-instructions');
        this.content_target = $('object')
    },
    'apply_handlers': function() {
        $$('.view-trigger').each(function(trigger){
            trigger.observe('click', this.update_view.bindAsEventListener(this))
        }.bind(this));
    },
    'update_view': function(event) {
        event.stop();
        var trigger = event.findElement('a');
        var link = trigger.readAttribute('href');
        var desc = $(trigger.readAttribute('id') + '-desc');
        
        // highlight link
        this.triggers.invoke('removeClassName', 'active');
        trigger.addClassName('active');
        
        // hide instructions
        this.instructions.hide()
        
        // show description
        this.descriptions.invoke('hide');
        desc.show();
        
        // update image content
        this.content_target.update('<img src="' + link + '" />');
        
    }
});

// init.js
observe('dom:loaded', 
  function () {
    $$('img').each(function(trigger){
        trigger.title = trigger.alt;
    })
    var debug = false;
    if (window.location.href.indexOf(':8080') > -1) {
      debug = true;
    }
    Logger.addMethods({'DEBUG': debug});
    var client = new Client();
    log('client initialised')
  }
);

// quote_book.js
var QuoteBook = Class.create({
    'initialize': function() {
        log('initing');
        this.chastise();
        this.apply_handlers();
        this.current_page = 1;
        this.changePage(1);
        log('changed page');
    },
    'chastise': function() {
        this.previouslink = $('previousPage');
        this.nextlink = $('nextPage');
        this.customer_sections = $$('.customer-section');
        this.papers_sections = $$('.papers-section');
        this.customers_slot = $('customer-quotes');
        this.papers_slot = $('paper-quotes');
        this.total_sections = 0;
        if(this.customer_sections.length > this.papers_sections.length) {
            this.total_sections = this.customer_sections.length;
        } else {
            this.total_sections = this.papers_sections.length;
        }
    },
    'apply_handlers': function() {
        this.previouslink.observe('click', this.previousPage.bindAsEventListener(this));
        this.nextlink.observe('click', this.nextPage.bindAsEventListener(this));
    },
    'previousPage': function(event) {
        event.stop();
        var target_page = 1;
        if(this.current_page == 1) {
            target_page = this.total_sections;
        } else {
            target_page = this.current_page - 1
        }
        this.changePage(target_page);
    },
    'nextPage': function(event) {
        event.stop();
        var target_page = this.total_sections;
        if(this.current_page == this.total_sections) {
            target_page = 1;
        } else {
            target_page = this.current_page + 1
        }
        this.changePage(target_page);
    },
    'changePage': function(page) {
        // hide current content
        this.customers_slot.hide();
        this.papers_slot.hide();
        
        // load new content
        var customers = '';
        var papers = '';
        if($('customers'+page)) {
            customers = $('customers'+page).innerHTML;
        }
        if($('papers'+page)) {
            papers = $('papers'+page).innerHTML;
        }
        this.customers_slot.update(customers);
        this.papers_slot.update(papers);
        this.current_page = page;
        
        // show new content
        this.customers_slot.show();
        this.papers_slot.show();
    }
});


// RegistrationFormHandler.js
var RegistrationFormHandler = Class.create(
  NamedFormHandler, {
    'on_data_success': function ($super, $data) {
      new Ajax.Request('/@@login.ajax', {
          'parameters': {
            'login': $('registration-form-login-input').getValue(),
            'password': $('registration-form-password-input').getValue()
          },
          'onSuccess': function () {
            var target_url = '/';
            if (typeof(getattr(window.location, 'replace', false)) == typeof(function () {})) {
              window.location.replace(target_url);
            }
            else {
              window.location.href = target_url;
            }
          },
          'on401': function () {
            var target_url = '/';
            if (typeof(getattr(window.location, 'replace', false)) == typeof(function () {})) {
              window.location.replace(target_url);
            }
            else {
              window.location.href = target_url;
            }
          }.bind(this)
        }
      );
    }
  }
);


