if (!window.VK) window.VK = {};
if (!VK.Merchant) {
  VK.Merchant = {
    _popups: [],
    _gens: [],
    _base_domain: '',
    _ge: function(id) {
      return document.getElementById(id);
    },
    button: function(gen, but, index) {
      if (!but) but = {type: 'round'};
      if (but === but.toString()) but = {type: 'round', text: but};
      if (!but.text) but.text = 'Оплатить';
      if (!but.text_right) but.text_right = 'Контакте';
      return VK.Merchant.btn(gen, but, 'VK.Merchant.click', index);
    },
    wishbutton: function(gen, but, index) {
      if (!but) but = {type: 'round'};
      if (but === but.toString()) but = {type: 'round', text: but};
      if (!but.text) but.text = 'Хочу';
      if (!but.text_right) but.text_right = 'Подарок';
      return VK.Merchant.btn(gen, but, 'VK.Merchant.wishclick', index);
    },
    btn: function(gen, but, onclick, index) {
      if (index === undefined) {
        this._gens.push(gen);
        this._popups.push(false);
        index = this._popups.length - 1;
      } else {
        this._gens[index] = gen;
      }
      if (but.type == 'button') {
        return '<table cellspacing="0" cellpadding="0" id="vkpay' + index + '" onmouseover="VK.Merchant.change(1, ' + index + ');" onmouseout="VK.Merchant.change(0, ' + index + ');" onmousedown="VK.Merchant.change(2, ' + index + ');" onmouseup="VK.Merchant.change(1, ' + index + ');" onclick="' + onclick + '(' + index + ');" style="position: relative; width: auto; cursor: pointer; border: 0px;"><tr style="line-height: normal;"><td></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #3b6798;"><div style="border: 1px solid #5c82ab; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 4px 0px 6px; font-family: tahoma; font-size: 10px;">' + but.text + '</div></div></td>' +
               '<td style="vertical-align: middle;"><div style="background: url(http://vk.com/images/btns.png) 0px -42px no-repeat; width: 21px; height: 21px"></div></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #3b6798;"><div style="border: 1px solid #5c82ab; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 6px 0px 4px; font-family: tahoma; font-size: 10px;">' + but.text_right + '</div></div></td><td></td>' +
               '</tr></table>';
      } else if (but.type == 'round') {
        return '<table cellspacing="0" cellpadding="0" id="vkpay' + index + '" onmouseover="VK.Merchant.change(1, ' + index + ');" onmouseout="VK.Merchant.change(0, ' + index + ');" onmousedown="VK.Merchant.change(2, ' + index + ');" onmouseup="VK.Merchant.change(1, ' + index + ');" onclick="' + onclick + '(' + index + ');" style="position: relative; width: auto; cursor: pointer; border: 0px;"><tr style="line-height: normal;">' +
               '<td style="vertical-align: middle;"><div style="height: 21px; width: 2px; background: url(http://vk.com/images/btns.png) no-repeat -21px -42px;"></div></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #3b6798; border-left: 0px;"><div style="border: 1px solid #5c82ab; border-left: 0px; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 4px 0px 6px; font-family: tahoma; font-size: 10px;">' + but.text + '</div></div></td>' +
               '<td style="vertical-align: middle;"><div style="background: url(http://vk.com/images/btns.png) 0px -42px no-repeat; width: 21px; height: 21px"></div></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #3b6798; border-right: 0px;"><div style="border: 1px solid #5c82ab; border-right: 0px; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 6px 0px 4px; font-family: tahoma; font-size: 10px;">' + but.text_right + '</div></div></td>' +
               '<td style="vertical-align: middle;"><div style="height: 21px; width: 2px; background: url(http://vk.com/images/btns.png) no-repeat -21px -63px;"></div></td>' +
               '</tr></table>';
      } else {
        return '<span style="position: relative; cursor: pointer" onclick="' + onclick + '(' + index + ')">' + but.text + '</span>';
      }
    },
    change: function(state, index) {
      var row = this._ge('vkpay' + index).rows[0];
      var elems = [row.cells[1].firstChild.firstChild, row.cells[3].firstChild.firstChild];
      for (var i = 0; i < 2; ++i) {
         var elem = elems[i];
        if (state == 0) {
          elem.style.backgroundColor = '#6d8fb3';
          elem.style.borderTopColor = '#7e9cbc';
          elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#5c82ab';
        } else if (state == 1) {
          elem.style.backgroundColor = '#84a1bf';
          elem.style.borderTopColor = '#92acc7';
          elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#7293b7';
        } else if (state == 2) {
          elem.style.backgroundColor = '#6688ad';
          elem.style.borderBottomColor = '#7495b8';
          elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderTopColor = '#51779f';
        }
      }
      var elems = [row.cells[0].firstChild, row.cells[4].firstChild];
      for (var i = 0; i < 2; ++i) {
        var elem = elems[i];
        if (elem) {
          if (state == 0) {
            elem.style.backgroundPosition = '-21px -' + (42 + i * 21) + 'px';
          } else if (state == 1) {
            elem.style.backgroundPosition = '-23px -' + (42 + i * 21) + 'px';
          } else if (state == 2) {
            elem.style.backgroundPosition = '-25px -' + (42 + i * 21) + 'px';
          }
        }
      }
      if (state == 0 || state == 2) {
        row.cells[2].firstChild.style.backgroundPosition = '0px -42px';
      } else if (state == 1) {
        row.cells[2].firstChild.style.backgroundPosition = '0px -63px';
      }
    },
    click: function(index) {
      var details = (this._gens[index].prototype && this._gens[index].prototype.toString.call(this._gens[index]) === '[object Function]') ? this._gens[index]() : this._gens[index];
      if (!details || !details.items || !details.items.length) return;

      var params = {act: 'auth'};
      var fields = ['merchant_id', 'layout', 'fail_url', 'success_url', 'required_fields'];
      for (var i = 0; i < fields.length; ++i) {
        if (details[fields[i]]) {
          params[fields[i]] = details[fields[i]];
        }
      }
      for (var i = 0; i < details.items.length; ++i) {
        for (var j in details.items[i]) {
          params['item_' + j + '_' + i] = details.items[i][j];
        }
      }
      for (var i in details.custom) {
        i = parseInt(i) || 0;
        if (i >= 0 && i < 10) {
          params['custom_' + i] = details.custom[i];
        }
      }
      if (!params.merchant_id || !params.fail_url || !params.success_url) return;
      var url = details.testmode ? 'paytest.php' : 'pay.php';

      VK.Merchant.popup(index, url, params, {width: 554, height: 349});
    },
    wishclick: function(index) {
      var details = (this._gens[index].prototype.toString.call(this._gens[index]) === '[object Function]') ? this._gens[index]() : this._gens[index];
      if (!details || !details.item_id || !details.merchant_id) return;

      var params = {act: 'auth'};
      var fields = ['merchant_id', 'item_id', 'item_name', 'item_description', 'item_currency', 'item_price', 'shipping_price', 'item_photo_url', 'item_category', 'item_tags', 'item_digital', 'sig'];
      for (var i in fields) {
        if (details[fields[i]] !== window.undefined) {
          params[fields[i]] = details[fields[i]];
        }
      }
      var url = details.testmode ? 'wishlisttest.php' : 'wishlist.php';

      VK.Merchant.popup(index, url, params, {width: 554, height: 349});
    },
    popup: function(index, url, params, options) {
      var popupName = 'vkpay' + params.merchant_id + '_' + index;
      var width = options.width || 554;
      var height = options.height || 349;
      var left = (screen.width - width) / 2;
      var top = (screen.height - height) / 2;
      var popupParams = 'scrollbars=0, resizable=1, menubar=0, left=' + left + ', top=' + top + ', width=' + width + ', height=' + height + ', toolbar=0, status=0';
      var popup = this._popups[index] = window.open('', popupName, popupParams);
      try {       
        if (!this._base_domain) {
          for (var elem = document.getElementsByTagName('head')[0].firstChild; elem; elem = elem.nextSibling) {
            var m;
            if (elem.tagName && elem.tagName.toLowerCase() == 'script' && (m = elem.src.match(/(http:\/\/(?:[a-z0-9_\-\.]*\.)?(?:vk\.com|vkontakte\.ru)\/)js\/api\/merchant\.js(?:\?|$)/))) {
              this._base_domain = m[1];
            }
          }
        }
        if (!this._base_domain) {
          this._base_domain = 'http://vkontakte.ru/';
        }
        var text = '<form accept-charset="UTF-8" action="' + this._base_domain + url + '" method="POST" id="auth_form">';
        for (var i in params) {
          text += '<input type="hidden" name="' + i + '" value="' + params[i].toString().replace(/"/g, '&quot;') + '" />';
        }
        text += '</form>';
        text += '<script type="text/javascript">document.getElementById("auth_form").submit()</script>';

        text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' +
               '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' +
               '<head><meta http-equiv="content-type" content="text/html; charset=windows-1251" /></head>' +
               '<body>' + text + '</body></html>';
        popup.document.write(text);
      } catch (e) {
      }
      popup.blur();
      popup.focus();
    }
  }
}