//$Id: Common.js,v 1.52 2007-09-25 01:47:36 khang Exp $
Function.prototype.inheritsFrom = function(parentClassOrObject) {
 // <summary>
 // Copied from: http://phrogz.net/JS/Classes/OOPinJS2.html   
 // Call this to define an inheritance between 2 functions
 // </summary>
 if (parentClassOrObject.constructor == Function) {
  //Normal Inheritance 
  this.prototype = new parentClassOrObject;
  this.prototype.constructor = this;
  this.prototype.parent = parentClassOrObject.prototype;
 }
 else {
  //Pure Virtual Inheritance 
  this.prototype = parentClassOrObject;
  this.prototype.constructor = this;
  this.prototype.parent = parentClassOrObject;
 }
 return this;
}


function showWaitingPage(hostpath, frame) {
 try {
  var targetFrame = "centerFrame";
  if (frame != null)
   targetFrame = frame;
  var isValid = true;
  if (typeof(Page_IsValid) != 'undefined')
   isValid = Page_IsValid;

  if (isValid == true) {
   var mainWindow = window;

   try {
    while (mainWindow.frameElement != null && mainWindow.frameElement.id != targetFrame && mainWindow != mainWindow.parent)
     mainWindow = mainWindow.parent;
   }
   catch (e) { }
   var dlg = mainWindow.findDialog("waitingPage");
   if (dlg == null) {
    dlg = mainWindow.openDialogEx1(virtualAppHost, "about:blank", 200, 100, true, null);
    dlg.allowTitleBar(false);
    dlg.allowStatusBar(false);
    dlg.destroyOnHide = false;
    dlg.setDropDownHideMode('preventchange');
    dlg.showDDLs(true, mainWindow);
    dlg.setId("waitingPage");
   }
   dlg.show(true);
   dlg.bringToTop();
   var content = "<!DOCTYPE html><html><head><title></title><style type='text/css'>\n"
+ "body {color: #000099;font-family: Verdana;font-size: 8pt;}body,html{margin:0;padding:0}.s0,body,html,.s1,* html .s3{height:100%}.s0{margin:0 auto;display:table}.s1{display:table-cell;white-space:nowrap}.s1,* html .s3,* html .s2{vertical-align:middle}.s2{padding:.3em .5em}* html .s1{text-align:center}* html .s3,* html .s2{display:inline-block;text-align:left}* html .s2{display:inline;height:0}.s3{width:1px}"
+ "</style></head>"
   + "<body><div class='s0'><div class='s1'><div class='s2'><table><tr><td><img src='" + virtualAppHost + "Images/Loading.gif' /></td><td style='vertical-align:middle'>" + __waitingmessage + "</td></tr></table></div><span class='s3'></span></div></div></body></html>";
   dlg.getInnerWindow().document.write(content);
   dlg.getInnerWindow().document.close();
  }
 }
 catch (e) { }
}

function closeWaitingPage() {
 try {
  var mainWindow = window;

  try {
   while (mainWindow.frameElement != null && mainWindow.frameElement.id != "centerFrame" && mainWindow != mainWindow.parent)
    mainWindow = mainWindow.parent;
  }
  catch (e) { }

  var dlg = mainWindow.findDialog("waitingPage");
  if (dlg != null)
   dlg.show(false);
 }
 catch (e) { }
}

function getParentWindow() {
 /// <summary>
 /// Get the parent window.
 /// </summary>
 return (cg_shared.IsIE) ? document.parentWindow.parent : document.defaultView.parent;
}

function catchNumbericTextBox(e) {
 if (cg_shared.IsIE) {
  if (e.keyCode < 48 || e.keyCode > 57)
   cg_shared.preventEventDefault(e);
 }
 else {
  if ((e.charCode < 48 || e.charCode > 57) && e.keyCode == 0)
   cg_shared.preventEventDefault(e);
 }
}

function visibleControl(controlID, visible) {
 var control = document.getElementById(controlID);
 visibleControlEx(control, visible);
}

function visibleControlEx(control, visible) {
 if (control != null) {
  control.style.display = visible ? "" : "none";
  control.style.visibility = visible ? "visible" : "hidden";
 }
}

function displaySelectTags(status) {
 var selects = document.getElementsByTagName("SELECT");
 for (var id = 0; id < selects.length; id++) {
  var select = selects[id];
  select.style.visibility = status;
 }
}

function toggleDropDownList(status) {
 var selects = document.getElementsByTagName("SELECT");
 for (var id = 0; id < selects.length; id++) {
  var select = selects[id];
  select.style.visibility = status;
 }

 try {
  var iframes = document.getElementsByTagName("iframe");
  for (var id = 0; id < iframes.length; id++) {
   var iframe = iframes[id];
   if (iframe.contentWindow != null)
    iframe.contentWindow.manupulateSelects(status);
  }
 } catch (e) { }

 try {
  var dlgList = getDialogList();
  if (dlgList) {
   for (var id = 0; id < dlgList.length; id++) {
    var dlg = dlgList[id];
    var dlgWindow = dlg.getInnerWindow();
    try {
     if (dlgWindow)
      dlgWindow.toggleDropDownList(status);
    }
    catch (e) { continue; }
   }
  }
 }
 catch (e) { }
}

function getCenterWindow() {
 var mainWindow = window;

 try {
  while (mainWindow.frameElement != null && mainWindow.frameElement.id != "centerFrame" && mainWindow != mainWindow.parent)
   mainWindow = mainWindow.parent;
 }
 catch (e) { }
 return mainWindow;
}

function openDialogWithId(hostpath, dlgId, url, modal) {
 var height = (cg_shared.IsIE) ? window.document.body.offsetHeight - 50 : window.document.body.clientHeight - 50
 var width = (cg_shared.IsIE) ? window.document.body.offsetWidth - 50 : window.document.body.clientWidth - 50;
 var tempDialog = new CatDialog(window, dlgId, null, null, '', width, height, hostpath + 'Images/Common/CatDialog', 'SteelBlue2_', 'SteelBlue', 'Transparent', null, '', '', false, modal, false, true, true, false, false, false, false, false, true, true, true, false, -1);

 tempDialog.setUrl(url);
 tempDialog.destroyOnHide = true;
 //tempDialog.setSize(document.body.offsetWidth-50, document.body.offsetHeight-50);
 tempDialog.setSize(width, height);
 tempDialog.moveCenter();
 tempDialog.show(true);
 return tempDialog;
}

function openDialogEx1(hostpath, url, width, height, modal, show) {
 var tempDialog = new CatDialog(window, '', null, null, '', width, height, hostpath + 'Images/Common/CatDialog', 'SteelBlue2_', 'SteelBlue', 'Transparent', null, '', '', false, modal, false, true, true, false, false, false, false, false, true, true, true, false, -1);

 tempDialog.setUrl(url);
 tempDialog.destroyOnHide = true;
 tempDialog.setSize(width, height);
 tempDialog.moveCenter();
 if (show != null)
  tempDialog.show(show);
 return tempDialog;
}

function updateTitle() {
 try {
  if (window.frameElement.id == "centerFrame")
   cg_shared.getWindow(window.parent.frames.topFrame.document).breadcum(document.title);
 }
 catch (e) { }
}

function updateUILanguage() {
 var temp = getCenterWindow();
 cg_shared.getWindow(temp.parent.frames.topFrame.document).location.assign(cg_shared.getWindow(temp.parent.frames.topFrame.document).location.href);
 cg_shared.getWindow(temp.parent.frames.bottomFrame.document).location.assign(cg_shared.getWindow(temp.parent.frames.bottomFrame.document).location.href);
 temp.location.assign(temp.location.href);
}

/// Encode a string that used in URL
function cgEscape(txt) {
 return escape(txt.replace(/\+/g, "&#43"));
}

/*
Author   :  Nguyen Thanh Long
Function :  Used to get a control that is defined on server side by the command:
Ex: Page.ClientScript.RegisterHiddenField("FILTER_LIST_BOX", this.filterListBox.ClientID);
Parameter: 
- control:  The name of hidden field. In above example, it is "FILTER_LIST_BOX"
*/
function getElement(control) {
 var result;

 try {
  result = document.getElementById[document.getElementById[control].value];
 }
 catch (e) {
  result = null;
 }

 return result;
}

/*
Function.prototype.callNext = function(method)
{
var func = this;
return function()
{
func();
method();
};
}
*/
// Detect browers to get proper methods
var isIE = (navigator.appName == "Microsoft Internet Explorer");
var isNav = (navigator.appName == "Netscape");
$(window).bind("unload", null, unloadWindow);


/////////////////////// UNLOAD /////////////////////

function cgCommon_RegisterOnBeforeUnload() {
 $(window).bind("beforeunload", null, common_onbeforeunloadWindow);
}

function unloadWindow() {
 try {
  if (typeof (getCGExecuter) != 'undefined') {
   var temp = getCGExecuter();
   if (temp) {
    temp.dispose();
    delete temp;
   }
  }
 }
 catch (e) { }
}

function common_onbeforeunloadWindow() {
 cleanWebTabs();
}

function cleanWebTabs() {
 if (typeof igtab_all == 'object') {
  for (var tab in igtab_all) {
   if (tab) {
    var webtab = igtab_getTabById(tab);
    if (webtab && webtab.Tabs) {
     for (var idx = 0; idx < webtab.Tabs.length; idx++)
      webtab.Tabs[idx].setTargetUrl("");
    }
   }
  }
 }
}


function cleanFrames() {
 var frames = document.frames;
 for (var idx = 0; idx < frames.length; idx++) {
  var frame = frames[idx];
  if (frame.name != 'centerFrame') {
   try {
    frame.location.assign("");
   } catch (ex) { }
  }
 }
}

function OpenWindow(url) {
 window.open(url, '_blank', 'status=yes,toolbar=no,menubar=no,location=no,left=0,top=0,innerHeight=0,innerWidth=0,resizable=yes');
}
function ExportPowerPoint(url) {
 var width = 940;
 var height = 400;
 var top = (screen.height - height) / 2;
 var left = (screen.width - width) / 2;
 window.open(virtualAppHost + url, '_blank', 'status=yes,toolbar=no,menubar=no,location=no,left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ',resizable=yes');
}
function ShowDialog(url) {
 var dlg = getCenterWindow().openDialog(virtualAppHost, url, true);
 dlg.setSize(100, 100);
 dlg.autoFitSize();
 dlg.moveCenter();
}

function getDialog() {
 if (typeof (__commonDlg) == 'undefined')
  __commonDlg = openDialog(virtualAppHost, "", true);
 __commonDlg.show(true);
 return __commonDlg;
}

function showProgressPage(hostpath, url) {
 var targetFrame = "centerFrame";

 var mainWindow = window;

 try {
  while (mainWindow.frameElement != null && mainWindow.frameElement.id != targetFrame && mainWindow != mainWindow.parent)
   mainWindow = mainWindow.parent;
 }
 catch (e) { }

 var dlg = mainWindow.openDialog(hostpath, hostpath + url, true);
 dlg.papa = window;
 dlg.setDropDownHideMode('preventchange');
 dlg.showDDLs(true, mainWindow);
 dlg.allowTitleBar(false);
 dlg.allowStatusBar(false);
 dlg.setSize(400, 100);
 dlg.moveCenter();
}

/// <author>Thomas Bindzus</author>
/// <summary>Implements a way to load images in the background, which is used for viewing reports</summary>
/// <param name="img">The image that will be updated</param>
/// <param name="src">The url for the image to load in the background</param>
/// <example><![CDATA[<img id="imgId" src="/Images/Common/generating.gif" onload="loadImage(this, imgSrc);" />]]></example>
function loadImage(img, src) {
 // Unregister the onload event in order to prevent loops
 img.onload = null;

 // The image needs to have a valid id attribute   
 if (img.id == "" || img.id == null || img.id == undefined) {
  alert("Common.js/loadImage(this, '" + src + "'): Please specify the id attribute for the image element");
  return;
 }

 // Create a temporary image holder and set the src
 var tmpImg = new Image();
 tmpImg.src = src;

 // When image is loaded, the onload event is fired and will trigger
 // the visible image src attribute to refer to the loaded image instead
 tmpImg.onload = function() {
  var theImage = document.getElementById(img.id);
  theImage.src = this.src;
 }
}

//remove enter key of textbox
function removeEnterKey(evnt) {
 if (evnt.keyCode == 13)
  cg_shared.preventEventDefault(evnt.jquery ? evnt.originalEvent : evnt);
}

function cg_dateToString(date) {
 if (date == null)
  return "";
 if (typeof (date.getFullYear) != "function")
  return date.toString();
 var month = date.getMonth();
 var day = date.getDate();
 var year = date.getFullYear();
 var hour = date.getHours();
 var min = date.getMinutes();
 var sec = date.getSeconds();
 var ms = date.getMilliseconds();

 return day.toString() + "/" + (month + 1).toString() + "/" +
		(year.toString().length > 4 ? year.toString().substr(0, 4) : year) + " " +
		(hour == 0 ? "12" : (hour % 12).toString()) + ":" + (min < 10 ? "0" : "") +
		min + ":" + (sec < 10 ? "0" : "") + sec +
		(ms > 0 ? "." + ms.toString() : "") + " " + (hour < 12 ? "AM" : "PM");
}

function SetupPopupFrame(hostpath) {
 var win = getCenterWindow();
 var headerTag = win.document.documentElement.getElementsByTagName("Head")[0];
 var scriptTag = win.document.createElement("script");
 scriptTag.src = hostpath + "script/common/popupframe.js";
 headerTag.appendChild(scriptTag);
 return win
}

function getCenterPopupFrame(hostpath) {
 var centerWindow = SetupPopupFrame(hostpath);
 centerWindow.papa = window;
 return centerWindow
}

function showColorPopup(hostpath, src, left, top, width, height) {
 var dlg = getCenterWindow().openDialog(hostpath, src, true);
 dlg.papa = window;
 dlg.setDropDownHideMode('preventchange');
 dlg.showDDLs(true, window);
 dlg.allowTitleBar(false);
 dlg.allowStatusBar(false);
 dlg.setSize(width, height);
 dlg.moveCenter();
 return dlg;
}
/// <author>Thomas Bindzus</author>
// a date plus n days
Date.prototype.addDays =
function(days) {
 return new Date(this.getTime() + days * 24 * 60 * 60 * 1000);
}

//close the error page when user has no access to it.
function closePage() {
 if (window.opener) {
  window.close();
  return;
 }

 var dlg = null;
 if (typeof (parent.getActiveDialog) == "function")
  dlg = parent.getActiveDialog(document.body);

 if (dlg)
  dlg.show(false);
 else {
  var mainW = getCenterWindow();
  var homeurl = virtualAppHost + "Desktop.aspx";
  if (cg_shared.getWindow(mainW.parent.frames.document).topFrame.__accesstohomepage)
   homeurl = virtualAppHost + "MyPortal/MyPortalPage.aspx";
  mainW.location.assign(homeurl, true);
 }
}

//go to home page
function goHome() {
 closePage();
}

/// Anh Duc: These functions get from ResourceList JS code since i need them available in order grid
//This function is written based on Infragistis code, but modified so that it works correctly for FireFox
function getMainMenuItemsFireFox(mainMenu) {
 var itemAr = new Array();
 var itemCount = 0;
 var uniqueId = mainMenu.getClientUniqueId();
 var item = igmenu_getItemById(uniqueId + "_1");
 if (item == null) {
  for (var i = 2; i < 15; i++) {
   item = igmenu_getItemById(uniqueId + i.toString());
   if (item != null)
    break;
  }
 }
 while (item) {
  itemAr[itemCount++] = igmenu_getItemById(item.Id);
  item = getNextSiblingFireFox(item);
 }
 return itemAr;
}

//This function is written based on Infragistis code, but modified so that it works correctly for FireFox
function getItemsFireFox(menu) {
 var itemAr = new Array();
 var itemCount = 0;
 var item = menu.getFirstChild();
 while (item) {
  itemAr[itemCount++] = item;
  item = getNextSiblingFireFox(item);
 }
 return itemAr;
}


//This function is written based on Infragistis code, but modified so that it works correctly for FireFox
function getNextSiblingFireFox(menuItem) {
 var item = menuItem.element.nextSibling;
 if (item != null && item.id != null)
  item = igmenu_getItemById(item.id);
 else if (item != null) {
  item = menuItem.element.nextSibling.nextSibling;
  if (item != null && item.id != null)
   item = igmenu_getItemById(item.id);
 }
 return item;
}

function adjustGridHeight(grid) {
 ///<summary>
 /// Adjust the height of grid which is used alot in Catalogue.
 ///</summary>
 if ((typeof (grid)).toLowerCase() == "string")
  grid = igtbl_getGridById(grid);
 if (grid == null || typeof grid == 'undefined')
  return;
 return set_gridHeight(grid, 0);
}

function set_gridHeight(grid, paddingBottom) {
 ///<summary>
 /// set the height of a grid. Mostly you want to adjust grid's height with the bottom.
 /// All you need is to calculate the height from bottom of grid to the bottom of the dialog.
 ///</summary>
 if (grid == null || typeof grid == "undefined" || typeof (grid.MainGrid) == 'undefined')
  return;
 var h = (document.body.clientHeight - grid.MainGrid.offsetTop - 30) - paddingBottom;
 $("#" + grid.Id + "_mr").height(h);
 $("#" + grid.Id + "_mc").height(h);
 $("#" + grid.Id + "_mtb").height(h);
 return h;
}

function EncodeSearchName(searchName) {
 return encodeURIComponent(searchName);
}

function captureEnterKey() {
 cg_catchEnter = true;
 $(document).bind('keypress', null, catchEnter);
}

function catchEnter(evnt) {
 if (evnt.keyCode == 13) {
  if (typeof (Page_ClientValidate) == 'undefined' || Page_ClientValidate())
   __doPostBack('CatchEnter', '');
  cg_shared.stopEventFlow(evnt);
 }
}

function getRootWindow() {//Get the window that contain 3 frame: topFrame, centerFrame and bottomFrame
 var result = window;
 while (result != result.parent)
  result = result.parent;
 return result;
}

function checkIfOpeningResourceHasBeenOpenAlready(resourceId) {
/// <summary> Check if a being opened resource has already opened in order to prevent a resource from being opened more than 1 time</summary>
 if (getRootWindow().centerFrame == null) //This check used in FieldWork Management; 
  return false;
 var childWins = getRootWindow().centerFrame.getDialogList();
 if (childWins == null)
  return false;
 for (var i = 0; i < childWins.length; i++)
  if (childWins[i].getInnerWindow().__editedResource && childWins[i].getInnerWindow().__editedResource.id == resourceId)
  return true;

 return false;
}

function resourcedialog_onclose() {
 ///<summary>Default common function used to handle event "onclose" fire from the dialog.</summary>

 //If there's anything to do before close the dialog, it should be put into function "handleBeforeClose"
 if (typeof (handleBeforeClose) == "function")
  handleBeforeClose();
 else
  closeDialog();

 //always return false to cancel the event
 return false;
}

function closeDialog() {
 ///<summary>Default common function used to close the dialog.</summary>
 if (typeof (parent.getActiveDialog) != 'undefined') {
  var dlgex = parent.getActiveDialog(document.body);
  if (typeof (dlgex.papa.catdlg_onclose) != 'undefined')
   dlgex.papa.catdlg_onclose(dlgex);
  dlgex.show(false, false, true);
 }
}

function cancelUnexpectedEvent(evnt, controlId) {
 ///<summary>The click event of control can be fired by clicking on somewhere in the page.
 ///So, it should be canceled</summary>
 ///<param name="evnt">the current event</param>
 ///<param name="controlId">the control Id of the control which should be ignored the event</param>
 ///<return>true if the event is canceled and vice versa</return>

 if (cg_shared.IsFireFox && evnt.explicitOriginalTarget.id != controlId) {
  cg_shared.stopEventFlow(evnt);
  return true;
 }
 return false;
}

function AdjustDateTimeObject(dateTime, isToUTC) {
 /// <summary> Convert dateTime to UTC and  back again </summary>
 /// <param name="dateTime"> Date object</param>
 /// <param name="isUTC">
 ///   isToUTC =  true: Convert dateTime to UTC  datetime
 ///   isToUTC =  false: Convert dateTime to local datetime 
 /// </param>

 // convert to milisecond since Jan 1 1970
 var localTime = dateTime.getTime();

 // obtain local UTC offset and convert to msec
 // method getTimezoneOffset() returns the time zone offset in minutes, so multiple with 60000
 // to converto miliseconds
 var localOffset = dateTime.getTimezoneOffset() * 60000;

 // obtain UTC time in milisecond
 var utc = (isToUTC) ? localTime + localOffset : localTime - localOffset;

 return new Date(utc);
}

function FixFFProblemWithSubMenu(MenuId) {
 var m = igmenu_getMenuById(MenuId);
 if (typeof (m) == 'undefined') {
  var i = igmenu_initMenu;
  igmenu_initMenu = function(MenuId) { var m = i(MenuId); FixFFProblemWithSubMenu(MenuId); return m; }
  return;
 }
 if (typeof(m.orgDSM) != 'undefined') return;
 m.orgDSM = m.displaySubMenu;
 m.displaySubMenu = function(s, p, v) {
  if (typeof (s.runtimeStyle) == 'undefined')
   s.runtimeStyle = {};
  m.orgDSM(s, p, v);
  var a = s.firstChild;
  var c = s.style.width;
  if (a && a.style && a.style.width == "") {
   a.style.width = c;
   var b = a.firstChild;
   if (b && b.style)
    b.style.width = c;
  }
 }
}

