import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';

@Component({
  selector: 'my-app',
  moduleId: module.id,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name: string = 'Angular 2';
  locations: Array<string>;
  counties: Array<string>;
  addresses: Array<any>;
  sortState: number = -1;

  public rowInEdit: any;

  constructor(private _appService: AppService) { }

  ngOnInit() {
    this._appService.getData()
      .subscribe(data => {
        this.locations = data.Locations;
        this.addresses = data.Addresses;

        var n: any = [];
        for (var i = 0; i < data.Addresses.length; i++) {
          if (n.indexOf(data.Addresses[i].County) == -1) n.push(data.Addresses[i].County);
        }
        this.counties = n.sort();

        console.log(data);
      });
  }
  typed(item: any) {
    if (!this.addresses.find(addr => addr.ZipCode === item.Zip))
      item.Zip = undefined;
  }
  toggleExpandAll(expand: boolean) {
    this.locations.forEach((loc: any) => {
      loc.expanded = expand;
    });
  }
  
(evt: MouseEvent, row: any) {
    if (!this.rowInEdit && !row.editing) {
      let $btn = $('div.ui-iggrid-buttoncontainer');
      let $tr = $(evt.target).closest('tr');

      let position = $tr.offset();
      let left = $tr.width() - $btn.width() - 15;
      let top = $tr.height() + position.top;

      $btn.css({ 'left': left, 'top': top });

      row.editing = true;
      this.rowInEdit = row;
    }
  }
  onCloseRow() {
    if (this.rowInEdit) {
      this.rowInEdit.editing = false;
      this.rowInEdit = undefined;
    }
  }
  sortName() {
    this.sortState = this.sortState * -1;
    this.locations.sort((a: any, b: any) => {
      if (a.LocationName < b.LocationName) return this.sortState;
      if (a.LocationName > b.LocationName) return this.sortState * -1;
      return 0;
    });
  }
  sortMid() {
    this.sortState = this.sortState * -1;
    this.locations.sort((a: any, b: any) => {
      if (this.sortState > 0) return a.MID - b.MID;
      else return b.MID - a.MID;
    });
  }
}
onEditRow