/* vim: set ts=2 sw=2 sts=2 et: */
/**
 * Common controller
 *
 * @category   X-Cart
 * @package    X-Cart
 * @subpackage JS Library
 * @author     Ruslan R. Fazlyev <rrf@x-cart.com>
 * @version    $Id: controller.js 117 2011-02-25 19:30:13Z max $
 * @link       http://www.x-cart.com/
 * @see        ____file_see____
 */

function xauthTogglePopup(link, mode)
{
  xauthLoadingChecker(true);

  return !popupOpen(
    'xauth_layer.php' + (mode ? '?mode=' + mode : ''),
    null,
    {
      width: 435,
      height: 285,
      closeOnEscape: true
    }
  );
}

function xauthLoadingChecker(reset)
{
  if (reset) {
    arguments.callee.counter = 0;
  }

  if (0 < jQuery('.xauth-popup-rpx iframe').length) {
    jQuery('.xauth-popup-rpx iframe').load(
      function() {
        jQuery('.xauth-bg-loading').remove();
      }
    );

  } else if (100 > arguments.callee.counter) {
      setTimeout(arguments.callee, 300);
      arguments.callee.counter++;
  }
}
xauthLoadingChecker.counter = 0;

function xauthOpenProductShare(button)
{
  var product = jQuery('.big_box .box_title:eq(0)').text();
  var description = jQuery('form[name=orderform] table:eq(0) table:eq(0) tr td:eq(0)').text();

  if (!product) {
    return false;
  }

  RPXNOW.language_preference = xauth_rpx_language;
  RPXNOW.ssl = 'https' == xauth_http_protocol;

  RPXNOW.loadAndRun(
    ['Social'],
    function () {
      var activity = new RPXNOW.Social.Activity(
        xauthRPXEscape(lbl_xauth_rpx_share_comment),
        xauthRPXEscape(substitute(lbl_xauth_rpx_look_this_product, 'product', product)),
        self.location + ''
      );

      activity.setTitle(xauthRPXEscape(lbl_xauth_rpx_share_comment));
      activity.setDescription(xauthRPXEscape(description ? description : product));
      activity.addActionLink(xauthRPXEscape(product), self.location + '');

      var image = jQuery('#product_thumbnail');
      var images = jQuery('.dpimages-icons-box a');

      if (0 < image.length) {
        var imc = new RPXNOW.Social.ImageMediaCollection();

        imc.addImage(xauthRPXPrepareURL(image.attr('src')), self.location + '');

        if (0 < images.length) {
          images.each(
            function() {
              var i = jQuery(this);
              imc.addImage(xauthRPXPrepareURL(i.attr('href')), self.location + '');
            }
          );
        }

        activity.setMediaItem(imc);
      }

      RPXNOW.Social.publishActivity(
        activity,
        {
          urlShortening: true
        }
      );
    }
  );

  return true;
}

function xauthOpenCartItemShare(elm)
{
  var tbl = jQuery(elm).parents('form[name=cartform]').eq(0);
  if (tbl.length) {
    var f = tbl.get(0);
    if (!f.xauthProcessed) {
      var rows = jQuery('table', f).get(0).rows;
      for (var i = 0; i < rows.length; i++) {
        jQuery(rows[i]).addClass('xauth-cart-row');
      }

      f.xauthProcessed = true;
    }
  }

  tbl = jQuery(elm).parents('.xauth-cart-row').eq(0);

  var product = jQuery('font.ProductTitle', tbl).text();
  var description = jQuery('table td:eq(1) > table:eq(0) td:eq(0)', tbl).text();
  var url = jQuery('td.PListImgBox a', tbl).attr('href');

  if (!tbl.length || !product || !url) {
    return false;
  }

  if (url.search(/^\//) != -1) {
    url = 'http://' + xauth_current_host + url;

  } else if (url.search(/^https?:\/\//) == -1) {
    url = xauth_catalogs_customer + '/' + url;
  }

  RPXNOW.language_preference = xauth_rpx_language;
  RPXNOW.ssl = 'https' == xauth_http_protocol;

  RPXNOW.loadAndRun(
    ['Social'],
    function () {
      var activity = new RPXNOW.Social.Activity(
        xauthRPXEscape(lbl_xauth_rpx_share_comment),
        xauthRPXEscape(substitute(lbl_xauth_rpx_look_this_product, 'product', product)),
        url
      );

      activity.setTitle(xauthRPXEscape(lbl_xauth_rpx_share_comment));
      activity.setDescription(xauthRPXEscape(description ? description : product));
      activity.addActionLink(xauthRPXEscape(product), url);

      var image = jQuery('td.PListImgBox a img', tbl);

      if (0 < image.length) {
        var imc = new RPXNOW.Social.ImageMediaCollection();
        imc.addImage(xauthRPXPrepareURL(image.attr('src')), url);
        activity.setMediaItem(imc);
      }

      RPXNOW.Social.publishActivity(
        activity,
        {
          urlShortening: true
        }
      );
    }
  );

  return true;
}

function xauthOpenInvoiceShare(elm)
{
  RPXNOW.language_preference = xauth_rpx_language;
  RPXNOW.ssl = 'https' == xauth_http_protocol;

  RPXNOW.loadAndRun(
    ['Social'],
    function () {
      var activity = new RPXNOW.Social.Activity(
        xauthRPXEscape(lbl_xauth_rpx_share_comment),
        xauthRPXEscape(lbl_xauth_rpx_invoice_share_note),
        xauthRPXEscape(xauth_catalogs_customer)
      );

      activity.setTitle(xauthRPXEscape(lbl_xauth_rpx_share_comment));

      RPXNOW.Social.publishActivity(
        activity,
        {
          urlShortening: true
        }
      );
    }
  );

  return true;
}

function xauthRPXEscape(str)
{
  str = str.substr(0, 1600);

  var len = str.length;
  var collect = '';
  var c, x, n;

  for (var i = 0; i < len; i++) {
    n = str.charCodeAt(i);

    if (n <= 127) {
        collect += str.substr(i, 1);

    } else {
        c = n.toString(16);
        for (x = c.length; x < 4; x++) {
          c = '0' + c;
        }
        collect += '\\u' + c;
    }
  }

  return collect;
}

function xauthRPXPrepareURL(url)
{
  if (url.substr(0, 1) == '/') {
    url = self.location.protocol + '//'
      + self.location.host
      + (self.location.port ? ':' + self.location.port : '')
      + url

  } else if (-1 == url.search(/^https?:\/\//)) {
    url = self.location.protocol + '//'
      + self.location.host
      + (self.location.port ? ':' + self.location.port : '')
      + self.location.pathname.replace(/\/[^\/]+\.(php|html|htm)$/, '') + '/' + url;
  }

  return url;
}

setTimeout(
  function() {
    jQuery(document).ready(
      function() {
        if (jQuery('#dialog-message .xauth-err').length) {
          jQuery('#dialog-message').clearQueue();
        }

        jQuery('a,input,button').filter(
          function() {
            return 'undefined' != typeof(this.onclick)
              && this.onclick
              && this.onclick.toString().search(/popupOpen..login\.php../) != -1;
          }
        ).click(
          function() {
            xauthLoadingChecker(true);
          }
        );

        var surl = self.location + '';
        if (
          surl.search(/login.php/) != -1
          || surl.search(/error_message.php.+need_login/) != -1
        ) {
          xauthLoadingChecker(true);
        }
      }
    );
  },
  500
);

