<? global $config, $user;?>
<? if ( count( $this -> sites_to_confirm ) ):?>
  <div class="row">
    <div class="col-12">
      <div class="panel panel-error panel-border top">
        <div class="panel-heading">
          <span class="panel-title">Niepotwierdzone strony</span>
        </div>
        <div class="panel-body">
          <? foreach ( $this -> sites_to_confirm as $site ):?>
            <a href="/ranker/main_view/id=<?= $site['id'];?>"><?= $site['name'];?></a><? if ( $site != end( $this -> sites_to_confirm ) ):?> | <? endif;?>
          <? endforeach;?>
        </div>
      </div>
    </div>
  </div>
<? endif;?>
<div class="row">
  <div class="col-xs-12 col-md-8">
    <div class="panel panel-success panel-border top">
      <div class="panel-heading">
        <span class="panel-title">Informacje: <a href="http://<?= $this -> site['url'];?>" target="_blank" class="text-primary"><?= $this -> site['url'];?></a></span>
      </div>
      <div class="panel-body">
        <div class="mb10">
          <?= \Html::button(
                      array(
                        'class' => 'btn-sm btn-default',
                        'title' => 'Poprzednia strona',
                        'url'   => '/ranker/main_view/id=' . $this -> prev_site_id,
                        'icon'  => 'fa-backward'
                      )
                  );?>
          <?= \Html::button(
                      array(
                        'class' => 'btn-sm btn-default',
                        'title' => 'Następna strona',
                        'url'   => '/ranker/main_view/id=' . $this -> next_site_id,
                        'icon'  => 'fa-forward'
                      )
                  );?>
          <?= \Html::button(
                      array(
                        'class' => 'btn-sm btn-default',
                        'title' => 'Dodaj stronę',
                        'url'   => '/ranker/site_edit/',
                        'icon'  => 'fa-plus'
                      )
                  );?>
          <?= \Html::button(
                      array(
                        'class' => 'btn-sm btn-default',
                        'title' => 'Edytuj stronę',
                        'url'   => '/ranker/site_edit/id=' . $this -> site['id'],
                        'icon'  => 'fa-cog'
                      )
                  );?>
          <?= \Html::button(
                      array(
                        'class' => 'btn-sm btn-default site-delete',
                        'title' => 'Usuń stronę',
                        'icon'  => 'fa-trash'
                      )
                  );?>
          <? if ( $this -> site['date_confirm'] < date( 'Y-m-d' ) and $this -> site['need_confirm'] ):?>
            <?= \Html::button(
                        array(
                          'class' => 'btn-sm btn-success site-confirm',
                          'title' => 'Potwierdź wyniki',
                          'icon'  => 'fa-check',
                          'attr'  => [ 'site-id' => $this -> site['id'] ]
                        )
                    );?>
          <? endif;?>
          <select name="page" class="form-control ranker-select" id="page" onChange="var id = $(this).val(); document.location.href='/ranker/main_view/id=' + id;" style='max-width: 250px;'>
            <?
            if ( is_array ( $this -> sites ) ) foreach ( $this -> sites as $site )
            {
              if ( $this -> site['id'] == $site['id'] )
                $name = $site['name'];
              ?>
                <option value="<?= $site['id'];?>" <? if ( $this -> site['id'] == $site['id'] ) echo 'selected="selected"';?>>
                  <?= $site['name'];?>
                </option>
              <?
            }
            ?>
          </select>
          <? if ( $this -> site['subscription'] > 0 ) echo 'Ab: <b>' . \S::number( $this -> site['subscription'] ) . ' zł</b>';?>
        </div>
        <div>
          <? if ( $this -> site['majestic'] ):?>
              TF: <a href="#" class="chart" type="tf" site-id="<?= $this -> site['id'];?>" site-url="<?= $this -> site['url'];?>"><?= $this -> majestic['tf'];?></a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
              CF: <a href="#" class="chart" type="cf" site-id="<?= $this -> site['id'];?>" site-url="<?= $this -> site['url'];?>"><?= $this -> majestic['cf'];?></a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
              BL: <a href="#" class="chart" type="bl" site-id="<?= $this -> site['id'];?>" site-url="<?= $this -> site['url'];?>"><?= $this -> majestic['feb'];?></a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
              RD: <a href="#" class="chart" type="rd" site-id="<?= $this -> site['id'];?>" site-url="<?= $this -> site['url'];?>"><?= $this -> majestic['rd'];?></a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
          <? endif;?>
          <? if ( $this -> site['semstorm'] ):?>
              Top3: <a href="#" class="chart" type="top3" site-id="<?= $this -> site['id'];?>" site-url="<?= $this -> site['url'];?>"><?= $this -> semstorm['top3'];?></a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
              Top10: <a href="#" class="chart" type="top10" site-id="<?= $this -> site['id'];?>" site-url="<?= $this -> site['url'];?>"><?= $this -> semstorm['top10'];?></a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
              Top50: <a href="#" class="chart" type="top50" site-id="<?= $this -> site['id'];?>" site-url="<?= $this -> site['url'];?>"><?= $this -> semstorm['top50'];?></a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
          <? endif;?>
          <?= \factory\Ranker::last_login_client( $this -> site['id'] );?> | Liczba fraz: <b><?= count( $this -> phrases );?></b>
        </div>
      </div>
    </div>
  </div>
  <div class="col-xs-12 col-md-4">
    <div class="panel panel-success panel-border top">
      <div class="panel-heading">
        <span class="panel-title">Zarobki</span>
      </div>
      <div class="panel-body">
        <div class="mb10">Dzisiaj (netto): <span id="day-profit" class="bold"><?= $this -> day_profit;?></span> <a href="#" id="refresh-earnings" class="btn btn-primary btn-xs ml10"><i class="fa fa-refresh"></i></a></div>
        <div>Netto ogółem: <span id="month-profit" class="bold"><?= $this -> month_profit;?></span></div>
      </div>
    </div>
  </div>
</div>
<div class="panel panel-primary panel-border top mbn">
  <div class="panel-heading">
    <span class="panel-title">Lista fraz</span>
    <div class="pull-right">
       <a href="/ranker/main_view/id=<?= $this -> site['id'];?>&year=<?= date( 'Y', strtotime( '-1 months', strtotime( $this -> year . '-' . $this -> month . '-01' ) ) );?>&month=<?= date( 'm', strtotime( '-1 months', strtotime( $this -> year . '-' . $this -> month . '-01' ) ) );?>" class="btn btn-sm btn-default" title="Poprzedni m-c">
        <i class="fa fa-backward"></i>
      </a>
      <a href="/ranker/main_view/id=<?= $this -> site['id'];?>&year=<?= date( 'Y', strtotime( '+1 months', strtotime( $this -> year . '-' . $this -> month . '-01' ) ) );?>&month=<?= date( 'm', strtotime( '+1 months', strtotime( $this -> year . '-' . $this -> month . '-01' ) ) );?>" class="btn btn-sm btn-default" title="Następny m-c">
        <i class="fa fa-forward"></i>
      </a>
      <select name="month_global" class="form-control ranker-select" id="month_global" onChange="document.location.href='/ranker/main_view/id=<?= $this -> site['id'];?>&year=' + $( '#year_global' ).val() + '&month=' + $( this ).val();">
        <option value="01" <? if ( $this -> month == '01' ) echo 'selected="selected"'; ?>>Styczeń</option>
        <option value="02" <? if ( $this -> month == '02' ) echo 'selected="selected"'; ?>>Luty</option>
        <option value="03" <? if ( $this -> month == '03' ) echo 'selected="selected"'; ?>>Marzec</option>
        <option value="04" <? if ( $this -> month == '04' ) echo 'selected="selected"'; ?>>Kwiecień</option>
        <option value="05" <? if ( $this -> month == '05' ) echo 'selected="selected"'; ?>>Maj</option>
        <option value="06" <? if ( $this -> month == '06' ) echo 'selected="selected"'; ?>>Czerwiec</option>
        <option value="07" <? if ( $this -> month == '07' ) echo 'selected="selected"'; ?>>Lipiec</option>
        <option value="08" <? if ( $this -> month == '08' ) echo 'selected="selected"'; ?>>Sierpień</option>
        <option value="09" <? if ( $this -> month == '09' ) echo 'selected="selected"'; ?>>Wrzesień</option>
        <option value="10" <? if ( $this -> month == '10' ) echo 'selected="selected"'; ?>>Październik</option>
        <option value="11" <? if ( $this -> month == '11' ) echo 'selected="selected"'; ?>>Listopad</option>
        <option value="12" <? if ( $this -> month == '12' ) echo 'selected="selected"'; ?>>Grudzień</option>
      </select>
      <select name="year_global" id="year_global" class="form-control ranker-select" onChange="document.location.href='/ranker/main_view/id=<?= $this -> site['id'];?>&year=' + $( this ).val() + '&month=' + $( '#month_global' ).val();">
        <? for ( $i = date( 'Y') - 2; $i <= date( 'Y') + 2; $i++ ):?>
          <option value="<?= $i;?>" <? if ( $i == $this -> year ) echo 'selected="selected"'; ?>><?=$i;?></option>
        <? endfor;?>
      </select>
    </div>
  </div>
</div>
<div class="positions">
  <div class="left-column">
    <div class="row mn">
      <div class="col-xs-12 phrase-info">
        <?= \Html::button(
                    array(
                      'class' => 'btn-xs btn-success',
                      'title' => 'Dodaj frazy',
                      'url'   => '/ranker/phrase_edit/site-id=' . $this -> site['id'],
                      'icon'  => 'fa-plus mr5',
                      'text'  => 'Dodaj frazy'
                    )
                );?>
          <?= \Html::button(
                      array(
                        'class' => 'btn-xs btn-danger site-refresh',
                        'title' => 'Odśwież wszystkie pozycje',
                        'icon'  => 'fa-refresh mr5',
                        'attr'  => [ 'site-id' => $this -> site['id'] ],
                        'text'  => 'Odśwież'
                      )
                  );?>
      </div>
    </div>
    <? if ( is_array( $this -> phrases ) and count( $this -> phrases ) <= 200 ): foreach ( $this -> phrases as $phrase ):?>
      <?
        $phrase_class = '';

        if ( new DateTime( $phrase['date_end'] ) < new DateTime( date( 'Y-m-d' ) ) or new DateTime( $this -> site['date_end'] ) < new DateTime( date( 'Y-m-d' ) ) )
          $phrase_class = 'text-danger';

        if ( $phrase['date_start'] and new DateTime( $phrase['date_start'] ) > new DateTime( date( 'Y-m-d' ) ) )
          $phrase_class = 'text-danger';

        $pos = $phrase['positions'][ date( 'Y-m-d' ) ]['position'];

        if ( $pos <= 10 )
          $start = 0;
        else
        {
          $start = 10 * floor( $pos / 10 );
          if ( $pos%10 == 0 )
            $start = $start - 10;
        }
      ?>
      <div class="row mn">
        <div class="col-xs-12 phrase-info phrase-info-<?= $phrase['id'];?>">
          <a href="http://www.google.pl/search?q=<?= urlencode( $phrase['phrase'] );?>&num=10&ie=utf8&hl=pl&start=<?= $start;?>" target="_blank" title="<?= $phrase['phrase'];?>" class="phrase <?= $phrase_class;?>">
            <?= $phrase['phrase'];?>
          </a>
          <a href="<?= $phrase['last_url'];?>" class="text-muted phrase-url" id="phrase-url-<?= $phrase['id'];?>" target="_blank" title="<?= $phrase['last_url'];?>">
            <?= $phrase['last_url'];?>
          </a>
          <div class="phrase-options">
            <? if ( $phrase['localization'] ):?><i class="fa fa-map-marker"></i><? endif;?>
            <a href="#" class="btn phrase-refresh" site-id="<?= $this -> site['id'];?>" phrase-id="<?= $phrase['id'];?>" title="Wymuś ponowne sprawdzenie pozycji">
              <i class="fa fa-refresh"></i>
            </a>
            <a href="/ranker/phrase_edit/phrase-id=<?= $phrase['id'];?>&site-id=<?= $this -> site['id'];?>" class="btn" title="Edytuj wybraną frazę">
              <i class="fa fa-cog"></i>
            </a>
            <a href="#" class="btn phrase-delete" site-id="<?= $this -> site['id'];?>" phrase-id="<?= $phrase['id'];?>" title="Usuń wybraną frazę">
              <i class="fa fa-trash"></i>
            </a>
            <a href="/ranker/phrase_costs_edit/phrase-id=<?= $phrase['id'];?>&site-id=<?= $this -> site['id'];?>" class="btn" title="Płatności za frazę">
              <i class="fa fa-dollar"></i>
            </a>
          </div>
        </div>
      </div>
    <? endforeach; endif;?>
  </div>
  <div class="right-column">
    <div class="table-responsive">
      <?
        $start  = date( 'Y-m-d', mktime( 0, 0, 0, $this -> month, 1, $this -> year ) );
        $days   = date( 't', strtotime( $start ) );
      ?>
      <table class="table table-bordered table-striped table-condensed">
        <thead>
          <tr>
            <th class="text-center text-muted" site-id="<?= $this -> site['id'];?>" date="<?= date( 'Y-m-t', strtotime( '-1 month', strtotime( $this -> year . '-' . $this -> month ) ) );?>">
              <?= date( 't', strtotime( '-1 month', strtotime( $this -> year . '-' . $this -> month ) ) );?>
            </th>
            <? for ( $i = 1; $i <= $days; $i++ ):?>
              <th class="text-center pointer table-date <? if ( $this -> comments[ date( 'Y-m-d', strtotime( $this -> year . '-' . $this -> month . '-' . $i ) ) ] ) echo "event-exists";?>" site-id="<?= $this -> site['id'];?>" date="<?= date( 'Y-m-d', strtotime( $this -> year . '-' . $this -> month . '-' . $i ) );?>">
                <?= $i;?>
              </th>
            <? endfor;?>
          </tr>
        </thead>
        <tbody>
          <? if ( is_array( $this -> phrases ) and count( $this -> phrases ) <= 200 ):?>
            <? foreach ( $this -> phrases as $phrase ):?>
              <tr>
                <?
                  $date_tmp = date( 'Y-m-t', strtotime( '-1 month', strtotime( $this -> year . '-' . $this -> month ) ) );

                  $pos = $phrase['positions'][ $date_tmp ]['position'];
                  $map = $phrase['positions'][ $date_tmp ]['map'];
                  $url = $phrase['positions'][ $date_tmp ]['url'];

                  $class  = 'position';
                  $text   = '';
                  $end    = '';

                  if ( $pos == 1 )
                    $class = 'pos_1';
                  if ( $pos == 2 || $pos == 3 )
                    $class = 'pos_2';
                  if ( $pos >= 4 && $pos <= 6 )
                    $class = 'pos_4';
                  if ( $pos >= 7 && $pos <= 10 )
                    $class = 'pos_7';
                  if ( $pos >= 11 && $pos <= 20 )
                    $class = 'pos_11';
                  if ( $pos == 0 || $pos >= 21 )
                    $class = 'pos_21';

                  if ( new DateTime( $phrase['date_end'] ) < new DateTime( date( 'Y-m-d' ) ) or new DateTime( $this -> site['date_end'] ) < new DateTime( date( 'Y-m-d' ) ) )
                    $class = 'end position';

                  if ( $phrase['date_start'] and new DateTime( $phrase['date_start'] ) > new DateTime( date( 'Y-m-d' ) ) )
                    $class = 'end position';

                  if ( $pos != '' )
                    $pos = $pos;
                  else
                    $pos = '-';
                ?>
                <td class="position text-center small <?= $class;?>" id="<?= $phrase['id'] . '-' .  $date_tmp;?>" phrase-id="<?= $phrase['id'];?>" date="<?= $date_tmp;?>" title="<?= $url;?>">
                  <span><?= $pos == '' ? '-' : $pos;?></span>
                </td>
              <? for ( $i = 1; $i <= $days; $i++ ):
                  $i < 10 ? $d = '0' . $i : $d = $i;

                  $pos = $phrase['positions'][ $this -> year . '-' . $this -> month . '-' . $d ]['position'];
                  $map = $phrase['positions'][ $this -> year . '-' . $this -> month . '-' . $d ]['map'];
                  $url = $phrase['positions'][ $this -> year . '-' . $this -> month . '-' . $d ]['url'];

                  $class  = 'position';
                  $text   = '';
                  $end    = '';

                  if ( $pos == 1 )
                    $class = 'pos_1';
                  if ( $pos == 2 || $pos == 3 )
                    $class = 'pos_2';
                  if ( $pos >= 4 && $pos <= 6 )
                    $class = 'pos_4';
                  if ( $pos >= 7 && $pos <= 10 )
                    $class = 'pos_7';
                  if ( $pos >= 11 && $pos <= 20 )
                    $class = 'pos_11';
                  if ( $pos == 0 || $pos >= 21 )
                    $class = 'pos_21';

                  if ( new DateTime( $phrase['date_end'] ) < new DateTime( date( 'Y-m-d' ) ) or new DateTime( $this -> site['date_end'] ) < new DateTime( date( 'Y-m-d' ) ) )
                    $class = 'end position';

                  if ( $phrase['date_start'] and new DateTime( $phrase['date_start'] ) > new DateTime( date( 'Y-m-d' ) ) )
                    $class = 'end position';
                  ?>
                  <td class="position text-center small <? if ( $pos != '' ):?>pointer<? endif;?> <?= $class;?>" id="<?= $phrase['id'] . '-' .  $this -> year . '-' . $this -> month . '-' . $d;?>" phrase="<?= $phrase['id'];?>" date="<?= $this -> year . '-' . $this -> month . '-' . $d;?>" title="<?= $url;?>">
                    <span>
                      <?
                        if ( $pos != '' ) {
                          echo $pos;
                        }
                        else {
                          if ( $phrase['days_offset'] and date( 'Y-m-d', strtotime( '+' . $phrase['days_offset'] . 'days', strtotime( $phrase['last_checked'] ) ) ) != date( 'Y-m-d' ) ) {
                            echo '-';
                          }
                          else
                          {
                            if ( $pos == '' and $this -> year . '-' . $this -> month . '-' . $d == date( 'Y-m-d' ) and $class != 'end position' ) {
                              echo '<i class="fa fa-refresh spin"></i>';
                              ?><script type="text/javascript">
                                $( function() {
                                   ajax_check_phrase_position( <?= $phrase['id'];?> );
                                });
                              </script><?
                            }
                          }
                        }
                      ?>
                    </span>
                    <input type="text" class="position-edit" value="<?= $pos;?>">
                  </td>
                <? endfor;?>
              </tr>
            <? endforeach;?>
          <? endif;?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- komentarz dzienny -->
<div id="comment-info">
  <form method="POST" action="#" class="form-horizontal">
    <input type="hidden" id="comment-date" value="">
    <input type="hidden" id="comment-site-id" value="">
    <div class="row">
      <div class="col col-xs-12">
        <div class="form-group ">
          <div class="col-lg-12">
            <textarea class="comment form-control" name="comment-text" id="comment-text" rows="6"></textarea>
          </div>
        </div>
        <div class="form-group">
          <div class="col-xs-12 text-left">
            <?= \Html::button(
                        array(
                          'class' => 'btn btn-sm btn-success',
                          'text'  => 'Zatwierdź',
                          'js'    => '',
                          'icon'  => 'fa-check-circle mr5'
                        )
                    );?>
            <?= \Html::button(
                        array(
                          'class' => 'btn btn-sm btn-dark',
                          'text'  => 'Zamknij',
                          'js'    => '$( "#overlay" ).hide(); $( "#comment-info" ).hide();',
                          'icon'  => 'fa-times mr5'
                        )
                    );?>
            <?= \Html::button(
                        array(
                          'class' => 'btn btn-sm btn-danger pull-right',
                          'text'  => 'Usun',
                          'js'    => '',
                          'icon'  => 'fa-trash mr5'
                        )
                    );?>
          </div>
        </div>
      </div>
    </div>
  </form>
</div>

<!-- komentarz -->
<? if ( $this -> site['comments'] ):?>
  <div class="panel panel-danger panel-border top">
    <div class="panel-body">
      <?= $this -> site['comments'];?>
    </div>
  </div>
<? endif;?>

<!-- stawki -->
<? if ( is_array( $this -> phrases ) ):?>
  <div class="row">
    <?
      $suma = 0;
      foreach ( $this -> phrases as $phrase )
      {
        $discount = '';

        if ( $this -> site['discount'] )
          $discount = $this -> site['discount'];

        if ( $phrase['discount'] )
          $discount = $phrase['discount'];

        if ( is_array( $phrase['prices'] ) )
        {
          ?>
          <div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">
            <div class="panel panel-primary">
              <div class="panel-heading small"><?= $phrase['phrase'];?> <? if ( $discount > 0 ):?><span class="fr">(rabat <?= $discount;?>%)</span><? endif;?></div>
              <div class="panel-body p0">
                <?
                  if ( is_array( $phrase['prices'] ) )
                  {
                    $sum = 0;
                    ?>
                    <table class="table table-condensed table-bordered table-striped">
                      <thead>
                        <tr>
                          <td class="text-right">Przedział</td>
                          <td class="text-right">Stawka</td>
                          <td class="text-right">Ilość dni</td>
                          <td class="text-right">Należność</td>
                        </tr>
                      </thead>
                      <tbody>
                        <?
                        foreach ( $phrase['prices'] as $price )
                        {
                          $price_c  = \S::number( $price['price'] - \S::number( $price['price'] * $discount / 100 ) );
                          ?>
                          <tr <? if ( !$price['count'] ):?> style="background: #efefef;"<? endif;?>>
                            <td class="text-right">
                              <?= $price['start'];?> - <?= $price['end'];?>
                            </td>
                            <td class="text-right">
                              <?= \S::number_display( $price_c );?>
                            </td>
                            <td class="text-right">
                              <?= $price['count'];?>
                            </td>
                            <td class="text-right">
                              <?= \S::number_display( $price_c * $price['count'] );?>
                            </td>
                          </tr>
                          <?
                          $sum  = $sum + $price_c * $price['count'];
                          $suma = $suma + $price_c * $price['count'];
                        }
                        ?>
                        <tr>
                          <td colspan="3" class="text-right">Suma:</td>
                          <td class="alert-dark dark text-right"><?= \S::number_display( $sum );?></td>
                        </tr>
                      </tbody>
                    </table>
                    <?
                  }
                ?>
              </div>
            </div>
          </div>
          <?
        }
      }
    ?>
  </div>
  <div class="row">
    <? if ( $suma ):?>
      <div class="col-md-3">
        <div class="panel panel-dark">
          <div class="panel-heading">
            Razem netto: <?= \S::number_display( $suma );?>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="panel panel-dark">
          <div class="panel-heading">
            Razem brutto: <?= \S::number_display( $suma * $config['profit']['vat'] );?>
          </div>
        </div>
      </div>
    <? endif;?>
  </div>
<? endif;?>

<div id="swl-content">
  <div class="content"></div>
</div>

<div id="chart"></div>

<link rel="stylesheet" type="text/css" href="/libraries/framework/vendor/plugins/c3charts/c3.min.css">
<script type="text/javascript" src="/libraries/framework/vendor/plugins/c3charts/d3.min.js"></script>
<script type="text/javascript" src="/libraries/framework/vendor/plugins/c3charts/c3.min.js"></script>
<script type="text/javascript" src="/libraries/jquery.bpopup.min.js"></script>
<script type="text/javascript" src="/libraries/framework/vendor/plugins/highcharts/highcharts-all.js"></script>
<script type="text/javascript">
  $( function()
  {
    var timer;

    Highcharts.setOptions(
    {
      lang: {
        loading: 'Ładowanie...',
        months: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
        weekdays: ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
        shortMonths: ['Sty', 'Lut', 'Mar', 'Kwi', 'Maj', 'Cze', 'Lip', 'Sie', 'Wrz', 'Paź','Lis', 'Gru'],
        exportButtonTitle: "Export",
        printButtonTitle: "Drukowanie",
        rangeSelectorFrom: "Od",
        rangeSelectorTo: "Do",
        rangeSelectorZoom: "Przybliżenie",
        downloadPNG: 'Pobierz obraz PNG',
        downloadJPEG: 'Pobierz obraz JPEG',
        downloadPDF: 'Pobierz dokument PDF',
        downloadSVG: 'Pobierz obraz SVG',
        thousandsSep: " ",
        decimalPoint: ','
      }
    });

    $( '#chart' ).appendTo( '#ajax-container' );
    var chart;
    var url;
    var title_text;
    var yaxis_title;

    $( 'body' ).on( 'click', '.chart', function()
    {
      var site_url  = $( this ).attr( 'site-url' );
      var site_id   = $( this ).attr( 'site-id' );
      var type      = $( this ).attr( 'type' );

      switch ( type )
      {
        case 'top3':
          url = "/json.php?action=site_top3&site_id=" + site_id;
          title_text  = 'Semstorm Top3: ';
          yaxis_title = 'Semstorm Top3';
        break;
        case 'top10':
          url = "/json.php?action=site_top10&site_id=" + site_id;
          title_text  = 'Semstorm Top10: ';
          yaxis_title = 'Semstorm Top10';
        break;
        case 'top50':
          url = "/json.php?action=site_top50&site_id=" + site_id;
          title_text  = 'Semstorm Top50: ';
          yaxis_title = 'Semstorm Top50';
        break;
        case 'bl':
          url         = "/json.php?action=site_feb&site_id=" + site_id;
          title_text  = 'Backlinks strony: ';
          yaxis_title = 'Backlinks';
        break;
        case 'rd':
          url         = "/json.php?action=site_rd&site_id=" + site_id;
          title_text  = 'Referring Domains strony: ';
          yaxis_title = 'Referring Domains';
        break;
        case 'cf':
          url         = "/json.php?action=site_cf&site_id=" + site_id;
          title_text  = 'Citation Flow strony: ';
          yaxis_title = 'Citation Flow';
        break;
        case 'tf':
          url         = "/json.php?action=site_tf&site_id=" + site_id;
          title_text  = 'Trust Flow strony: ';
          yaxis_title = 'Trust Flow';
        break;
      }

      $( '#ajax-container' ).css({
        'height': '600px',
        'width' : '90%'
      });

      $( '#chart' ).css({
        'width': '100%'
      });

      $( '#overlay, #ajax-container' ).show();

      $.getJSON( url, function( json )
      {
        chart = new Highcharts.Chart(
        {
          chart: {
            renderTo: 'chart',
            type: 'line',
            marginRight: 130,
            marginBottom: 25
          },
          title: {
            text: title_text + '<b>' + site_url + '</b>',
            x: -20
          },
          subtitle: {
            text: '',
            x: -20
          },
          xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: {
              day: '%Y-%m-%d'
            },
            title: {
              text: 'Data'
            }
          },
          yAxis: {
            title: {
                text: yaxis_title
            },
            plotLines: [{
              value: 0,
              width: 1,
              color: '#808080'
            }]
          },
          tooltip: {
            formatter: function() {
              return '' + Highcharts.dateFormat( "%Y-%m-%d", this.x ) + ':<br /><b>' + this.y + '</b>';
            }
          },
          series: json
        });
      });
      return false;
    });

    $( 'body' ).on( 'click', '#refresh-earnings', function()
    {
      var button = $( this );

      if ( button.attr( 'disabled' ) == 'disabled' )
        return false;

      jQuery.ajax(
      {
        type: 'POST',
        cache: false,
        url: '/ajax.php',
        data:
        {
          a: 'refresh-earnings'
        },
        beforeSend: function()
        {
          button.attr( 'disabled', 'disabled' );
        },
        success: function( response )
        {
          data = jQuery.parseJSON( response );
          $( '#day-profit' ).html( data.day_profit );
          $( '#month-profit' ).html( data.month_profit );
          button.removeAttr( 'disabled' );
        }
      });
    });

    $( 'body' ).on( 'dblclick', '.position', function()
    {
      var id = $( this ).attr( 'id' );
      $( 'td#' + id ).children( 'span' ).addClass( 'hide' );
      $( 'td#' + id ).children( 'input' ).show().focus().select();
    });

    $( 'body' ).on( 'focusout keypress', '.position-edit', function(event)
    {
      if ( event.type == 'keypress' && event.keyCode === 13 || event.type == 'focusout' )
      {
        var new_class = '';
        var input     = $( this );
        var date      = $( this ).parent( 'td' ).attr( 'date' );
        var position  = $( this ).val();
        var phrase_id = $( this ).parent( 'td' ).attr( 'phrase' );

        jQuery.ajax(
        {
          type: 'POST',
          cache: false,
          url: '/ajax.php',
          data:
          {
            date:       date,
            phrase_id:  phrase_id,
            position:   position,
            a:          'change_phrase_position'
          },
          beforeSend: function()
          {
            $( '#' + phrase_id + '-' + date ).removeClass( 'pos_1 pos_2 pos_4 pos_7 pos_11 pos_21' );
            $( '#' + phrase_id + '-' + date + ' span' ).html( '' );
          },
          success: function( data )
          {
            input.hide();
            input.parent( 'td' ).children( 'span' ).html( position ).removeClass( 'hide' );

            if ( position == 1 )
              new_class = 'pos_1';
            if ( position == 2 || position == 3 )
              new_class = 'pos_2';
            if ( position >= 4 && position <= 6 )
              new_class = 'pos_4';
            if ( position >= 7 && position <= 10 )
              new_class = 'pos_7';
            if ( position >= 11 && position <= 20 )
              new_class = 'pos_11';
            if ( position == 0 || position >= 21 )
              new_class = 'pos_21';

            $( '#' + phrase_id + '-' + date ).addClass( new_class );

            jQuery( '#overlay' ).hide();
          }
        });
      }
    });

    $( 'body' ).on( 'click', '.phrase-refresh', function()
    {
      var site_id   = $( this ).attr( 'site-id' );
      var phrase_id = $( this ).attr( 'phrase-id' );

      ajax_refresh_phrase_position( site_id, phrase_id );
      return false;
    });

    $( 'body' ).on( 'click', '.swl-stats', function()
    {
      var swl_id = $( this ).attr( 'swl-id' );

      $('#swl-content').bPopup(
      {
          content:'iframe',
          contentContainer:'.content',
          loadUrl:'http://www.projectpro.pl/swl/group_links/iframe=true&pswd=ec97fb1b23aac077cef7188f90e1a74b&link-id=' + swl_id
      });
    });

    $( 'body' ).on( 'dblclick', '.site-confirm', function()
    {
      $( this ).blur().addClass( 'disabled' );
      ajax_site_confirm( $( this ).attr( 'site-id' ), <?= $this -> next_site_id;?> );
    });

    /* odświeżenie wszystkich pozycji */
    $( 'body' ).on( 'click', '.site-refresh', function()
    {
      $.alert(
      {
        title: 'Potwierdź',
        content: 'Na pewno chcesz odświerzyć wszystkie pozycje?',
        type: 'orange',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        buttons:
        {
          confirm:
          {
            text: 'Zatwierdź',
            btnClass: 'btn-blue',
            keys: ['enter'],
            action: function()
            {
              $( '.positions .left-column .phrase-options .phrase-refresh' ).each( function()
              {
                $( this ).trigger( 'click' );
              });
            }
          },
          cancel:
          {
            text: 'Anuluj',
            action: function() {}
          }
        }
      });
    });

    $( 'body' ).on( 'click', '.site-delete', function()
    {
      $.alert(
      {
        title: 'Potwierdź',
        content: 'Na pewno chcesz usunąć wybraną stronę?',
        type: 'orange',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        buttons:
        {
          confirm:
          {
            text: 'Zatwierdź',
            btnClass: 'btn-blue',
            keys: ['enter'],
            action: function()
            {
              document.location.href = "/ranker/site_delete/site-id=<?= $this -> site['id'];?>";
            }
          },
          cancel:
          {
            text: 'Anuluj',
            action: function() {}
          }
        }
      });
    });

    $( 'body' ).on( 'click', '.phrase-delete', function()
    {
      var site_id   = $( this ).attr( 'site-id' );
      var phrase_id = $( this ).attr( 'phrase-id' );

      $.alert(
      {
        title: 'Potwierdź',
        content: 'Na pewno chcesz usunąć wybraną frazę?',
        type: 'orange',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        buttons:
        {
          confirm:
          {
            text: 'Zatwierdź',
            btnClass: 'btn-blue',
            keys: ['enter'],
            action: function()
            {
              document.location.href = '/ranker/phrase_delete/phrase-id=' + phrase_id + '&site-id=' + site_id;
            }
          },
          cancel:
          {
            text: 'Anuluj',
            action: function() {}
          }
        }
      });
    });

    $( 'body' ).on( 'click', '.table-date', function()
    {
      var date    = $( this ).attr( 'date' );
      var site_id = $( this ).attr( 'site-id' );

      jQuery.ajax(
      {
        type: 'POST',
        cache: false,
        url: '/ajax.php',
        data:
        {
          date:     date,
          site_id:  site_id,
          a:       'comment_details'
        },
        beforeSend: function()
        {
          $( '#overlay' ).show();
        },
        success: function( response )
        {
          $( '#comment-date' ).val( date );
          $( '#comment-site-id' ).val( site_id );
          $( '#comment-text' ).val( response );
          $( '#comment-info' ).show();
        }
      });
    });

    $( 'body' ).on( 'click', '#comment-info .btn-success', function()
    {
      var date    = $( '#comment-date' ).val();
      var site_id = $( '#comment-site-id' ).val();
      var comment = $( '#comment-text' ).val();

      jQuery.ajax(
      {
        type: 'POST',
        cache: false,
        url: '/ajax.php',
        data:
        {
          date:     date,
          site_id:  site_id,
          comment:  comment,
          a:       'comment_save'
        },
        beforeSend: function()
        {
        },
        success: function( response )
        {
          $( '#comment-info, #overlay' ).hide();
          $( 'th[date=' + date + ']' ).addClass( 'event-exists' );
        }
      });
    });

    $( 'body' ).on( 'click', '#comment-info .btn-danger', function()
    {
      var date    = $( '#comment-date' ).val();
      var site_id = $( '#comment-site-id' ).val();

      jQuery.ajax(
      {
        type: 'POST',
        cache: false,
        url: '/ajax.php',
        data:
        {
          date:     date,
          site_id:  site_id,
          a:       'comment_delete'
        },
        beforeSend: function()
        {
        },
        success: function( response )
        {
          $( '#comment-info, #overlay' ).hide();
          $( 'th[date=' + date + ']' ).removeClass( 'event-exists' );
        }
      });
    });
  });
</script>