# this var holds whatever HTML has been parked
# to make room for a loader
#
class App.Shared
  constructor: (@el) ->
    # initialize some stuff
    # it will be re-instated with releaseLoader
    @loaded_html = ""
    @loaded_element = ""
    @currentForm = ""

  setCurrentForm: (f) =>
    @currentForm = f

  getCurrentForm: =>
    @currentForm

  callToast: (msg,time=3000,style="rounded") =>
     Materialize.toast(msg, time,style)

  getDownload: (xhr,data) =>
    # Check if a filename is existing on the response headers.
    filename = ""
    disposition = xhr.getResponseHeader("Content-Disposition")
    if disposition && disposition.indexOf("attachment") != -1
      filenameRegex = /filename[^;=\n]*=(([""]).*?\2|[^;\n]*)/
      matches = filenameRegex.exec(disposition)
      if matches != null && matches[1]
        filename = matches[1].replace(/[""]/g, "")
    #
    type = xhr.getResponseHeader("Content-Type")
    blob = new Blob([data], {type: type})
    #
    if typeof window.navigator.msSaveBlob != "undefined"
      # // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed.
      window.navigator.msSaveBlob(blob, filename)
    else
      URL = window.URL || window.webkitURL
      downloadUrl = URL.createObjectURL(blob)
      downloadUrl.oneTimeOnly = true
      #
      if filename
        # // Use HTML5 a[download] attribute to specify filename.
        a = document.createElement("a")
        # // Safari doesn"t support this yet.
        if typeof a.download == "undefined"
          window.location = downloadUrl
        else
          a.href = downloadUrl
          a.download = filename
          document.body.appendChild(a)
          a.click()
      else
        window.location = downloadUrl



  closeSweetAlert: ($elem=null) =>
    try
      unless $elem == undefined
        $elem.show()
      swal.close()
    catch error
      $('.sweet-overlay').hide()
      $('.sweet-alert').hide()


  # cloneObject will make a copy of an object - not a copy of the reference
  # to some object!
  #
  # var obj1= {bla:'blabla',foo:'foofoo',etc:'etc'};
  # var obj2= new cloneObject(obj1);
  #
  # 03-07-2015 (whd) not sure whether this method is OK!!!!
  # cp'ed from: http://scriptcult.com/subcategory_1/article_414-copy-or-clone-javascript-array-object
  #
  cloneObject: (source) =>
    for i in source
      if typeof source[i] == 'source'
        this[i] = new cloneObject source[i]
      else
        this[i] = source[i]



  #
  # set a loader - see http://materializecss.com/preloader.html
  # for examples
  #
  setLoader: (elem,html) =>
    html ||= '<div class="progress"><div class="indeterminate"></div></div>'
    @loaded_element = $(elem)
    @loaded_html = elem.html()
    elem.html(html)
    return @loaded_html

  #
  # release the loader
  #
  releaseLoader: (elem=null) =>
    elem ||= @loaded_element
    $(elem).html(@loaded_html)

  tellResponse: (msg,anchor='.message_container',fade=15000,selector='.alert') =>
    $(anchor).prepend(msg)
    if fade>0
      fadeItOut $(anchor).find(selector), 15000

  reportError: (msg) =>
    Materialize.toast( msg, 4500, 'red lighten-3')


  #
  # fadeItOut will fade an element out with a preset or
  # supplied delay
  #
  fadeItOut: (e,delay=3500) =>
    $(e).delay( delay ).fadeOut( 1000 )

  #
  # dataArgumentOn constructs the data: argument on AJAX calls
  # from what ever data- attributes an element holds
  #
  # excemptions: data-id, data-remote, data-ajax, data-method, data-type and data-url
  #
  dataArgumentOn: (elem) =>
    $(elem).data()
    # try
    #
    #   swal( 'pageOnLoad', 'pageOnLoad blev kaldt!', 'success')
    #
    # catch error
    #   console.log 'ok - giving up'
    # console.log 'page loaded!'

  #
  # check to see iff this browser supperts the File APIs
  #
  fileApiSupportCheck: () =>
    if (window.File && window.FileReader && window.FileList && window.Blob)
      # All the File APIs are supported.
      console.log 'file APIs supported '
    else
      document.getElementById('message_container').innerHTML = '<div class="alert fade in alert-warning"><a href="#!" class="warning close-notice btn-floating btn-small waves-effect waves-light" aria-hidden="true" type="button" data-dismiss="alert"><i class="material-icons">close</i></a>This browser does not support this application fully! Use latest Chrome - or advance cautiously!</div>';