﻿//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) {
 osjs().ready(function($) {
  var linkHref;
  var isAButton = false;
  try {
   linkId = '#' + linkId;
   RichWidgets_Popup_Editor_ParentUrl = parentUrl;

   //Checks if the id is from a link or not
   linkHref = $(linkId).attr('href');

   //Tests for visibility/existence
   if (typeof linkHref == 'undefined') {
     var onClick = $(linkId).get(0).getAttribute('onclick');
     if (typeof onClick == 'undefined') {
       throw ("Inexistent or Invisible button");
     }
     if (onClick == null) {
       isAButton = true;
       throw ("Not a navigate");
     }
     linkHref = onClick.toString().match(/href='([^']*)'/)[1];
     if (typeof linkHref != 'undefined') {
       isAButton = true;
       throw ("Not a navigate");
     }     
   }

  } catch(e) {
    if (!isAButton) {
      //Case the link is inexistent or invisible, it will show no errors.
      return;
    }
  }

  if (typeof linkHref == 'undefined' || linkHref == "" || linkHref == "#" || linkHref.indexOf("javascript:") == 0) {
   throw (new Error("Popup link id must be the id of a Link or Button Widget with Method Navigate."));
  } 

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

  // if there's a confirmation message, store in an attribute the result
  if ($(linkId).get(0).getAttribute('onclick') != null) {
    $(linkId).get(0).setAttribute('onclick', $(linkId).get(0).getAttribute('onclick').replace("if( ret != true )", "osjs('" + linkId + "').get(0).setAttribute('confirmed', ret); if( ret != true )"));
  }

  $(linkId).click(function(event) {
   if ($(linkId).get(0).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 = $(linkId).attr('href'); 
   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() {
    resizePopup(this, $(this).parents('div:eq(0)'), $(this).parents('div:eq(0)').find("div:eq(0)"));
   });
   popupDiv = null;
   pleaseWaitDiv = null;
   return false;
  });
  
  function removeDialogShadow(div) {
   $(div).parents('.ui-dialog').removeShadow();
  };

  function addDialogShadow(div) {
   $(div).parents('.ui-dialog').removeShadow().dropShadow();
   $(div).parents('.ui-dialog').css('z-index', RichWidgets_Popup_Editor_Index);
  };

  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: true,
    height: setHeight,
    position: 'center',
    width: ((setWidth == -1) ? RichWidgets_Popup_Editor_InitialWidth: setWidth),
    dragStart: function() { removeDialogShadow(divToPopup) },
    dragStop: function() { addDialogShadow(divToPopup) },
    close: function() {
     removeDialogShadow(divToPopup);
     $(divToPopup).find('iframe').attr('src', 'about:blank');
     $(divToPopup).find('iframe').empty();
     $(divToPopup).dialog('destroy');
     $(divToPopup).empty();
    }
   });
   $(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 resizePopup(frameObj, divToPopup, divPleaseWait) {
   $(divToPopup).find('iframe').css("height", "auto");
   var documentServer = document.location.href.replace(/(https?:\/\/[^\/]*).*/,'$1');
   var frameServer = frameObj.src.replace(/(https?:\/\/[^\/]*).*/,'$1');
   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.contentDocument) ? frameObj.contentDocument: frameObj.contentWindow.document;
    if (innerDoc.documentElement.scrollHeight == 0) // strangely this event is also triggered on close
     return;
   }
   $(divToPopup).find('iframe').height(0);

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


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

   $(divToPopup).height(height);
   
   // Fix IE issue with scrollbars when explicitly setting the height
   if (sameOrigin) 
    innerDoc.body.style.height = 'auto';

   //Hide ECT
   $(innerDoc).find('.ECT_FeedbackContainer').hide();
   var divPopupOuterWindow = $(divToPopup).parents('.Popup');
   
   var animateFinal = {};

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

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

   var onAnimationComplete = function() {
    $(divToPopup).dialog('size');
    addDialogShadow(divToPopup);
    $('.ui-dialog-titlebar-close-no-title').css('display','block');
    $(divToPopup).find('iframe').height('100%').width(width);
   };

   $(divPleaseWait).hide();
   if (setHeight == -1 || setWidth == -1) divPopupOuterWindow.animate(animateFinal, {
    duration: 200,
    complete: onAnimationComplete
   });
   else onAnimationComplete();
   
   innerDoc = null;
   divPopupOuterWindow = null;
   
   $(divToPopup).find('iframe').unbind("load");
  }

 });
}

function RichWidgets_Popup_Editor_Close(iFrame) {
 setTimeout(function() { 
 osjs('.ui-dialog-content').find('iframe').attr('src', 'about:blank'); 
 osjs('.ui-dialog-content').find('iframe').empty();
 osjs('.ui-dialog-content').dialog('close'); }, 
 0);
};