﻿/*
* Puretracks Fast-Brand Client Library
*
* Copyright © 2010, Puretracks, a division of Somerset Entertainment Ltd.
* All rights reserved.
* http://corporate.puretracks.com/
*
* Auhor: Roman Gubarenko
*/


/* 
* Async Action Mechanism Utils
*/

(function($)
{
  //
  // Encode client data to transfer as action parameter
  //
  // data - array of objects that you wish to encode
  //
  $.FBEncodeClientData = function(data)
  {
    if (data == null) return "|0|";
    else if (typeof (data) == "string") return "|" + data.length + "|" + data;
    else if (data.constructor == Array)
    {
      var result = "";
      for (var i = 0; i < data.length; i++)
      {
        result += $.FBEncodeClientData(data[i]);
      }
      return result;
    }
    else throw "Invalid client data";
  },

  //
  // Rise action resulting in async postback.
  //
  // scopeID - id of the update panel that the action is associated with
  // actionName - name of the action using which the system calls a handler
  // actionArgs - array of stringifiable object to pass to action handler as params
  //
  $.FBAsyncAction = function(scopeID, actionName, actionArgs)
  {
    var target = scopeID;
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (!Array.contains(prm._asyncPostBackControlIDs, target)) prm._asyncPostBackControlIDs.push(target);
    if (!Array.contains(prm._asyncPostBackControlClientIDs, target)) prm._asyncPostBackControlClientIDs.push(target);
    __doPostBack(target, "" + actionName + "|" + $.FBEncodeClientData(actionArgs));
  }
})(jQuery);


(function($)
{
  var staticMembers =
  {
    _isListening: false,
    _refreshHandlers: new Array()
  };


  //
  // Install listener callback for refresh of specific update panel.
  // The tool becomes extremely useful whe we need to execute certain
  // activities when a specific update panel is refreshed.
  //
  // updatePanelID - id of the update panel to listen
  // callback - function pointer to execute on refresh
  //
  $.FBAddAsyncRefreshHandler = function(updatePanelID, callback)
  {
    if (typeof (updatePanelID) != "string" || typeof (callback) != "function")
      throw "FBAddAsyncRefreshHandler: Invalid plugin function params";

    // install update panel refresh listener
    if (!staticMembers._isListening)
    {
      var prm = Sys.WebForms.PageRequestManager.getInstance();

      prm.add_pageLoaded(function(sender, args)
      {
        $.each(args.get_panelsUpdated(), function(idx, elem)
        {
          if (elem.id == updatePanelID)
          {
            var handler = staticMembers._refreshHandlers[updatePanelID];
            if (handler) handler();
          }
        });
      });

      staticMembers._isListening = true;
    }

    // populate list of refresh handlers
    staticMembers._refreshHandlers[updatePanelID] = callback;

    $.log("FBAddAsyncRefreshHandler: Async refresh handler added for: " + updatePanelID);
  }
})(jQuery);


/* 
* Misc Platform Utils
*/

(function($)
{
  //
  // Generate random alphanumeric string token. Useful when
  // you need to get some pretty looking unique id.
  //
  // length - length of string in characters
  //
  $.FBGetRandomToken = function(length)
  {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var result = "";
    for (var i = 0; i < length; i++) result += chars.substr(Math.floor(Math.random() * 36), 1);
    return result;
  }
})(jQuery);


/*
* FBStartThemeroller jQuery Plugin v1.1
*
* Manages jQuery Theme Roller application within FastBrand platform.
*
*/

; (function($)
{
  var ctx =
  {
    _token: $.FBGetRandomToken(10),
    _themeConfig: null,
    _reloadTimer: null
  };

  $.FBStartThemeroller = function(options)
  {
    // allow this plugin to run only in Firefox!
    if (!/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
    {
      alert("Due to security restrictions, you can run this tool only in Firefox");
      return;
    }

    var settings = { cssScope: "" };
    $.extend(settings, options);

    var containerID = "jQuery_themeroller_container_" + ctx._token;
    var csslinkID = "jQuery_themeroller_csslink_" + ctx._token;

    if ($("#" + containerID).size() > 0)
    {
      $("#" + containerID).fadeIn();
    }
    else
    {
      $('<div id="' + containerID + '" style="display: none; position: fixed; background: #111; top: 25px; right: 25px; padding: 22px 0 15px 4px;width: 245px;height:400px; -webkit-border-radius: 6px; -moz-border-radius: 6px; z-index: 9999999;"><a href="#" class="closetr" style="font-family: verdana, sans-serif; font-size: 10px; display: block; position: absolute; right: 0; top: 2px; text-align: right; background: url(http://jqueryui.com/themeroller/developertool/icon_bookmarklet_close.gif) 0 2px no-repeat; width: 16px;height: 16px; color: #fff; text-decoration: none;" title="close themeroller"></a><iframe name="trapp" src="http://jqueryui.com/themeroller/developertool/appinterface.php" style="background: transparent; overflow: auto; width: 240px;height:100%;border: 0;" frameborder="0" ></iframe></div>')
        .appendTo('body')
       	.draggable({
       	  start: function()
       	  {
       	    $("<div class='dragdivcover' />").appendTo('#' + containerID).css({ width: $(this).width(), height: $(this).height(), position: 'absolute', top: 0, left: 0 });
       	  },
       	  stop: function()
       	  {
       	    $("#" + containerID + " .dragdivcover").remove();
       	  },
       	  opacity: 0.6,
       	  cursor: 'move'
       	})
        .find('a.closetr').click(function()
        {
          if (ctx._token) $("#" + containerID).fadeOut();
          if (ctx._reloadTimer)
          {
            clearTimeout(ctx._reloadTimer);
            ctx._reloadTimer = null;
          }
        })
        .end()
        .find('.ui-resizable-s').css({
          background: 'url(http://jqueryui.com/themeroller/developertool/icon_bookmarklet_dragger.gif) 50% 50% no-repeat',
          border: 'none',
          height: '14px',
          dipslay: 'block',
          cursor: 'resize-s',
          bottom: '-3px'
        })
        .end()
        .css('cursor', 'move')
        .fadeIn();
    }

    var fnReloadCSS = function()
    {
      $.log("FBStartThemeroller: reloading CSS");

      var themeConfig = window.location.hash;
      if (themeConfig.indexOf("#") >= 0) themeConfig = themeConfig.split("#")[1];

      if (themeConfig != "" && themeConfig != ctx._themeConfig)
      {
        $("head #" + csslinkID).remove();
        $("head").append('<link id="' + csslinkID + '" href="jQueryThemeStylesheet.axd?cssScope=' + settings.cssScope + '&themeConfig=' + encodeURIComponent(themeConfig) + '" type="text/css" rel="stylesheet" />');
        ctx._themeConfig = themeConfig;

        $.log("FBStartThemeroller: CSS has been updated!");
      }

      ctx._reloadTimer = window.setTimeout(fnReloadCSS, 2000);
    };

    $.log("FBStartThemeroller: themeroller started: " + containerID);

    // initial call to start the timer
    fnReloadCSS();
  }
})(jQuery);


/*
* Custom fix to disable functional areas of packshot for Not Available products
*/

; (function($)
{
  $(document).ready(function()
  {
    $("img.packshot_img[src$=na_medium.gif]").each(function()
    {
      $(this).parent("a").attr("href", "javascript:void(0)");
      $(this).parent("a").parent("td").next("td").html("<div class='blurb_text'>Sorry, this product is no longer available for sale.</div>");
    })
  });
})(jQuery);
