settings = require("../../../config/settings").settings
dispatcher = require('../../common/js/dispatcher')

origin_city = ''
googletag = window.googletag
locale = LOCALE
google_csa_channel = settings.google_csa_channel
mouse_over_ads = false

csa_page_options =
  channel: google_csa_channel
  pubId: "pub-0240520437227076"
  hl: locale
  domainLinkAboveDescription: true
  instantPreviews: false
  location: false
  plusOnes: false
  sellerRatings: false
  siteLinks: false
  linkTarget: '_blank'
csa_adblocks = [{
  destination_city: ''
  params:
    container: "ad_top_container"
    minTop: 1
    width: "640px"
    fontSizeTitle: 13
    fontSizeDescription: 13
    colorBackground: "#FFFFFF"
    colorTitleLink: "#000000"
    colorDomainLink: "#000000"
    colorText: "#222222"
    colorLocation: "#000000"
    fontFamilyAttribution: "Arial"
    noTitleUnderline: true
    detailedAttribution: false
    adLoadedCallback: (id, ads_loaded) ->
      console.log('no ads loaded') unless ads_loaded
    }, {
    destination_city: ''
    params:
      container: "adsense_right_column"
      number: 2
      width: "230px"
      fontSizeTitle: 13
      fontSizeDescription: 12
      colorBackground: "#F1F1F1"
      colorTitleLink: "#000"
      colorAnnotation: "#000"
      colorDomainLink: "#000"
      colorText: "#222222"
      colorLocation: "#5f5f5f"
      fontFamilyAttribution: "Arial"
      noTitleUnderline: true
      detailedAttribution: false
      adLoadedCallback: (id, ads_loaded) ->
        console.log('ADS_LOADED:', ads_loaded);
        nodes = document.getElementById(id)
        iframe = nodes.querySelector('iframe')
        iframe.addEventListener 'mouseover', ->
          mouse_over_ads = 'top'
        iframe.addEventListener 'mouseout', ->
          mouse_over_ads = undefined
  }
]

show_google_csa = (params) ->
  new_destination_city = params.segments[0].destination_name
  if csa_adblocks[0].destination_city != new_destination_city
    _.each csa_adblocks, (adblock) -> adblock.destination_city = new_destination_city
    csa_page_options.query = __("google_csa_query").replace("%{destination_city}", new_destination_city)
    params = ["ads", csa_page_options, csa_adblocks[0].params, csa_adblocks[1].params]
    _googCsa.apply this, params

show_doubleclick = (params) ->
  new_origin_city = params.segments[0].origin_name
  if new_origin_city != origin_city
    origin_city = new_origin_city
    googletag.cmd.push ->
      googletag.pubads().setTargeting('orgn_city', origin_city)
      googletag.display('div-gpt-ad-1407312614252-0')

dispatcher.on 'start_search', (e, {params}, source) ->
  return if source is 'parser' # and wait for places_restored event.
  show_google_csa params
  show_doubleclick params

dispatcher.on 'places_restored', (e, params) ->
  show_google_csa params
  show_doubleclick params
