
views.init = function() {

  views.common()

  Backbone.View.prototype.renderwhen = function( model, prop, val ) {
    var self=this;
    model.when_equal(prop,val, function(equal,curval) {
      equal ? (self.render && self.render()) : (self.hide && self.hide())
    })
  }

  Backbone.View.prototype.renderonchange = function( model, prop ) {
    var self=this;
    model.bind('change:'+prop,function(){
      self.render && self.render()
    })
  }


  views.pagebtn = function( elem, basic ) {
    elem.bind(C.tap,function(){
      app.model.page.set({type:basic.name})
    })
  }


  views.FeatureBarView = Backbone.View.extend(views.articlelist)


  views.FrontArticlesView = Backbone.View.extend(_.extend({
    onitem: function(art,elem,i) {
      if( i < C.num_top_art ) {
        elem.addClass('top')
      }

      if( 0 === i ) {
        elem.find('h4').addClass('first')
      }
    }
  },views.articlelist))


  views.FeatureBox = Backbone.View.extend(views.articlelist)


  views.FeatureColumn = views.Basic.extend({
    name: 'featurecol',
    el: $('#front_featurecol'),

    init_impl: function() {
      _.bindAll(this,'render_impl')
      var self=this;
      self.elem = {
        front_discover: $('#front_discover')
      }
    },

    render_impl: function() {
      var self=this;
      self.elem.front_discover.css({width:447})
      return true
    }
  })



  views.CatBarView = Backbone.View.extend({

    initialize: function() {
      _.bindAll(this,'render')
      var self=this;
      
      self.el = $('#front_catbar')
      self.cat_list = $('#front_cat_list')
      self.cat_tm = $('#front_cat_item_tm').clone()

      self.dirty = true

      self.subcat_list    = $('#front_subcatbar')
      self.subcat_list_tm = $('#front_subcat_list_tm').clone()
      self.subcat_item_tm = $('#front_subcat_item_tm').clone()

      self.catmap = {}
      self.subcatmap = {}
    },

    render: function() {
      var self=this;

      var show_cat_id   = null
      var show_cat_item = null

      function showcat( catid, cat_item,whence) {
        /*jshint boss:true*/
        
        self.cat_list.find('li').removeClass('current')
        cat_item.addClass('current')
        $('ul.front_subcat_list').hide()
        $('#subcat_list_'+catid).show()
      }

      function showsubcat( subcat_item) {
        self.subcat_list.find('li').removeClass('current')
        subcat_item && subcat_item.addClass('current')
      }

      var cat

      if( self.dirty ) {
        self.dirty = false

        // FIX: move all this init

        self.cat_list.empty()
        self.subcat_list.empty()

        var first_cat_item = null
        var first_cat_id = null


        for( cat in app.cats ) {
          var catid = cat.replace(' ','-')

          var catname = app.cats[cat].name || cat
          var cat_item = self.cat_tm.clone().text(catname).attr('id','cat_'+catid)
          self.catmap[cat] = cat_item

          cat_item.bind(C.tap,function(catid,cat_item,cat){
            return function() {
              //showcat(catid,cat_item,'select')
              app.model.frontpage.set({cat:cat,subcat:''}).trigger('frontpage-cat')
            }
          }(catid,cat_item,cat))


          if( !first_cat_item ) {
            first_cat_item = cat_item
            first_cat_id = catid
          }

          self.cat_list.append(cat_item)

          var subs = app.cats[cat]
          var subcat_list = self.subcat_list_tm.clone().empty().hide().attr('id','subcat_list_'+catid)
          self.subcat_list.append(subcat_list)

          for( var i = 0; i < subs.length; i++ ) {
            var sub = subs[i]

            var name = sub
            var url = null

            if( sub.url ) {
              name = sub.name
              url = sub.url
            }

            var subcat_item = self.subcat_item_tm.clone().text(name).attr('id','subcat_'+catid+'_'+name)
            self.subcatmap[name] = subcat_item

            subcat_item.bind(C.tap,function(subcat_item,name,url){
              return function() {
                if( url ) {
                  window.location = url
                }
                else {
                  app.model.frontpage.set({subcat:name}).trigger('frontpage-subcat')
                }
              }
            }(subcat_item,name,url))

            subcat_list.append(subcat_item)
          }
        }

        show_cat_id   = first_cat_id
        show_cat_item = first_cat_item
      }

      cat = app.model.frontpage.get('cat')
      if( cat ) {
        show_cat_item = self.catmap[cat]
        show_cat_id   = show_cat_item.attr('id').substring(4)
      }
      showcat( show_cat_id, show_cat_item, 'render' )

      var subcat = app.model.frontpage.get('subcat')
      if( subcat ) {
        showsubcat( self.subcatmap[subcat] )
      }
    }

  })


  views.WebSearch = views.Search.extend({
    prefix:'web',
    render_impl: function() {
      var self=this;
      var terms = app.model.search.get('terms')
    }
  })



  views.UserMenuView = Backbone.View.extend({

    initialize: function() {
      _.bindAll(this,'render')

      var self=this;

      self.authdiv = $('#'+mode.name+'_auth')
      self.noauthdiv = $('#'+mode.name+'_noauth')
      self.unknownauthdiv = $('#'+mode.name+'_unknownauth')
    },


    render: function() {
      var self=this;

      var auth = app.model.user.get('auth')
      util.hide(self.unknownauthdiv)

      if( auth ) {
        var user = app.model.user.get('user')
        
        //self.account_name.text(user.nick)
        self.authdiv.removeClass('hide')
        self.noauthdiv.addClass('hide')
      }
      else {
        self.authdiv.addClass('hide')
        self.noauthdiv.removeClass('hide')
      }
    }

  })



  views.WebHeader = Backbone.View.extend({
    el: $('#web_header'),

    initialize: function() {
      _.bindAll(this,'render')      
      var self=this;

      self.elem = {
        tagline: $('#web_header_tagline'),
        edition: $('#web_header_edition'),
        logo: $('#web_header_logo'),
        link: $('#web_header_link'),
        today: $('#web_header_today'),

        calltoaction: $('#calltoaction')
      }

      self.elem.calltoaction.bind(C.tap,function(){
        app.chartaca.fire('calltoaction')
      })
    },

    render: function() {
      var self=this;

      // FIX: use views.Masthead

      var today = new Date()
      var isEditionDay = business.iseditionday(today)

      var editioncode = app.model.edition.get('code')
      if( (!editioncode || 'daily'===editioncode) && !isEditionDay ) {
        util.hide(self.elem.edition)
        util.show(self.elem.tagline)
        self.elem.logo.attr('src','img/dbpostlogo_web.png')
        self.elem.link.attr('href','/')
        util.show(self.elem.today.text( today.toString('HH:mm, d MMMM yyyy') ))
      }
      else {
        var edd

        if( editioncode && 'daily'!==editioncode ) {
          edd = business.yyyymmdd(editioncode)
        }
        else {
          edd = business.editiondate(new Date())
        }

        log('edd='+edd+' ec='+editioncode)

        util.hide(self.elem.tagline)
        self.elem.today.html('&nbsp;')
        util.show(self.elem.edition.text( edd.toString('d MMMM yyyy') ))
        self.elem.logo.attr('src','img/sbpostlogo_web.png')
        self.elem.link.attr('href','#!edition/'+editioncode)
      }
    }

  })



  views.MenuView = Backbone.View.extend({
    el: $('#menu_view'),

    initialize: function() {
      _.bindAll(this,'render','hide','setCat')

      var self=this;

      this.catmenu = $('#catmenu')
      this.content = $('#catmenu_content')
      this.catlist = $('#catmenu_list')
      this.cat     = $('#catmenu_cat')

      this.title = $('#front_section_title')

      this.close_btn = $('#menu_close_btn')
      this.close_btn.bind(C.tap,function(){
        self.hide()
      })

      $('#catmenu_cat').bind(C.tap, function(e){
        app.model.frontpage.set({cat:e.target.innerText,subcat:''})
        self.hide()
      })

      self.preview = views.list(
        '#catmenu_storylist',
        '#catmenu_story',
        {
          'h2': 'h',
          'p': 'd',
          'img': {val:'img',ifempty:'hide',setattr:{
            name:'src',
            custom:function(imgurl){return views.s3imgurl(imgurl,self.options.imgcode)}
          }}
        },
        null,
        function(item,elem,i) {
          new views.ArticleInfoView({
            el:elem,
            sid:item.sid,
            pub:item.pub,
            type:item.ty,
            custom:function(){
              return function() {
                self.hide()
              }
            }
          })
        }
      )
    },


    render: function() { 
      var self=this;
      self.me = this.content[0]

      self.overlay = $('<div>').css({position:'absolute',top:0,left:0,zIndex:9100,
                                     width:this.options.formfactor.get('w'),
                                     height:this.options.formfactor.get('h')
                                     //,opacity:0.2, backgroundColor:'green'
                                    })

      self.overlay.bind(C.tap,function(){
        self.overlay.remove()
        self.hide()
      })

      $('body').append(self.overlay)


      self.catlist.empty()
      app.cats_order.forEach(function(cat){
        self.catlist.append( $('<li>').text(cat).bind(C.tap,function(){
          self.setCat(cat)
        }))
      })
      

      var lastms  = $('#catmenu_story_2')
      //var width   = app.articlelayout.get('viewwidth')
      var width   = self.options.formfactor.get('w')

      // FIX: needs abstraction
      if( width <= 768 ) {
        $('#catmenu_list').width(148)
        $('#catmenu_storybar').width(600)
      }
      else {
        $('#catmenu_list').width(204)
        $('#catmenu_storybar').width(800)
      }

      // FIX: should remember
      self.setCat('Home')
      self.catmenu.show()

      var h = this.content.height()

      Firmin.translateY( self.me, -1*h).translateY( 0, '1s')
    },

    hide: function() {
      var self=this;

      self.overlay && self.overlay.remove()
      var h = this.content.height()

      if( !self.scroller ) {
        self.scroller.destroy()
      }

      Firmin.translateY( self.me, -1*h,'1s',function(){
        self.catmenu.hide()
        self.visible = false
      })
    },

    setCat: function(cat) {
      var self=this;
      self.cat.text(cat)

      app.model.articlestore.loadcat(cat,function(list){
        var padding = (4-(list.length%4))%4
        $('#catmenu_scroller').width( 200 * (list.length+padding) )

        self.preview.render(list,function(){
          self.scroller = new iScroll('catmenu_storybar', {
	    snap: true,
	    momentum: false,
            bounce:false,
	    hScrollbar: false,
	    vScrollbar: false
          })
        })
      })
    }

  })



  views.Page = Backbone.View.extend({
    el: $('#page'),

    initialize: function() { 
      var self=this;
      _.bindAll(this,'render','hide')

      self.renderwhen( self.options.model, 'type', 'page' )

      self.options.model.bind('change:page',self.render)
    },

    render: function() { 
      var self=this;

      self.model.load(function(page,content){
        
        if( page != self.page ) {
          self.el.empty()

          if( content ) {
            self.el.html(content)
          }

          self.page = page
        }
        util.show(self.el)
      })
    },

    hide: function() { var self=this;
      util.hide(self.el)
    }
  })


  views.ClickArticleView = Backbone.View.extend({
    el: $('#web_article_view'),

    elem: {
      front_discover: $('#front_discover')
    },


    initialize: function() {
      var self=this;
      _.bindAll(this,'render','setArticle','hide','setSimilar','flowcol','page')

      this.colviews = []
      this.articlelayout = this.options.articlelayout

      self.content = $("#web_article_content")

      this.firstcol = new views.ColView({articlelayout:this.articlelayout,articleview:this})
      self.content.append( this.firstcol.el )

      self.artid = null
    },

    render: function() {
      var self=this;

      function rendercols(whence) {
        if( !self.article.access ) {

          var pub = self.article.pub
          if( _.isString(pub) ) {
            pub = app.model.articlestore.parseDate(pub)
          }

          if( 0 === pub.getDay() || 'newspaper' === self.article.ty ) {

            // might have purchased
            self.article.access = app.model.user.access().access(pub,'render-access')

            if( !self.article.access ) {
              new views.ArticleInfoView().sendToPurchase(self.article.sid,pub)
              return;
            }
          }
        }


        util.hide(self.el)

        if( !self.items ) {
          return;
        }

        //var onecol = self.items.length < 17
        var onecol = true //self.items.length < 17
        if( onecol ) {
          app.view.overview.showmpu(1)
          //self.elem.front_discover.css({width:340})
          app.view.featurecol.show()
        }
        else {
          app.view.overview.showmpu(2)
          self.elem.front_discover.css({width:700})
          //$('#front_articlelist').hide()
          //$('#front_featurecol').hide()
          app.view.featurecol.hide()
          $('#front_thirdcol').width(320)
        }


        self.articlelayout.set({colheight:-2,
                                colwidth:340,
                                webcols:true})

        app.view.frontarticles.hide()
        app.view.page.hide()

        self.firstcol.setItems(self.items)
        self.firstcol.setSimilar(self.similar)
        self.firstcol.render()

        var head = $('#web_article_head')
        head.find('h2').text( self.article.h )
        head.find('p').text( self.article.m )

        app.navigate('!story/'+app.story_link_desc(self.article) )

        window.scrollTo(0,0)
        util.show(self.el)
      }

      var artid = self.options.page.get('artid')

      if( artid != self.artid ) {
        self.loadArticle(artid,function(art){
          self.setArticle(art)
          rendercols('load')
        })
      }
      else {
        rendercols('already')
      }
    },


    page: function() {
      var self=this;

      var pagetype = app.model.page.get('type')
      if( 'article' != pagetype ) {
        self.hide()
      }
    },


    hide: function() {
      var self=this;
      util.hide(self.el)
      self.visible = false
    },


    setArticle: function(article) {
      var self=this;

      self.article = article
      self.artid = article.sid

      this.items = new ColItemList()

      for( var i = 0; i < article.contents.length; i++ ) {
        var item = new models.ColItem( article.contents[i] )
        this.items.add(item)
      }
    },


    setSimilar: function(similar) {
      this.similar = similar;
    },

    flowcol: function(colp,items) {
      var col = this.colviews[colp]

      if( !col ) {
        col = this.colviews[colp] = new views.ColView({articlelayout:this.articlelayout,articleview:app.view.articleview,pos:colp})
        this.content.append( col.el )
      }

      col.setItems(items)
      col.render()
    }

  })



  // FIX: should just be Front
  views.FrontPageView = Backbone.View.extend({
    el: $('#front_view'),

    initialize: function() {
      _.bindAll(this,'render','reload')
      var self=this;

      self.front_wrapper = $('#front_wrapper')

      this.cat    = $('#front_section_cat')
      this.subcat = $('#front_section_subcat')

      self.elem = {
        frontarticles: $('#frontarticles'),
        purchase_complete_msg: $('#web_purchase_complete_msg'),
        stocktable_btn: $('#front_stocktable_btn'),
        stocktable_iseq_btn: $('#front_stocktable_iseq_btn'),
        stocktable_close_btn: $('#stocktable_close_btn'),
        stocktable: $('#stocktable'),
        stocktable_frame: $('#stocktable_frame')
      }


      self.bind('frontpage-render',function(){
        self.render()
      })


      $('#front_adtop').removeClass('hide')

      app.model.frontpage.bind('frontpage-cat',function(){
        var cat = app.model.frontpage.get('cat')
        if( '' !== cat ) {
          util.hide(self.elem.frontarticles)
          app.model.page.set({type:'front'})
          app.view.frontpage.trigger('frontpage-render')
          app.navigate('#!cat/'+cat)
        }
      })

      app.model.frontpage.bind('frontpage-subcat',function(){
        var cat = app.model.frontpage.get('cat')
        var subcat = app.model.frontpage.get('subcat')
        if( '' !== subcat ) {
          util.hide(self.elem.frontarticles)
          app.model.page.set({type:'front'})
          app.view.frontpage.trigger('frontpage-render')
          app.navigate('#!subcat/'+cat+'/'+subcat)
        }
      })

      function show_stocktable() {
        self.elem.stocktable_frame.attr('src','http://sbp.chartaca.com.s3.amazonaws.com/embed/sbp/stocktable.html')
        util.show(self.elem.stocktable)
      }

      self.elem.stocktable_btn.bind(C.tap,function(){
        show_stocktable()
      })

      self.elem.stocktable_iseq_btn.bind(C.tap,function(){
        show_stocktable()
      })

      self.elem.stocktable_close_btn.bind(C.tap,function(){
        util.hide(self.elem.stocktable)
      })
    },

    reload: function() {
      document.location.href = document.location.href
    },

    render: function() {
      var self=this;

      util.hide(self.front_wrapper)

      app.view.articleview.hide()
      app.view.catbar.render()
      app.view.header.render()

      app.view.frontarticles.hide()


      var bodywidth = Math.min(1024,window.innerWidth)
      $(document.body).css({width:bodywidth+'px'})

      var lastfhf = $('#front_header_feature_3')

      var logo = $('#front_header_logo')
      var noauth = $('#front_noauth')

      var discovercol = $('#front_discover').width(447).show()
      var thirdcol    = $('#front_thirdcol').width(255).show()


      $('#front_header_home_btn').hide()


      var cat = app.model.frontpage.get('cat')
      this.cat.text( cat )

      var subcat = app.model.frontpage.get('subcat')
      this.subcat.text( subcat )

      var pagetype = app.model.page.get('type')
      if( 'front' == pagetype ) {
        app.model.frontarticles.load()
      }

      util.show(self.front_wrapper)
      util.show(self.el)

      var purchase_complete = app.model.page.get('purchase_complete')

      if( purchase_complete ) {
        log('show thanks',self.elem.purchase_complete_msg)
        util.show(self.elem.purchase_complete_msg)
        app.model.page.set({purchase_complete:false})
      }
      else {
        util.hide(self.elem.purchase_complete_msg)
      }
    }
  })


}

