/*
 * RedTiki Cool Columns jQuery Plugin
 * @author Cam Worth (camw@redtiki.com.au)
 *
 * @type can be both,left or right
 */
(function( $ ){

  $.fn.angledcolumns = function( options ) {

    var settings = {
      'type' : 'both',
      'leftStart' : 0,
      'leftEnd' : 200,
      'leftStep' : 10,
      'rightStart' : 200,
      'rightEnd' : 0,
      'rightStep' : 10,
      'leftOverlay': '/columns/overlay.png',
      'maxSteps': 300,
      'leftGutter' : 0,
      'rightGutter' : 0,
      'debug' : false,
      'sandbagRightHeight' : 10,
      'sandbagLeftHeight' : 10,
      'onComplete' : function(el){}
    };

    var sandbag_tmpl = '<div style="padding:0px;margin:0px;height:{SANDBAGHEIGHT}px;line-height:{LINEHEIGHT};overflow:hidden;float:{DIRECTION};clear:{DIRECTION};width:{WIDTH}px;background-color:transparent;" class="sandbag sandbag-{DIRECTION}" id="{ID}">&nbsp;</div>';
    var sandbag_debug_tmpl = '<div style="padding:0px;height:{SANDBAGHEIGHT}px;margin:0px;line-height:{LINEHEIGHT};overflow:hidden;float:{DIRECTION};clear:{DIRECTION};width:{WIDTH}px;background-color:rgba(0,0,0,.6);" class="sandbag sandbag-{DIRECTION}" id="{ID}">&nbsp;</div>';

    return this.each(function() {
      // If options exist, lets merge them
      // with our default settings
      if ( options ) {
        $.extend( settings, options || {} );
      }
      //get the lineheight of the item...
      var lh = $(this).css('line-height');
      var to_insert = '';
      var nid = '';
      var dir = '';
      var width = 0;
      var el_height = 0;
      var total_steps = 0;
      var images_sandbagged = false;
      //establish how many of these should be added
      
      //make sure that the trackers for this el is attached
      if (typeof(this.ccleftpos) == 'undefined') {
          this.ccleftwidth = settings.leftStart;
          this.ccleftheight = 0;
          this.cclastid = false;
      }
      if (typeof(this.ccrightpos) == 'undefined') {
          this.ccrightwidth = settings.rightStart;
          this.ccrightheight = 0;
      }

      while( ((this.ccleftheight + el_height) <= $(this).height() && (this.ccrightheight + el_height) <= $(this).height()) && total_steps <= settings.maxSteps) {


          if (this.ccrightheight < $(this).height() && (settings.type == 'both' || settings.type == 'right') ) {

              nid = 'sbright-'+this.ccrightheight + this.id;
              dir = 'right';
              if (settings.rightStart > settings.rightEnd) {
                  width = (this.ccrightwidth >= settings.rightEnd) ? this.ccrightwidth - settings.rightStep : this.ccrightwidth;
              } else {
                  width = (this.ccrightwidth <= settings.rightEnd) ? this.ccrightwidth + settings.rightStep : this.ccrightwidth;
              }
              
              if (width) {
                  to_insert = (settings.debug) ? sandbag_debug_tmpl : sandbag_tmpl;
                  to_insert = to_insert.replace(/{LINEHEIGHT}/g,lh);
                  to_insert = to_insert.replace(/{ID}/g,nid);
                  to_insert = to_insert.replace(/{DIRECTION}/g,dir);
                  to_insert = to_insert.replace(/{WIDTH}/g,width);
                  to_insert = to_insert.replace(/{SANDBAGHEIGHT}/g,settings.sandbagRightHeight);

                  if (!this.cclastid) {
                      $(this).prepend(to_insert);
                  } else {
                      $('#'+this.cclastid).after(to_insert);
                  }

                  this.cclastid = nid;

                  if (el_height == 0) {
                      el_height = $('#'+nid).height();
                  }

                  this.ccrightwidth = width;
                  this.ccrightheight = this.ccrightheight + el_height;
              }
              

          }


          if (this.ccleftheight < $(this).height() && (settings.type == 'both' || settings.type == 'left')) {

              nid = 'sbleft-'+this.ccleftheight + this.id;
              dir = 'left';
              if (settings.leftStart > settings.leftEnd) {
                  width = (this.ccleftwidth >= settings.leftEnd) ? this.ccleftwidth - settings.leftStep : this.ccleftwidth;
              } else {
                  width = (this.ccleftwidth <= settings.leftEnd) ? this.ccleftwidth + settings.leftStep : this.ccleftwidth;
              }

              to_insert = (settings.debug) ? sandbag_debug_tmpl : sandbag_tmpl;
              to_insert = to_insert.replace(/{LINEHEIGHT}/g,lh);
              to_insert = to_insert.replace(/{ID}/g,nid);
              to_insert = to_insert.replace(/{DIRECTION}/g,dir);
              to_insert = to_insert.replace(/{WIDTH}/g,width);
              to_insert = to_insert.replace(/{SANDBAGHEIGHT}/g,settings.sandbagLeftHeight);

              if (!this.cclastid) {
                  $(this).prepend(to_insert);
              } else {
                  $('#'+this.cclastid).after(to_insert);
              }

              this.cclastid = nid;

              if (el_height == 0) {
                  el_height = $('#'+nid).height();
              }

              this.ccleftwidth = width;
              this.ccleftheight = this.ccleftheight + el_height;

          }
          //setup image sandbags so that images can be used in the angled cols...
          //basically we want to compute the max width between the sandbags...
          if (!images_sandbagged) {

              $('.img-sandbag',$(this)).each(function(){
                  $(this).before('<div style="height:'+$(this).height()+'px;" id="'+$(this).attr('id')+'_imgsandbag">&nbsp;</div>');
                  $(this).css({'position':'absolute','top':'0px','right':'0px'});
                  $(this).after('<div style="height:'+$(this).height()+'px;width:'+$(this).width()+'px;position:absolute;top:0px;right:0px;" id="'+$(this).attr('id')+'_imgsandbagoverlay" class="img-overlay">&nbsp;</div>');
              });

              images_sandbagged = true;
          }

          total_steps++;

      }

      //if the parent was not entirely filled by the sandbags then add some specially sized ones...
      if (this.ccrightheight < $(this).height() && (settings.type == 'both' || settings.type == 'right')) {
            nid = 'sbright-'+this.ccrightheight + this.id;
            dir = 'right';
            if (settings.rightStart > settings.rightEnd) {
              width = (this.ccrightwidth >= settings.rightEnd) ? this.ccrightwidth - settings.rightStep : this.ccrightwidth;
            } else {
              width = (this.ccrightwidth <= settings.rightEnd) ? this.ccrightwidth + settings.rightStep : this.ccrightwidth;
            }

            if (width) {
              to_insert = (settings.debug) ? sandbag_debug_tmpl : sandbag_tmpl;
              to_insert = to_insert.replace(/{LINEHEIGHT}/g,lh);
              to_insert = to_insert.replace(/{ID}/g,nid);
              to_insert = to_insert.replace(/{DIRECTION}/g,dir);
              to_insert = to_insert.replace(/{WIDTH}/g,width);
              to_insert = to_insert.replace(/{SANDBAGHEIGHT}/g,settings.sandbagRightHeight);

              if (!this.cclastid) {
                  $(this).prepend(to_insert);
              } else {
                  $('#'+this.cclastid).after(to_insert);
              }

              this.cclastid = nid;

              if (el_height == 0) {
                  el_height = $('#'+nid).height();
              }

              this.ccrightwidth = width;
              this.ccrightheight = this.ccrightheight + el_height;
            }


      }

      //if the parent was not entirely filled by the sandbags then add some specially sized ones...
      if (this.ccleftheight < $(this).height() && (settings.type == 'both' || settings.type == 'left')) {

          nid = 'sbleft-'+this.ccleftheight + this.id;
          dir = 'left';
          if (settings.leftStart > settings.leftEnd) {
              width = (this.ccleftwidth >= settings.leftEnd) ? this.ccleftwidth - settings.leftStep : this.ccleftwidth;
          } else {
              width = (this.ccleftwidth <= settings.leftEnd) ? this.ccleftwidth + settings.leftStep : this.ccleftwidth;
          }

          to_insert = (settings.debug) ? sandbag_debug_tmpl : sandbag_tmpl;
          to_insert = to_insert.replace(/{LINEHEIGHT}/g,lh);
          to_insert = to_insert.replace(/{ID}/g,nid);
          to_insert = to_insert.replace(/{DIRECTION}/g,dir);
          to_insert = to_insert.replace(/{WIDTH}/g,width);
          to_insert = to_insert.replace(/{SANDBAGHEIGHT}/g,settings.sandbagLeftHeight);

          if (!this.cclastid) {
              $(this).prepend(to_insert);
          } else {
              $('#'+this.cclastid).after(to_insert);
          }

          this.cclastid = nid;

          if (el_height == 0) {
              el_height = $('#'+nid).height();
          }

          this.ccleftwidth = width;
          this.ccleftheight = this.ccleftheight + el_height;

      }

      

      var right_sandbags = $('.sandbag-right',$(this));
      var left_sandbags = $('.sandbag-left',$(this));

      $('.align-bottom-right', $(this)).each(function(){
          var pos = $(this).position();
          
          //figure out the triangles....
          var total_height_of_triangle = ((settings.rightStart/settings.rightStep) * settings.sandbagRightHeight) - (settings.sandbagRightHeight/2);

          var middle_of_element = pos.top + $(this).height();

          var adjacent = total_height_of_triangle - middle_of_element; //b2

          var opposite = adjacent * Math.tan((12)*(Math.PI/180));

          var pos_from_right = Math.floor(opposite - settings.rightGutter);

          if ($.browser.msie && $.browser.version < 8) {

              $(this).after('<div style="height:'+$(this).height()+'px;"><!-- --></div>');

              var parent_width = $(this).parent().width();
              
              var wrapper = $('<div style="height:'+$(this).height()+'px;margin-right:'+pos_from_right+'px;width:'+(parent_width-pos_from_right)+'px;position:absolute;left:0px;top:'+pos.top+'px;"></div>');
              
              $(this).wrap(wrapper);

              $(this).css({'width':(parent_width-pos_from_right)+'px'});
                
          } else {
              $(this).css({'margin-right':pos_from_right+'px'});
          }

      });


      $('.align-top-right', $(this)).each(function(){
          var pos = $(this).position();

          //figure out the triangles....
          var total_height_of_triangle = ((settings.rightStart/settings.rightStep) * settings.sandbagRightHeight) - (settings.sandbagRightHeight/2);

          var middle_of_element = pos.top;

          var adjacent = total_height_of_triangle - middle_of_element; //b2

          var opposite = adjacent * Math.tan((12)*(Math.PI/180));

          var pos_from_right = Math.floor(opposite - settings.rightGutter);

          if ($.browser.msie && $.browser.version < 8) {

              $(this).after('<div style="height:'+$(this).height()+'px;"><!-- --></div>');

              var parent_width = $(this).parent().width();

              var wrapper = $('<div style="height:'+$(this).height()+'px;margin-right:'+pos_from_right+'px;width:'+(parent_width-pos_from_right)+'px;position:absolute;left:0px;top:'+pos.top+'px;"></div>');

              $(this).wrap(wrapper);

              $(this).css({'width':(parent_width-pos_from_right)+'px'});

          } else {
              $(this).css({'margin-right':pos_from_right+'px'});
          }


      });

      $('.align-right', $(this)).each(function(){
          var pos = $(this).position();

          //figure out the triangles....
          var total_height_of_triangle = ((settings.rightStart/settings.rightStep) * settings.sandbagRightHeight) - (settings.sandbagRightHeight/2);

          var middle_of_element = pos.top + ($(this).height()/2);

          var adjacent = total_height_of_triangle - middle_of_element; //b2

          var opposite = adjacent * Math.tan((12)*(Math.PI/180));

          var pos_from_right = Math.floor(opposite - settings.rightGutter);

          if ($.browser.msie && $.browser.version < 8) {

              $(this).after('<div style="height:'+$(this).height()+'px;"><!-- --></div>');

              var parent_width = $(this).parent().width();

              var wrapper = $('<div style="height:'+$(this).height()+'px;margin-right:'+pos_from_right+'px;width:'+(parent_width-pos_from_right)+'px;position:absolute;left:0px;top:'+pos.top+'px;"></div>');

              $(this).wrap(wrapper);

              $(this).css({'width':(parent_width-pos_from_right)+'px'});

          } else {
              $(this).css({'margin-right':pos_from_right+'px'});
          }


      });

     

      $('.align-left', $(this)).each(function(){
          var pos = $(this).position();
          var parent_width = $(this).parent().width();

          var gutter = settings.leftGutter;

          var el_to_get = Math.ceil(pos.top / el_height);
          var r_el_to_get_width = (right_sandbags.length > el_to_get) ? $(right_sandbags[el_to_get]).width() : 0;
          var l_el_to_get_width = (left_sandbags.length > el_to_get) ? $(left_sandbags[el_to_get]).width() : 0;

          var left_edge = (pos.left)? pos.left : l_el_to_get_width;

          var push_amt = parent_width - left_edge - (l_el_to_get_width - gutter);
          

          $(this).css({'position':'relative', 'left':push_amt+'px','top':Math.floor(pos.top)+'px'});


      });

     

      settings.onComplete(this);

    });

  };
})( jQuery );
