﻿
// Cross domain popup widget.
// Script is hosted on the SERVICE side and used by the HOST side to load cross domain window
// Developer: Albert Ribakovsky

/*
USAGE SAMPLE


    <!--EMBED WIDGET-->
    <script type="text/javascript" src="http://ofek/common/lms/tasks/widget/iframe/service/JS/widget.js" id="cdi_src"></script>
    <!--EMBED WIDGET-->

    <!--INCLUDE WIDGET 1-->
    <script type="text/javascript" src="http://ofek/common/lms/tasks/widget/iframe/service/JS/widget.js"></script>
    <script type="text/javascript">
      //supply widget codebase to download needed resources
      cdi.config.widgetBase = "http://ofek/common/lms/tasks/widget/iframe/service/";
    </script>
    <!--INCLUDE WIDGET 1-->

    <!--INCLUDE WIDGET 2-->
    <script type="text/javascript" src="http://ofek/common/lms/tasks/widget/iframe/service/JS/jquery.min.js"></script>
    <script type="text/javascript" src="http://ofek/common/lms/tasks/widget/iframe/service/JS/json2.js"></script>
    <link type="text/css" rel="stylesheet" href="http://ofek/common/lms/tasks/widget/iframe/service/css/widget.css">
    <script type="text/javascript" src="http://ofek/common/lms/tasks/widget/iframe/service/JS/widget.js" id="Script2"></script>
    <!--INCLUDE WIDGET 2-->

    <script type="text/javascript">
    function OpenWindow() {
      
          cdi.Open({
            UseSSO: false,
            HtmlInteraction: $("#htmlData").html(),
            ID: "cc6f03a5-5ea6-4028-bf43-05f996f65176",
            Item: {
              ID: 30,
              Name: "שם הפריט",
              Source: "כותר"
            }
          });
        }
    </script>
*/

var cdi = {


  widgetName: "cdi",

  settings:
    {
      Width: "90%",
      Height: "90%",
      TaskSource: "ofek",
      ID: 0,
      Title: "",
      HtmlInteraction: "",
      TopicID: 0,
      Item: {
        ID: "",
        Name: "",
        Source: ""
      },
      ReturnUrl: "",
      ReturnTitle: "",
      Culture: "he",
      IframePosition: "absolute",
      XdHelperPath: "xd_helper.htm?ver=3",
      ScriptPath: "ofek",
      OnFinishCallback: null,
      ClientBaseUrl: "",
      UseSSO: true,
      ShowSchoolSelection : false
    },

  //INSTALL WIDGET
  //*******************************************************
  config:
    {
      jQueyUrl: "js/jquery.min.js",
      jsonUrl: "js/json2.js",
      cssUrl: "css/widget.css",
      timer: null,
      isFirstTime: true,
      widgetBase: "",
      initData: null,
      isInstalled: false,
      isEmbed: false
    },

  Init: function (data)
  {

    this.config.initData = data;

    var embedTag = document.getElementById(this.widgetName + "_src");

    if (embedTag)
    {
      //if widget is embeded on the page, get BASECODE url to download needed resources from the widget location
      //otherwise the host page must supply dependency resources or widget BASECODE url

      this.config.isEmbed = true;
      this.config.widgetBase = document.getElementById(this.widgetName + "_src").getAttribute("src").toLowerCase().replace("js/widget.js", "");
    }
    this.AddEvent(window, "load", function () { cdi.Install() });
  },
  Install: function ()
  {

    if (this.config.widgetBase)
    {

      if (!this.IsJQueryExist())
      {
        this.ImportScript(this.config.widgetBase + this.config.jQueyUrl, "myJQuery");
      }
      if (!this.IsJsonExist())
      {
        this.ImportScript(this.config.widgetBase + this.config.jsonUrl, "myJson");
      }

      var cssUrl = this.config.widgetBase + this.config.cssUrl;
      this.ImportStyle(cssUrl, "myWidgetCss");

    }

    clearInterval(this.config.timer);
    this.config.timer = setInterval(this.widgetName + ".CheckInstallStatus()", 200);

  },
  IsInstalled: function ()
  {
    return this.config.isInstalled;
  },
  IsJsonExist: function ()
  {
    return (typeof (JSON) == "object");
  },
  IsJQueryExist: function ()
  {
    return (typeof (jQuery) == "function");
    //return ((typeof (jQuery) == "function") && (typeof (jQuery.noop) == "function")); // checks for jQuery version, later than or equal to 1.4
  },
  ImportScript: function (url, id)
  {
    var item = document.createElement("script");
    item.src = url;
    item.type = "text/javascript";
    item.defer = true;
    item.id = id;
    var head = document.getElementsByTagName("head").item(0);
    if (head)
      head.appendChild(item);
    else
      document.body.appendChild(item);
  },
  ImportStyle: function (url, id)
  {

    var item = document.createElement("link");
    item.href = url;
    item.type = "text/css";
    item.rel = "stylesheet";
    item.id = id;
    var head = document.getElementsByTagName("head").item(0);
    if (head)
      head.appendChild(item);
    else
      document.body.appendChild(item);
  },
  AddEvent: function (obj, evt, func)
  {
    if (document.addEventListener)
      obj.addEventListener(evt, func, false);
    else if (document.attachEvent)
      obj.attachEvent("on" + evt, func);
    else
      eval(obj + ".on" + evt + "=" + func);
  },
  CheckInstallStatus: function ()
  {

    if (this.IsJQueryExist() && this.IsJsonExist())
    {
      clearInterval(this.config.timer);
      this.OnDocumentReady();
    }
  },
  //*******************************************************



  //WIDGET PUBLIC MEMBERS
  //*******************************************************
  OnDocumentReady: function ()
  {
    this.ExtendSettings(this.config.initData);

    this.InitBaseObjects();

  },
  Open: function (data)
  {
    this.EscapeStringData(data);

    this.ExtendSettings(data);

    this.LoaderShow();

    this.PostData();
  },
  //*******************************************************


  //WIDGET PRIVATE MEMBERS
  //*******************************************************
  ExtendSettings: function (data)
  {
    $.extend(this.settings, data);
    if (!this.settings.ClientBaseUrl || this.settings.ClientBaseUrl == "")
    // Get ClientBaseUrl from document.location if hasn't been initialized
    {
      this.settings.ClientBaseUrl = document.location.href;
    }

  },
  EscapeStringData: function (data)
  {
    if (data.Title)
    {
      data.Title = escape(data.Title);
    }
    if (data.HtmlInteraction)
    {
      data.HtmlInteraction = escape(data.HtmlInteraction);
    }
    if (data.ReturnUrl)
    {
      data.ReturnUrl = escape(data.ReturnUrl);
    }
    if (data.ReturnTitle)
    {
      data.ReturnTitle = escape(data.ReturnTitle);
    }

  },
  InitBaseObjects: function ()
  {
    var item = document.createElement("iframe");

    $('<iframe id="' + this.widgetName + '_iframe" name="' + this.widgetName + '_iframe" frameborder="no" allowtransparency="true">')
            .appendTo("body");

    $('<div id="' + this.widgetName + '_loader"></div>')
            .appendTo("body");

    $('<form action="' + this.config.widgetBase + 'default.aspx"></form>')
            .attr("method", "post")
            .attr("id", this.widgetName + "_form")
            .attr("target", this.widgetName + "_iframe")
            .append('<input id="' + this.widgetName + '_data" type="hidden" name="data" />')
    //.append('<input type="submit" />')
            .appendTo("body");

  },
  LoaderShow: function ()
  {
    var w = $(window).width();
    var h = $(window).height();

    var loader = $("#" + this.widgetName + "_loader");
    loader.css("left", (w - loader.width()) / 2 + "px");
    loader.css("top", (h - loader.height()) / 2 + "px");
    loader.css("opacity", 0.8)
            .fadeIn("fast");
  },
  LoaderHide: function ()
  {
    var loader = $("#" + this.widgetName + "_loader");
    loader.fadeOut("fast");
  },
  PostData: function ()
  {

    var w = $(window).width();
    var h = $(window).height();

    var win = $("#" + this.widgetName + "_iframe");
    win.css("left", "-100000px").css("top", "-100000px");
    win.css("width", w + "px").css("height", h + "px");
    win.show();

    var data = JSON.stringify(this.settings);

    $("#" + this.widgetName + "_data").val(data);

    if (this.settings.IframePosition != null && this.settings.IframePosition != 'undefined')
    {
      $("#" + this.widgetName + "_iframe").css("position", this.settings.IframePosition);
    }

    if (this.settings.UseSSO)
    {

      var ssoFrame = $('<iframe id="sso_iframe" frameborder="no" allowtransparency="true" src="' + this.config.widgetBase + 'SsoPage.aspx" style="width:1px;height:1px;position:absolute">');
      var widgName = this.widgetName;

      // use a temp iframe to make sure current user is login
      //sso is canceled  for add task for allowing post
      ssoFrame.load(function ()
      {
        cdi.SubmitForm();
        ssoFrame.remove();
      });

      ssoFrame.appendTo("body");
    }
    else
    {
      this.SubmitForm();
    }

  },
  SubmitForm: function ()
  {
    $("#" + this.widgetName + "_form").submit();
  },
  WindowShow: function ()
  {

    var win = $("#" + this.widgetName + "_iframe");
    win.css("left", "0px").css("top", "0px");
    //win.fadeIn();
    win.show();

    //Set this timeout cause of the timeout in TaskGeneralGuidlinesControl.ascx -> loadEditorInitialValue()
    //Without this timeout the loadEditorInitialValue function will overrite the user input in the editor
    //setTimeout("cdi.LoaderHide()", 3000);
    cdi.LoaderHide();
  },
  WindowHide: function ()
  {
    this.LoaderHide();

    var win = $("#" + this.widgetName + "_iframe");
    //win.fadeOut("fast");
    win.hide();
  },
  OnFinish: function (value)
  {

    var args = (decodeURIComponent(value));
    if (args)
    {

      var obj = eval("(" + args + ")");

      if (typeof (this.settings.OnFinishCallback) == "function")
      {
        this.settings.OnFinishCallback(obj);
      }
    }
  }
  //*******************************************************


}




function ProccessCommand(cmd, value) {

    switch (cmd) {
        case "load":
            cdi.WindowShow();
            break;
          case "close":
            cdi.WindowHide();
            cdi.OnFinish();
            break;
          case "saving":
            cdi.LoaderShow();
            break;
        case "finish":
            cdi.WindowHide();
            cdi.OnFinish(value);
            break;
    }
}
//*******************************************************


cdi.Init();
