$column-width: 56px !default;
$gutter-width: 18px !default;
$margin-width: 18px !default;
$columns: 16 !default;

$gridsystem-width: $columns * $column-width + ($columns - 1) * $gutter-width + 2 * $margin-width;

@mixin floatgrid($row-width: 4, $offset: 0, $by-index: true) {
  $gutter-width-relative: $gutter-width / $max-width-page * 100%;
  $row-split-width: round($row-width / 2);
  $row-split-width-factor: $row-width / $row-split-width;

  width: 100%;
  float: left;

  @media #{$screen-XXS} {
    width: ((100% / $row-width) * $row-split-width-factor) + (($gutter-width-relative / $row-width) * $row-split-width-factor) - $gutter-width-relative;
    margin-right: $gutter-width-relative;
    @if $by-index {
      &:nth-child(#{$row-split-width + $offset}n+#{$row-split-width + $offset}) {
        margin-right: 0;
      }
    } @else {
      &:nth-of-type(#{$row-split-width + $offset}n+#{$row-split-width + $offset}) {
        margin-right: 0;
      }
    }
  }

  @media #{$screen-S} {
    width: 100% / $row-width + ($gutter-width-relative / $row-width) - $gutter-width-relative;
    margin-right: $gutter-width-relative;
    @if $by-index {
      &:nth-child(#{$row-split-width + $offset}n+#{$row-split-width + $offset}) {
        margin-right: $gutter-width-relative;
      }
      &:nth-child(#{$row-width + $offset}n+#{$row-width + $offset}) {
        margin-right: 0;
      }
    } @else {
      &:nth-of-type(#{$row-split-width + $offset}n+#{$row-split-width + $offset}) {
        margin-right: $gutter-width-relative;
      }
      &:nth-of-type(#{$row-width + $offset}n+#{$row-width + $offset}) {
        margin-right: 0;
      }
    }
  }

  @media print {
    width: 100% !important;
    margin-right: 0 !important;
  }
}

@mixin gridwidth($x: 0, $offset: true) {
  @if $offset {
    width: 100% * (($column-width + $gutter-width) * $x - $gutter-width) / $gridsystem-width;
  }
  @else {
    width: 100% * (($column-width + $gutter-width) * $x + $gutter-width) / $gridsystem-width;
  }
}

@mixin gridposition($x: 0, $offset: true) {
  @if $offset {
    margin-left: 100% * (($column-width + $gutter-width) * $x - $gridsystem-width + $margin-width) / $gridsystem-width;
  }
  @else {
    margin-left: 100% * (($column-width + $gutter-width) * $x - $gridsystem-width) / $gridsystem-width;
  }
}

@for $x from 1 through $columns {
  div.width-#{$x} {
    @include gridwidth($x);
  }
}

@for $x from 0 through $columns - 1 {
  div.position-#{$x} {
    @include gridposition($x);
  }
}

@mixin cell {
  position: relative;
  float: left;
  left: 100%;

  @include print {
    float: none;
    position: static;
    left: 0;
    margin: 0 !important;
  }
}

@mixin row {
  @include clearfix();
  width: 100%;
  max-width: $max-width-page;
  margin: 0 auto;
  display: block;
  position: relative;
}

.row {
  @include row();
}

.cell {
  @include cell();
}

.width-full {
  @include gridwidth($columns);
}
