﻿//Open an Dialog
var RichWidgets_Popup_Editor_ShowTimeoutMilSecs = 200;
var RichWidgets_Popup_Editor_HideTimeoutMilSecs = 800;
var RichWidgets_Popup_Editor_InitialWidth = 210;
var RichWidgets_Popup_Editor_InitialHeight = 100;
var RichWidgets_Popup_Editor_notifyWidget;
var RichWidgets_Popup_Editor_Index = 4010;
var RichWidgets_Popup_Editor_ParentUrl;

function RichWidgets_Popup_Editor_init(linkId, notifyId, setTitle, setHeight, setWidth, parentUrl, useModal) {
 var GetLinkHref = function(widget) {
    var linkHref;
    var isAButton = false;
    try {
    //Checks if the id is from a link or not
    linkHref = osjs(widget).attr('href');

    //Tests for visibility/existence
    if (typeof linkHref == 'undefined') {
      var onClick = widget.getAttribute('onclick');
      if (typeof onClick != 'undefined') {
        isAButton = true;
        if (onClick != null) {
          var hrefMatch;
          if((hrefMatch = onClick.toString().match(/href='([^']*)'/)) != null) {
                linkHref = hrefMatch[1];
          }
        }
      }
    } //else: throw ("Inexistent or Invisible button");
   } catch(e) {}
  
   return [linkHref, isAButton];
 }

 osjs().ready(function($) {
  linkId = '#' + linkId;
  var linkWidget;
  try { linkWidget = $(linkId).get(0); } catch(e) {}
  if (typeof linkWidget == 'undefined') {
    //Case the widget is inexistent or invisible, it will show no errors.
    return;
  }
  
  RichWidgets_Popup_Editor_ParentUrl = parentUrl;
    
  var getLinkResult = GetLinkHref(linkWidget);
  var linkHref = getLinkResult[0];
  var isAButton = getLinkResult[1];

  if (typeof linkHref == 'undefined' || linkHref == "" || linkHref == "#" || linkHref.indexOf("javascript:") == 0) {
   try {
       window.OsHandleException(new Error("Popup link id must be the id of a Link or Button Widget with Method Navigate."), $.osErrorCodes.SystemJavascriptError, 'Popup_Editor');
   } catch(e) {}
   return;
  }

  if (isAButton) {
    //remove the existing on-click
    linkWidget.setAttribute('onclick', linkWidget.getAttribute('onclick').toString().replace('window.location.href=', 'return false;window.location.href='));
  }

  // if there's a confirmation message, store in an attribute the result
  if (linkWidget.getAttribute('onclick') != null) {
    linkWidget.setAttribute('onclick', linkWidget.getAttribute('onclick').toString().replace("if( ret != true )", "osjs('" + linkId + "').get(0).setAttribute('confirmed', ret); if( ret != true )"));
  }
  var supportsShadows = !($.browser.msie&&parseInt($.browser.version, 10)<9);

  $(linkWidget).click(function(event) {
   if (linkWidget.getAttribute("confirmed") == 'false') {
     return false;
   }
   if (OsIsIE()) {
     osFocusBackend.ClearFocusedElement();
   }
   var popupDiv = $("<div style='text-align: center; display: none;'></div>").appendTo("body");
   popupDiv.append('<iframe width="100%" scrolling="auto" height="100%" frameborder="0" src="javascript:void(0);"/>');
   var waitText =  " Please wait while content is loading...";
   var imgHTML = "<img style='border-width: 0px; height: 16px; width: 16px;' src='/RichWidgets/img/SpinBlack.gif'/>";
   var pleaseWaitDiv = popupDiv.prepend("<div style='margin-top: 25px;' class='Text_Note'>" + imgHTML + waitText + "</div>")

   OpenPopup(popupDiv, setTitle, setHeight, setWidth, pleaseWaitDiv, linkId );
   RichWidgets_Popup_Editor_notifyWidget = notifyId;
   //load target page
   var ohref = GetLinkHref(linkWidget)[0];
   var rhref = ohref.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + (+ new Date().now) + "$2"); 
   var xhref = rhref + ((rhref == ohref) ? (rhref.indexOf('?') >= 0 ? "&" : "?") + "_=" + (+new Date) : ''); 
   popupDiv.find('iframe').attr('src', xhref); 
   popupDiv.find('iframe').load(function() {
       //after loading try to resize, if it is possible resize also after each ajax call
       if(RichWidgets_Popup_Editor_resize(setWidth, setHeight, true, supportsShadows))
        this.contentWindow.osAjaxBackend.BindAfterAjaxRequest(function(){
            parent.RichWidgets_Popup_Editor_resize(setWidth, setHeight, false, supportsShadows);
            });
   });
   popupDiv = null;
   pleaseWaitDiv = null;
   return false;
  });
  
  function removeDialogShadow(div) {
   if(supportsShadows)
    $(div).parents('.ui-dialog').removeShadow();
  };
  function addDialogShadow(div) {
   if(supportsShadows)
    $(div).parents('.ui-dialog').removeShadow().dropShadow();
  };

  function OpenPopup(divToPopup, setTitle, setHeight, setWidth, divPleaseWait) {
   $(divPleaseWait).show();
   //destroy any previous dialog 
   $('.ui-dialog-content').dialog('close');
   if (setHeight == -1) setHeight = RichWidgets_Popup_Editor_InitialHeight;
   $(divToPopup).show().dialog({
    dialogClass: 'Popup',
    resizable: false,
    autoResize: false,
    bgiframe: true,
    draggable: true,
    autoOpen: true,
    title: setTitle,
    modal: !(useModal === false),
    height: setHeight,
    position: 'center',
    width: ((setWidth == -1) ? RichWidgets_Popup_Editor_InitialWidth: setWidth),
    zIndex: RichWidgets_Popup_Editor_Index,
    dragStart: function() { removeDialogShadow(divToPopup) },
    dragStop: function() { addDialogShadow(divToPopup) },
    close: function() {
     removeDialogShadow(divToPopup);
     $(divToPopup).find('iframe').unbind("load");     
     $(divToPopup).find('iframe').attr('src', 'about:blank');
     setTimeout(function() {
      $(divToPopup).find('iframe').empty();
      $(divToPopup).dialog('destroy');
      $(divToPopup).empty().remove();
     }, 13); //We need to delay this! or IE7 crashes
    }
   });
   $(divToPopup).find('iframe').height(0);
   if (setTitle==" ") {
    $(".ui-dialog-titlebar").height(0);
    $(".ui-dialog-titlebar-close").attr("class","ui-dialog-titlebar-close-no-title").html("").hide();
    $(".ui-dialog").css("overflow","visible");
   } else {
    var titleHeight = $('.ui-dialog-titlebar').height();
    $(divToPopup).parents('.Popup').height(setHeight+titleHeight);
   }
  };
  
 });
}


function RichWidgets_Popup_Editor_resize(setWidth, setHeight, recenter, supportsShadows) {
    var frameObj = osjs('.ui-dialog-content').find('iframe');
    var divToPopup = osjs('.ui-dialog-content');
    osjs(frameObj).css("height", "auto");
    var documentServer = document.location.href.replace(/(https?:\/\/[^\/]*).*/, 'osjs1');
    var frameServer = frameObj[0].src.replace(/(https?:\/\/[^\/]*).*/, 'osjs1');
    var sameOrigin = (frameServer.toLowerCase() == documentServer.toLowerCase() || frameServer.indexOf("http") != 0);
    if (!sameOrigin && (setWidth == -1 || setHeight == -1)) throw (new Error("A Popup with a screen from a different server (or https) needs explicict width, height set."));
    if (sameOrigin) {
        var innerDoc = (frameObj[0].contentDocument) ? frameObj[0].contentDocument : frameObj[0].contentWindow.document;
        if (innerDoc.documentElement.scrollHeight == 0) // strangely this event is also triggered on close
        return false;
    }
 
    osjs(frameObj).height(0);

    var oldHeight = osjs(divToPopup).parents('.Popup').outerHeight();

    var width = ((setWidth == -1) ? innerDoc.documentElement.scrollWidth : setWidth);
    var height = ((setHeight == -1) ? innerDoc.documentElement.scrollHeight : setHeight);
    var titleHeight = osjs('.ui-dialog-titlebar').height();

    // Fix issues with scrollbars
    if (setHeight == -1) {
        // IE7 needs a little more space to remove the scrollbars
        if (osjs.browser.msie) height = height + 1;
    } else { //when explicitly setting the height
        if (sameOrigin) innerDoc.body.style.height = 'auto';
    }

    osjs(divToPopup).height(height);


    //Hide ECT
    osjs(innerDoc).find('.ECT_FeedbackContainer').hide();
    var divPopupOuterWindow = osjs(divToPopup).parents('.Popup');

    var animateFinal = {};

    if (setHeight == -1) {
        var oldTop = parseInt(divPopupOuterWindow.css("top"));
        if (recenter)
            animateFinal.top = Math.max(20, oldTop + (oldHeight - (height + titleHeight)) / 2);
        animateFinal.height = height + titleHeight;
    }

    if (setWidth == -1) {
        var oldLeft = parseInt(divPopupOuterWindow.css("left"));
        if (recenter)
            animateFinal.left = oldLeft + (divPopupOuterWindow.width() - width) / 2;
        animateFinal.width = width;
    }

    var onAnimationComplete = function () {
            osjs(divToPopup).dialog('size');
            if(supportsShadows)
                osjs(divToPopup).parents('.ui-dialog').removeShadow().dropShadow();
            osjs('.ui-dialog-titlebar-close-no-title').css('display', 'block');
            osjs(divToPopup).find('iframe').height('100%').width(width);
        };
    var divPleaseWait = osjs(".ui-dialog-content>.Text_Note")
    divPleaseWait.hide();
    
    
    
    if (setHeight == -1 || setWidth == -1) divPopupOuterWindow.animate(animateFinal, {
        duration: 200,
        complete: onAnimationComplete
    });
    else onAnimationComplete();

    innerDoc = null;
    divPopupOuterWindow = null;
    return true;
}

function RichWidgets_Popup_Editor_Close(iFrame) {
 setTimeout(function() {
  osjs('.ui-dialog-content').dialog('close'); }, 
 0);
};
