var numUpdates = 0;
var labelStyle = {
    display: "block"
};
window.ChapterTable = React.createClass({
  getInitialState: function(){
    return{
      chapters: null,
      chapterJson: "",
      isLoading: false,
      isAdmin: false,
      numUpdates: 0,
      isEdge: window.navigator.userAgent.indexOf("Edge") > -1
    }
  },
  componentDidMount: function(){
      window.isOdd = true;
      var capture = this;
    $("#txtPacketName").focus();
    numUpdates = 0;
    $.post("AdminAjaxHandler.ashx?handler=IsAdmin", function (data) {
    }).done(function (data) {
        var isadmin = false;
        if (data == "True")
        {
            isadmin = true;
        }
        capture.setState({
            isAdmin: isadmin
        })
    });
  },
  componentWillMount: function(){
    this.getChapters();
  },
  componentWillReceiveProps: function(){
    this.getChapters();
  },
  componentWillUpdate: function(){
    window.isOdd = true;
  },
  componentDidUpdate: function(){
    numUpdates++;
    //console.log(numUpdates);
    if(numUpdates <= 2)
    $("#txtPacketName").focus();
  },
  getChapters: function(){
    var capture = this;
    if(window.programId != null){
      this.setState({
        isLoading: true,
        chapters: null
      })
      $.post("AdminAjaxHandler.ashx?handler=GetChapterList_json", {PROGRAM_ID: window.programId, RULE_PACKET_ID: window.rulePacketId }, function (data) {
          }).done(function(data){
            var parsed = JSON.parse(data);
              capture.setState({
                isEven: false,
                chapters: parsed.chapters,
                chaptersJson: JSON.stringify(parsed.chapters),
                readOnly: parsed.readOnly,
                isLoading: false
              })
              //console.log(parsed);
              capture.forceJsonUpdate();
          });
    }
  },
  getNewChapter: function(){
    var capture = this;
    $.post("AdminAjaxHandler.ashx?handler=GetNewChapter_json", {}, function (data) {
        data = JSON.parse(data);
        var json = JSON.stringify(capture.state.chapters.concat(data));
        var chapters = capture.state.chapters.concat(data);
        capture.setState({
          chapters: chapters,
          chapterJson: json
        })
    });
  },
  updateChapterObject: function(chapterId, guid, property, value){
    var chapters = this.state.chapters.filter(function(chapter){
      if(chapter.id == chapterId){
        if(chapter.id > 0){
          chapter[property] = value;
        }else{
          if(chapter.guid == guid){
            chapter[property] = value;
          }
        }
      }
      return chapter;
    })
    this.setState({
      chapters: chapters,
      chapterJson: JSON.stringify(chapters)
    })
  },
  getRowClass: function(){
    if(window.isOdd){
      window.isOdd = false;
      return "chapter-row-odd"
    }else{
      window.isOdd = true;
      return "chapter-row-even"
    }
  },
  forceJsonUpdate: function(){
    //This function does nothing but force the hidden input to update its json. It's stupid and hacky but it's too late to care.
    this.updateChapterObject("%", "%", "%", "%");
  },
  handleChange: function(){

  },
  attachTooltips: function(){
    $("[rel='tooltip']").tooltip();
  },
  render: function(){
      var capture = this;
    return(
      <div id="packets_chapters">
        <div className="panel panel-primary chapter-table">
           <div className="panel-heading">Chapters
             {window.programId != 0 && !this.props.readOnly && !capture.state.isAdmin && this.props.packetType != "final" && this.props.packetType != "nonsubstantive"?
               <a onClick={this.getNewChapter} role="button" id="btnNewCom" className="btn btn-default btn-xs btn-packagenew btn-icon button-no-text">
                <label className="glyphicon glyphicon-plus"></label>New Chapter
               </a>
               :
               null
             }

           </div>
           <div className="panel-body table-responsive panel-table modal-table">
           {
             this.state.isLoading ?
                <div className="chapter-loading-indicator animated fadeIn extra-fast-animation"></div>
                :
                null
           }
              <table id="chapters_proposed" className="table table-striped table-bordered table-condensed">
                 <thead>
                    <tr id="ctl00_tblChapters_HeaderRow" className="bg-info">
                       <th width="10" scope="column"></th>
                       <th width="100" scope="column">Chapter No.</th>
                       <th scope="column">Chapter Name</th>
                       <th width="100" scope="column">Action</th>
                       {this.props.renderPervasive ?
                         <th scope="column">Pervasive</th>
                         :
                         null
                       }
                       <th width="500" scope="column">
                          {this.props.uploadHeaderTitle}
                          <span className="glyphicon glyphicon-question-sign upload-header-info" rel="tooltip" data-tooltip-title={this.props.uploadRowLabel} title={this.props.uploadRowLabel} data-toggle="tooltip" data-placement="right"></span>
                       </th>
                    </tr>
                 </thead>
                 <tbody>
                  {this.state.chapters != null ?
                    this.state.chapters.map(function(chapter, i){
                      return <ChapterRow
                        updateChapterObject={capture.updateChapterObject}
                        rule_id={chapter.rule_id}
                        guid={chapter.guid}
                        uploadRowLabel={capture.props.uploadRowLabel}
                        name={chapter.name}
                        amendedChapterName={chapter.amendedChapterName}
                        num={chapter.num}
                        id={chapter.id}
                        checked_yn={chapter.checked_yn}
                        pervasive={chapter.pervasive_yn}
                        action={chapter.action_id}
                        rowClass={capture.getRowClass()}
                        readOnly={capture.props.readOnly ? capture.props.readOnly : chapter.readOnly}
                        readOnlyRepealed={chapter.readOnlyRepealed}
                        href={chapter.href}
                        fileName ={chapter.file_name}
                        renderPervasive={capture.props.renderPervasive}
                        packetType={capture.props.packetType}
                        isEdge={capture.state.isEdge}
                        key={i}/>
                    })
                    :
                    null
                  }
                 </tbody>
              </table>
           </div>
        </div>
        <input type="text" name="chapters_json" id="chapters_json" value={this.state.chapterJson} onChange={this.handleChange}/>
        {this.attachTooltips()}
      </div>
    )
  }
})

var ChapterRow = React.createClass({
  getInitialState: function(){
    return{
      isChecked: false,
      repealChecked: false,
      supercedeChecked: false,
      pervasiveChecked: false,
      enactChecked: false,
      replaceChecked: false,
      helperMessage: "Upload Strike/Underscore Copy (Docx Only)",
      name: null,
      amendedChapterName: null,
      num: null,
      href: null,
      fileName: null,
      uploadVal: "",
      action: null,
      isUploading: false
    }
  },
  componentWillMount: function(){
    this.setState({
      isChecked: this.props.checked_yn,
      pervasiveChecked: this.props.pervasive,
      name: this.props.name,
      num: this.props.num,
      action: this.props.action,
      href: "../DownloadFile.aspx?" + this.props.href,
      fileName: this.props.fileName,
      amendedChapterName: this.props.amendedChapterName
    })
    switch(this.props.action.toLowerCase()){
      case "repeal":
        this.setState({
          repealChecked: true,
          supercedeChecked: false
        })
        break;
      case "supercede":
        this.setState({
          repealChecked: false,
          supercedeChecked: true
        })
      break;
      case "new":
        this.setState({
          repealChecked: false,
          supercedeChecked: true
        })
      break;
      case "enact":
        this.setState({
          repealChecked: false,
          supercedeChecked: false,
          enactChecked: false,
          pervasiveChecked: true
        })
      break;
      case "replace":
        this.setState({
            repealChecked: false,
            supercedeChecked: false,
            replaceChecked: false,
        })
      break;
    }
    if(this.props.checked_yn && this.props.packetType == "emergency"){
      this.setState({
        enactChecked: true,
        supercedeChecked: true,
        pervasiveChecked: true
      })
    }
    if (this.props.checked_yn && this.props.packetType == "nonsubstantive") {
      this.setState({
          replaceChecked: true,
          supercedeChecked: true,
          pervasiveChecked: true
      })
    }
  },
  componentDidMount: function(){
  if(this.props.action == "new" && this.props.rule_id == 0){
    this.refs.numInput.focus()
  }
},
  toggleChaptercheck: function(){
    if(this.state.isChecked ){
      this.setState({
        isChecked: false,
        enactChecked: false,
        replaceChecked: false
      })
      if(this.props.packetType == "emergency" || this.props.packetType == "nonsubstantive"){
        this.setState({
          supercedeChecked: false
        })
      }
      this.props.updateChapterObject(this.props.id, this.props.guid, "checked_yn" , false);
    }else{
      this.setState({
        isChecked: true,
        enactChecked: true, 
        replaceChecked: true, 
      })
      if(this.props.packetType == "emergency" || this.props.packetType == "nonsubstantive"){
        this.setState({
          supercedeChecked: true
        })
      }
      this.props.updateChapterObject(this.props.id, this.props.guid, "checked_yn" , true);
    }
  },
  checkRadio: function(e){
    switch(e.target.value.toLowerCase()){
      case "repeal":
        this.setState({
          repealChecked: true,
          supercedeChecked: false,
          pervasiveChecked: false
        })
        this.props.updateChapterObject(this.props.id, this.props.guid, "action_id" , "Repeal");
        this.props.updateChapterObject(this.props.id, this.props.guid, "pervasive_yn" , false);
        break;
      case "supercede":
        this.setState({
          repealChecked: false,
          supercedeChecked: true
        })
        this.props.updateChapterObject(this.props.id, this.props.guid, "action_id" , "Supercede");
        break;
      case "enact":
        this.setState({
          repealChecked: false,
          supercedeChecked: true,
          enactChecked: true
        })
        this.props.updateChapterObject(this.props.id, this.props.guid, "action_id" , "Enact");
      break;
      case "replace":
        this.setState({
            repealChecked: false,
            supercedeChecked: true,
            replaceChecked: true
        })
        this.props.updateChapterObject(this.props.id, this.props.guid, "action_id", "Replace");
      break;
    }
  },
  togglePervasive: function(){
    if(this.state.pervasiveChecked ){
      this.setState({
        pervasiveChecked: false,
      })
      this.props.updateChapterObject(this.props.id, this.props.guid, "pervasive_yn" , false);
    }else{
      this.setState({
        pervasiveChecked: true
      })
      this.props.updateChapterObject(this.props.id, this.props.guid, "pervasive_yn" , true);
    }
  },
  updateNumber: function (e) {
    var nonNumericRegex = /[^0-9.]+/g;
    //console.log(e.target.value.replace(nonNumericRegex, ""));
    this.setState({ num: e.target.value.replace(nonNumericRegex, "") });
    this.props.updateChapterObject(this.props.id, this.props.guid, "num", e.target.value.replace(nonNumericRegex, ""));
  },
  updateName: function(e){
    this.setState({
     amendedChapterName: e.target.value
    })
      this.props.updateChapterObject(this.props.id, this.props.guid, "amendedChapterName" , e.target.value);
  },
  updateNewName: function (e) {
    this.setState({
        name: e.target.value
    })
    this.props.updateChapterObject(this.props.id, this.props.guid, "name", e.target.value);
  },
  validateFileType: function(e){
    var _validFileExtensions = [".docx"];
    var sFileName = e.target.value;
    var capture = this;
    this.setState({
      isUploading: true
    })
    if (sFileName.length > 0) {
        var blnValid = false;
        for (var j = 0; j < _validFileExtensions.length; j++) {
            var sCurExtension = _validFileExtensions[j];
            if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                blnValid = true;
                break;
            }
        }

        if (!blnValid) {
            this.setState({
              helperMessage: "That file isn't a Word(.docx) document. Try again.",
              uploadVal: "",
              isUploading: false
            })
            alert("That file isn't a Word(.docx) document. Try again.");
            return false;
        }else{
          var file = e.target.files;
          // Create a formdata object and add the files
          var data = new FormData();
          $.each(file, function(key, value)
          {
              data.append(key, value);
          });

          data.append("guid", this.props.guid);
          data.append("packet_type", this.props.packetType);
          data.append("pervasive", this.props.pervasive);

          $.ajax({
            url: 'AdminAjaxHandler.ashx?handler=ChapterUpload',
            type: 'POST',
            data: data,
            cache: false,
            processData: false,
            contentType: false,
            success: function(data, textStatus, jqXHR)
            {
              capture.setState({
                href: "../DownloadFile.aspx?" + data,
                fileName: data.split("filename=")[1],
                uploadVal: "",
                isUploading: false
              })
                if(typeof data.error === 'undefined')
                {

                }
                else
                {
                    console.log('ERRORS: ' + data.error);
                }
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                console.log('ERRORS: ' + textStatus);
            }
        });
        }
    }
    return true;
  },
  getCheckedClass: function(){
    if(this.state.isChecked){
      return "chapter-row-active";
    }else{
      return null;
    }
  },
  getDownloadLink: function(){
    if(this.state.href != null){
      return (<div className="col-xs-12"><a href={this.state.href}>{this.state.fileName}</a></div>);
    }else{
      return null;
    }
  },
  checkDisabled: function (e) {
      console.log("Test: " + this.props.readOnlyRepealed);
      if (this.props.readOnlyRepealed)
      {
          e.stopPropagation();
          e.preventDefault();
          return false;
      }
  },
  getRadioOptions: function(){
    switch(this.state.action.toLowerCase()){
      case "null":
      case "repeal":
      case "supercede":
        case "replace":
            if (this.props.packetType.toLowerCase() == "nonsubstantive") {
                return (
                    <div className="replace-action-div">
                        <input name={"replace" + this.props.id} disabled="true" type="radio" value="Replace" checked={this.state.replaceChecked} id={"radio_replace" + this.props.id} onChange={this.props.readOnlyRepealed ? null : this.checkRadio} />
                        <label className="replace-action-label" htmlFor={"radio_replace" + this.props.id}>Replace</label>
                    </div>
                )
            }
        else if(this.props.packetType != "emergency"){
          return(
              <div>
                  <input name={"repeal" + this.props.id} disabled={!this.state.isChecked || this.props.readOnly} type="radio" value="Repeal" checked={this.state.repealChecked} id={"radio_repeal" + this.props.id} onChange={this.props.readOnlyRepealed ? null : this.checkRadio} />
                 <label htmlFor={"radio_repeal" + this.props.id}>Repeal</label>
                 <br/>
                 <input name={"supercede" + this.props.id} disabled={!this.state.isChecked || this.props.readOnly} type="radio" value="Supercede" id={"radio_supercede" + this.props.id} checked={this.state.supercedeChecked} onChange={this.props.readOnlyRepealed ? null : this.checkRadio}/>
                  <label htmlFor={"radio_supercede" + this.props.id}>Supercede</label>
              </div>
            )
        } else{
            return (              
              <div>
                 <input name={"enact" + this.props.id} disabled="true" type="radio" value="Enact" checked={this.state.enactChecked} id={"radio_enact" + this.props.id} onChange={this.props.readOnlyRepealed ? null : this.checkRadio} />
                 <label htmlFor={"radio_enact" + this.props.id}>Enact</label>
              </div>
            )
        }
        break;
      case "new":
        if (this.props.packetType.toLowerCase() == "nonsubstantive") {
            return (
                <div>
                    <input name={"replace" + this.props.guid} disabled={!this.state.isChecked || this.props.readOnly} type="radio" value="Replace" checked={this.state.replaceChecked} id={"radio_replace" + this.props.guid} onChange={this.props.readOnlyRepealed ? null : this.checkRadio} />
                    <label htmlFor={"radio_replace" + this.props.guid}>Replace</label>
                </div>
            )
        }
      else if(this.props.packetType != "emergency"){
        return(
          <div>
            <input name={"new" + this.props.guid} type="radio" disabled={!this.state.isChecked || this.props.readOnly} value="New" id={"radio_new" + this.props.guid} defaultChecked="true" onChange={this.props.readOnlyRepealed ? null : this.checkRadio}/>
            <label htmlFor={"radio_new" + this.props.id}>New</label>
          </div>
        )
      }else{
        return(
          <div>
             <input name={"enact" + this.props.guid} disabled={!this.state.isChecked || this.props.readOnly} type="radio" value="Enact" checked={this.state.enactChecked} id={"radio_enact" + this.props.guid} onChange={this.props.readOnlyRepealed ? null : this.checkRadio} />
             <label htmlFor={"radio_enact" + this.props.guid}>Enact</label>
          </div>
        )
      }
        break;
    }
  },
  render: function(){
    return(
      <tr className={this.props.rowClass + " " + this.getCheckedClass()}>
         <td>
                <div className="checkbox chapter-checkbox">
                    {this.props.readOnlyRepealed ? <div style={labelStyle} id="repealed-chapter-info" className="repealed-chapter-info" data-original-title="This Chapter has been repealed.  The Chapter Number cannot be reused." data-toggle="tooltip" data-placement="right" data-container="body" rel="tooltip" data-tooltip-title="This Chapter has been repealed.  The Chapter Number cannot be reused."><img src="../../../admin/images/ban-icon.png" /></div> :
                        <label className="">
                            <input type="checkbox" id="" checked={this.state.isChecked} disabled={this.props.readOnlyRepealed ? this.props.readOnlyRepealed : this.props.readOnly} onChange={this.props.readOnlyRepealed ? null : this.toggleChaptercheck} />
                        </label>
                    }
            </div>
         </td>
         <td>
         {this.props.action.toLowerCase() != "new" && this.props.action.toLowerCase() != "enact" ?
            this.props.num
            :
                    <input type="text" className="chapter-list-num-input" ref="numInput" disabled={!this.state.isChecked || this.props.readOnly || this.props.packetType.toLowerCase() == "final"} min="1" value={this.state.num} onChange={this.updateNumber}/>
         }
         </td>
         <td>
         {this.props.action.toLowerCase() != "new" && this.props.action.toLowerCase() != "enact" && !this.state.isChecked ?
            this.props.name
            :    
            //When Adding a New Chapter Show Different Input Field
            this.props.action.toLowerCase() == "new" ?
                        <input type="text" className="chapter-list-name-input" ref="nameInput" disabled={!this.state.isChecked || this.props.readOnly || this.props.packetType.toLowerCase() == "final"} value={this.state.name} onChange={this.updateNewName} />
            :
            //If Existing Chapter; Show Amended Name Option
            this.props.packetType.toLowerCase() == "nonsubstantive" ?
            this.props.name :
            <div>
                <span>{this.props.name}</span>
                <div>
                    <label><strong>Amended Chapter Name</strong></label>
                            <input type="text" className="chapter-list-name-input" ref="amendedNameInput" disabled={!this.state.isChecked || this.props.readOnly || this.props.packetType.toLowerCase() == "final"} value={this.state.amendedChapterName} onChange={this.updateName} />
                </div>
            </div>            
         }
         </td>
         <td>
         {this.getRadioOptions()}
         </td>
         {this.props.renderPervasive ?
         <td>
         {this.props.action.toLowerCase() != "new" ?
            <div className="checkbox chapter-checkbox">
               <label className="">
                    <input type="checkbox" checked={this.state.pervasiveChecked} disabled={this.state.isChecked && !this.props.readOnly ? false : true} id={"pervasive" + this.props.id} onChange={this.props.readOnlyRepealed ? null : this.togglePervasive}/>
               </label>
            </div>
            :
            null
          }
         </td>
         :
         null
         }
         <td>
            <div className="row">
               <div className="col-md-12 chapter-packet-download">
                  <div className="input-group pull-left edit-packet-upload">
                     <div id="strike_4110" className="edit-packet-download">
                     {
                       !this.props.isEdge ?
                       <label htmlFor={"upload " + this.props.guid} className={this.state.isChecked && !this.props.readOnly ? "btn btn-primary btn-xs btn-icon chapter-upload-button " : "btn btn-primary btn-xs btn-icon chapter-upload-button upload-disabled"}>
                         {!this.state.isUploading ?
                           <span><span className="glyphicon glyphicon-open"></span> Upload</span>
                           :
                           <span>
                             <img className="chapter-upload-loader" src="../images/save.gif" /> Uploading...
                           </span>
                         }
                         <input type="file" className="chapter-upload-input" value={this.state.uploadVal} disabled={this.state.isChecked && !this.props.readOnly ? false : true} accept=".docx" id={"upload " + this.props.guid} role="button" onChange={this.validateFileType}/>
                       </label>
                                        :
                                        <span>
                         <label htmlFor={"upload " + this.props.guid} for={"upload " + this.props.guid} className={this.state.isChecked && !this.props.readOnly ? "btn btn-primary btn-xs btn-icon chapter-upload-button " : "btn btn-primary btn-xs btn-icon chapter-upload-button upload-disabled"}>
                            {!this.state.isUploading ?
                                <span><span className="glyphicon glyphicon-open"></span> Upload</span>
                                :
                                <span>
                                    <img className="chapter-upload-loader" src="../images/save.gif" /> Uploading...
                                </span>
                            }
                        </label>
                        <input type="file" className="chapter-upload-input" value={this.state.uploadVal} disabled={this.state.isChecked && !this.props.readOnly ? false : true} accept=".docx" id={"upload " + this.props.guid} role="button" onChange={this.validateFileType} />
                        <label for={" upload " + this.props.guid}></label>
                        </span>
                      // <span>
                      //    {
                      //      this.state.isChecked && !this.props.readOnly ?
                      //        <input type="file" className="chapter-upload-input force-show" value={this.state.uploadVal} accept=".docx" id={"upload " + this.props.guid} role="button" onChange={this.validateFileType}/>
                      //      :
                      //        <input type="file" className="chapter-upload-input force-show" value={this.state.uploadVal} disabled="true" accept=".docx" id={"upload " + this.props.guid} role="button" onChange={this.validateFileType}/>
                      //    }

                      //</span>
                     }
                          <label className="pull-left">{!this.state.pervasiveChecked && this.props.packetType == "proposed" ? "Upload strike/underscore document" : "Upload clean document"}</label>
                     </div>
                  </div>
               </div>
               {this.getDownloadLink()}
            </div>
         </td>
      </tr>
    )
  }
})
