/*jshint evil:true */

var app = { 
  debug:{pre_start:function(){},post_start:function(){}},
  initparams:{view:{},model:{}},
  conf:{
    // non-sunday date (yyyymmdd as str) : [sunday replaced, start date rage, end date range] where date range maps to non-sunday date
    nonsunday:{'20111224':[20111225,20111224,20111231]},
    price:{single:'2.39',monthly:'7.99',quarterly:'19.99',annual:'69.99'}
  },
  dump:function(){
    return {sbpappid:app.sbpappid,newinstall:app.newinstall,checkintime:app.checkintime}
  }
}


 
app.cats = {
    "Home": ["News", "Budget 2012", "Media And Marketing",  "Business Interview", "News Focus", "Politics", "Profile", "Special Reports"],

    "Markets": ["Markets Features", "Board Room", "Done Deal", "Economics", "Inquisitor", "Insider",
		{name:"Job Search",url:"http://www.recruitireland.com/"},
		"Jobs", "Markets News", "Banking"
	       ],

    "Comment": ["Cliff Taylor", "David McWilliams", "Letters", "Op-ed", "Opinion", "Pat Leahy", "Richard Curran", "Tom McGurk", "Vincent Browne" ],

    "Agenda": [
	"Artistic Licence", "Books", "Film", "First Person", "Guide", "Inside Story", "Music", "Off Message", "Post Mortem"
    ],

    "Living": [
	"TV & Radio", "Fashion", "Food & Wine", "Modern Life", "Motoring", "Travel",
	{name:"Car Search",url:"http://www.motornet.ie/"}
    ],

    "Personal Finance": ["Features", "Loose Change", "Personal Finance", "Pocket Watch", "Tax Advice"],

    "Technology": ["Technology News", "Features", "Computers In Business", "Reality Bytes", "Reviews", "Apps"],

    "Property": [
	"Residential", "Cover Story", "Fine Arts", "Overseas", "Property News", 
	{name:'Property Search',url:"http://property.thepost.ie/residential/search"},
	"Commercial"
    ],

    "Small Business": ["Startup Of The Day", "Business Advice", "Business Of Law", "Out On Your Own", "People In Business", "Small Business"],

    "Commercial Reports": [ "Business Growth", "Commercial Features", "Education", "IT", "Management"]
}

app.cats['Agenda'].name = 'Magazine'

app.cats_order = [
    "Home",
    "Markets",
    "Comment",
    "Agenda",
    "Living",
    "Personal Finance",
    "Technology",
    "Property",
    "Small Business",
    "Commercial Reports"
]


function updaterecent( recent ) {
  if( recent && recent.arts && 0 < recent.arts.length) {
    app.model.articlestore.dirty.priority = true
    for( var i = 0; i < recent.arts.length; i++ ) {
      app.model.articlestore.clear(recent.arts[i].sid)
    }
    
    app.model.articles && app.model.articles.load()
    app.model.frontarticles && app.model.frontarticles.load()
  }
}

var updatecache_count = 0
function updatecache( recent ) {
  if( 11 < updatecache_count ) return;

  if( recent ) {
    if( !app.initdone ) {
      updatecache_count++
      setTimeout(function(){updatecache(recent)},5000)
    }
    else updaterecent( recent );
  }
}


function cachecheck() {
  util.http_get('/api/recent/'+app.checkintime+'/'+app.sbpappid+'/'+C.version,function(err,res){
    if( err ) return log('error','cachecheck',err);
    log('cachecheck',JSON.stringify(res))
    if( res.cacheclear ) {
      app.model.articlestore.clear()
    }
    else if( res.recent ) {
      updaterecent(res.recent)
    }
  })
}


function checkin() {
  app.sbpappid = store.get('sbpappid')

  if( !app.sbpappid ) {
    app.newinstall = true
    store.set('sbpappid',app.sbpappid = uuid())
  }
  log('sbpappid='+app.sbpappid)

  function rundebug() {
    try {
      var debug = store.get('debug') || ''
      eval(debug)
    }
    catch( e ) {
      log( 'error', 'debug', e )
    }
  }
  rundebug()

  app.checkintime = parseInt(store.get('checkintime')||new Date().getTime(),10)
  util.http_get('/api/checkin/'+app.checkintime+'/'+app.sbpappid+'/'+C.version,function(err,res){
    if( err ) return log('error','checkin',err)
    if( res ) {
      log('checkin',res)

      app.checkintime = res.when 
      store.set('checkintime',''+res.when)

      if( res.cacheclear ) {
        app.model.articlestore.clear()
      }
      updatecache(res.recent)

      app.cacheinterval = setInterval(cachecheck,C.cacheinterval)
      if( res.debug ) {
        store.set('debug',res.debug)
        app.debug.first = true
        rundebug()
      }
    }
  })

}


app.showmsg = function( text, title, button, cb ) {
  /*jshint devel:true */
  title = title || 'The Sunday Business Post'
  button = button || 'Dismiss'
  cb = cb || function(){}

  if( text && _.isString(text) && 0 < text.length ) {
    if( navigator.device ) {
      navigator.notification.alert( text, cb, title, button )
    }
    else {
      alert( text )
    }
  }
}


app.navigate = function( hash ) {
  app.router.navigate( hash )
  var url = window.location.href
  url = url.replace('#!','')
  _gaq && _gaq.push(['_trackPageview', url]);

  if( window.plugins && window.plugins.flurry ) { 
    if( !/articleview$/.exec( url ) ) {
      window.plugins.flurry.logPageView()
    }
  }
}


app.story_link_desc = function(art) {
  return encodeURIComponent(art.c).replace(/%20/g,'+')+
    '/'+encodeURIComponent(art.sc).replace(/%20/g,'+')+
    '/'+encodeURIComponent(art.h).replace(/%20/g,'+')+
    '/id/'+art.sid
}


function SubManager() {
  var self=this;

  self.encode = function(fields) {
    var params = []
    _.keys(fields).forEach(function(key){
      var val = fields[key]
      params.push( encodeURIComponent(key)+'='+encodeURIComponent(val) )
    })
    return params.join('&')
  }


  self.error = function(err) {
    log('error','submanager',JSON.stringify(err))
  }


  self.buy = function( spec ) {
    app.chartaca.fire('buy-start:single:'+spec.edition)

    var when = new Date()
    var millis = (''+(1000+when.getMilliseconds())).substring(1)
    var whenstr = when.toString('dd-MM-yyyy:HH:mm:ss:')+millis

    util.http_post('/api/buy/single/'+spec.edition, {
      whenstr:whenstr,
      when:when.getTime(),
      artid:spec.artid||spec.sid,
      channel:mode.device?'apple':'worldnet',
      email:spec.email

    }, function(err,purchase){
      if( err ) return self.error(err);
      if( purchase.err ) return self.error(purchase.err);

      if( mode.device ) {
        app.chartaca.fire('buy-proceed:single:apple:'+spec.edition)
        return self.apple.buy(spec,purchase)
      }
      else {
        app.chartaca.fire('buy-proceed:single:worldnet:'+spec.edition)
      }

      self.submit('https://'+C.payhost+'/merchant/paymentpage',{
        TERMINALID:      purchase.terminalid,
        CURRENCY:       'EUR',
        ORDERID:        purchase.orderid,
        AMOUNT:         purchase.amount,
        DATETIME:       purchase.whenstr,
        CUSTOMFIELD1:   purchase.pid,
        CUSTOMFIELD2:   spec.edition,
        //CARDHOLDERNAME: '',
        //ADDRESS1:       '',
        //ADDERSS2:       '',
        //POSTCODE:       '',
        EMAIL:          spec.email,
        DESCRIPTION:    spec.desc,
        //AUTOREADY:      '',
        RECEIPTPAGEURL: purchase.rpurl,
        //VALIDATIONURL:  '',
        HASH:           purchase.hash
      })
    })
  }

  self.submit = function( url, fields ) {
    url = url + '#' + new Date().getTime()
    var form = $('#worldnetform')
    var input = form.find('input').clone()
    form.empty()
    form.attr('action',url)

    _.keys(fields).forEach(function(key){
      var val = fields[key]
      var fin = input.clone()
      fin.attr('name',key).val(val)
      form.append(fin)
    })

    form.submit()
  }


  self.regcard = function(spec) {
    app.chartaca.fire('buy-regcard-start'+spec.kind)

    var when = new Date()
    var millis = (''+(1000+when.getMilliseconds())).substring(1)
    var whenstr = when.toString('dd-MM-yyyy:HH:mm:ss:')+millis

    util.http_post('/api/buy/regcard', {
      whenstr:whenstr,
      spec:spec
    }, function(err,regcard){
      if( err ) return self.error(err);
      if( regcard.err ) return self.error(regcard.err);
      self.submit(
        'https://'+C.payhost+'/merchant/securecardpage',
        {
          ACTION:       regcard.action,
          TERMINALID:  regcard.terminalid,
          MERCHANTREF: regcard.merchantref,
          DATETIME:    regcard.whenstr,
          HASH:        regcard.hash
      })
    })
  }


  self.subscribe = function(spec) {
    app.chartaca.fire('buy-subscribe-start:'+spec.kind)

    var when = new Date()
    var millis = (''+(1000+when.getMilliseconds())).substring(1)
    var whenstr = when.toString('dd-MM-yyyy:HH:mm:ss:')+millis
    var startstr = whenstr
    var period = spec.kind

    var subidmap = {monthly:'sbpmonth',quarterly:'sbpquarter',annual:'sbpannual'}
    var subid = subidmap[spec.kind]

    util.http_post('/api/buy/subscribe/'+subid, {
      whenstr:whenstr,
      startstr:startstr,
      artid:spec.artid,
      channel:mode.device?'apple':'worldnet',
      email:spec.email

    }, function(err,subscription){
      if( err ) return self.error(err);
      if( subscription.err ) return self.error(subscription.err);

      if( mode.device ) {
        app.chartaca.fire('buy-proceed:subscribe:apple:'+spec.kind)
        return self.apple.buy(spec,subscription)
      }
      else {
        app.chartaca.fire('buy-proceed:subscribe:worldnet:'+spec.kind)
      }

      self.submit(
        'https://'+C.payhost+'/merchant/subscriptionpage/register',
        {
          TERMINALID:  subscription.terminalid,
          MERCHANTREF: subscription.merchantref,
          STOREDSUBSCRIPTIONREF: subscription.subid,
          SECURECARDMERCHANTREF: subscription.cardref,
          DATETIME:    whenstr,
          STARTDATE:   startstr,
          HASH:        subscription.hash
      })
    })
  }

  
  if( mode.device ) {

    self.apple = {
      state: {},
      buy: function(spec,purchase) {
        var buy_elem = $('#'+mode.name+'_purchase_'+spec.kind)
        var buy_spinner = buy_elem.find('div.buy_spinner')

        try {
          self.apple.state.spinner = new Spinner(spin_opts).spin( buy_spinner[0] );
        } catch( e ) { log('error','spinner',e) }

        self.apple.state[spec.code] = {spec:spec,purchase:purchase}

        window.plugins.inAppPurchaseManager.requestProductData(
          spec.code, 
          function(productId, title, description, price) {
            plugins.inAppPurchaseManager.makePurchase( spec.code )
          }, 
          function(id) {
            log('error', "invalid product id: " + id)
          }
        )
      }
    }


    window.plugins.inAppPurchaseManager.onPurchased = function(transactionIdentifier, productId, transactionReceipt) {
      var state = self.apple.state[productId]

      if( self.apple.state.spinner ) { self.apple.state.spinner.stop() }

      util.http_post('/api/apple/purchased', {      
        sbpappid:app.sbpappid,
        when: new Date().getTime(),
        apple: {
          tid: transactionIdentifier,
          pid: productId,
          rcpt: transactionReceipt
        },
        spec:state.spec,
        purchase:state.purchase
      }, function( err, res ) {
        if( err ) return self.error(err);
        if( res ) {
          if( res.ok ) {
            if( res.login ) {
              util.http_cookies[C.token_name] = res.login.token
            }

            // load new editions and access
            app.model.user.load(function(auth,user,login){
              app.view.editions.dirty=true

              navigator.notification.alert( 

                "Thank You! You will now be taken directly to your purchased edition or article. "+
                  "Tap the Daily tab to return to daily news.", 

                function(){}, 'Purchase Complete', 'Dismiss')

              app.view.purchase.inprogress=false

              if( state.spec.sid ) {
                app.model.page.set({type:'article',artid:state.spec.sid}) 
                app.view.articleview.display_sid(state.spec.sid)
              }
              else {
                app.model.edition.set({code:state.spec.edition})

                // FIX move to event
                if( 'pad' == mode.name ) {
                  app.model.page.set({type:'front'})
                  app.view.frontpage.trigger('frontpage-render')
                  app.navigate('!edition/'+state.spec.edition)
                }
              }
            })
          }
        }
      })
    }


    window.plugins.inAppPurchaseManager.onRestored = function(transactionIdentifier, productId, transactionReceipt) {
      if( self.apple.state.spinner ) { self.apple.state.spinner.stop() }

      util.http_post('/api/apple/restored', {      
        when: new Date().getTime(),
        apple: {
          tid: transactionIdentifier,
          pid: productId,
          rcpt: transactionReceipt
        }
      }, function( err, res ) {
        if( err ) return self.error(err);
        if( res ) {
          app.model.user.load(function(){
            app.view.editions.dirty=true
          })
        }
      })
    }


    window.plugins.inAppPurchaseManager.onFailed = function(errno, errtext) {
      if( self.apple.state.spinner ) { self.apple.state.spinner.stop() }

      navigator.notification.alert( errtext, function(){}, 'Purchase Failed', 'Dismiss')
      app.view.purchase.inprogress=false

      util.http_post('/api/apple/failed', {      
        when: new Date().getTime(),
        apple: {
          errno:errno,errtext:errtext
        }
      }, function( err, res ) {
        if( err ) return self.error(err);
        if( res ) {
          
        }
      })
      
    }

  }
 
}


// spec = { codemap:{area:codes[{name:}]}, slotmap:{code:jQuery}, build:function(code) }
function AdManager(spec) {
  var self = this
  
  self.callcount = 0
  self.spec = spec
  self.queue = []

  if( $.writeCapture ) {
    // TO BE TESTED
    //$.writeCapture.writeOnGetElementById = true
  }


  self.showafter = function(delay) {
    log('cc:',self.callcount)

    if( self.callcount < 2 ) return;

    setTimeout(function(){
      if( self.lastspec ) {
        self.show(self.lastspec)
      }
    },delay)
  }

  self.checkqueue = function() {
    if( 0 < self.queue.length ) {
      self.show(self.queue.shift())
    }
  }

  // adspec = {area:,}
  self.show = function(adspecs) {
    var nowshowtime = new Date().getTime()
    if( self.lastshowtime && (nowshowtime-self.lastshowtime) < (1000+1000*Math.random()) ) {
      self.queue.push(adspecs)
      setTimeout(self.checkqueue,(1000+2000*Math.random()))
      return;
    }

    self.lastshowtime = nowshowtime

    if( adspecs ) {
      self.lastspec = adspecs
    }
    else {
      adspecs = self.lastspec
    }
    
    if( !adspecs ) return;

    self.callcount++;

    if( !_.isArray(adspecs) ) {
      adspecs = [adspecs]
    }

    for( var asI = 0; asI < adspecs.length; asI++ ) {
      var adspec = adspecs[asI]
      var codes = self.spec.codemap[adspec.area]
      if( codes ) {
        for( var cI = 0; cI < codes.length; cI++ ) {
          var code = codes[cI]
          log('ADCODE:'+adspec.area+':'+code.code)

          var html = self.spec.build(code)
          if( html ) {
            var slots = self.spec.slotmap[code.name]

            if( !slots ) {
              var prefix = adspec.area.split('-')[0]
              if( prefix ) {
                slots = self.spec.slotmap[prefix+'-*']
              }

              if( !slots ) {
                slots = self.spec.slotmap['*']
              }
            }

            if( slots ) {
              for( var sI = 0; sI < slots.length; sI++ ) {
                var slot = slots[sI]

                if( html && slot ) {
                  util.tick(function(slot,html){
                    return function(){
                      var slot_id = 'adslot_'+Math.random()
                      var inject = $('<div>').attr('id',slot_id)
                      slot.empty().append(inject)

                      if( spec.writeCapture && slot.writeCapture ) {
                        //log(slot_id,html)
                        inject.writeCapture().html(html)
                      }
                      else {
                        inject.html(html)
                      }
                    }
                  }(slot,html))
                }

                self.spec.postbuild(slot)
              }
            }
          }
        }
      }
    }
  }

}



