// -----------------------------------------------------------------------------
// <name>PageHelper.js</name>
// <summary>
// Generic helper methods for pages.
// Supports error indicating, cookie handling, drop down load-on-demand with Ajax,
// validation and other miscellaneous operations.
// Some methods requires StringHelper.js to be referenced by the caller page.
// </summary>
// -----------------------------------------------------------------------------


// <summary>
// Checks if some of the values is null.
// Values undefined, null, "", NullInteger are considered to be null representatives.
// Requires StringHelper.js to be referenced by the caller page.
// Returns false if error was found. Returns true if no error was found. Does not displays any dialog.
// <param name="arrayOfValues">Elementary values.</param>
// <param name="arrayOfLabels">Label elements with innerText and style.color members. Color will be set or cleared, innerText will be used for warning messages. Can be undefined or can have less elements than arrayOfValues.</param>
// <param name="commonErrorMessage">If specified shows pop-up dialog with warning message if one of the required values is null. Message text for pop-up dialog such "Please fill the required fields!". Label captions (innertText) may be appended after it.</param>
// <param name="errorColorForLabels">Error color value for labels (style.color).</param>
// <param name="noErrorColorForLabels">Normal color value for labels (style.color).</param>
// </summary>    
function checkRequiredValues( 
   arrayOfValues, 
   arrayOfLabels, 
   errorColorForLabels,
   noErrorColorForLabels )
{
   var error = false;
   
   for (var a = 0; a<arrayOfValues.length; a++)
   {
      var value = arrayOfValues[a];      
      
      if (isNull(value))
      {
         error = true;
         
         if (!isNull(arrayOfLabels) && arrayOfLabels.length > a && !isNull(arrayOfLabels[a]))
            arrayOfLabels[a].style.color = errorColorForLabels;
      }
      else
         if (typeof(value) == "string" && isNull(value,true))
         {
            error = true;
            
            if (!isNull(arrayOfLabels) && arrayOfLabels.length > a && !isNull(arrayOfLabels[a]))
               arrayOfLabels[a].style.color = errorColorForLabels;
         }
         else
         {
            if (!isNull(arrayOfLabels) && arrayOfLabels.length > a && !isNull(arrayOfLabels[a]))
               arrayOfLabels[a].style.color = noErrorColorForLabels;
         }
   }
   
   return !error;
}



// -----------------------------------------------------------------------------
// <summary>
// Redirects self with window.open( url, "_self" ).
// </summary>
// -----------------------------------------------------------------------------
function redirect( url )
{
   window.open( url, "_self" );
}

// -----------------------------------------------------------------------------
// <summary>
// Redirects parent with window.open( url, "_parent" ).
// </summary>
// -----------------------------------------------------------------------------
function redirectParent( url )
{
   window.open( url, "_parent" );
}

// -----------------------------------------------------------------------------
// <summary>
// Opens new window with window.open( url, "_blank" ).
// </summary>
// -----------------------------------------------------------------------------
function redirectBlank( url )
{
   window.open( url, "_blank" );
}

// -----------------------------------------------------------------------------
// <summary>
// Redirects in same page.
// </summary>
// -----------------------------------------------------------------------------
function redirectInSamePage( url )
{
   window.location = url;
}

// -----------------------------------------------------------------------------
// <summary>
// Displays or hides the control by setting element.style.display to "" or to "none".
// </summary>
// -----------------------------------------------------------------------------
function setVisible( element, visible )
{
   element.style.display = (visible ? "block" : "none");
}

var PageHelper_DisabledBackgroundColor = "#f5f5f5";

// -----------------------------------------------------------------------------
// <summary>
// Disables control. Set background color to PageHelper_DisabledBackgroundColor.
// </summary>
// -----------------------------------------------------------------------------
function disable( element )
{
   element.disabled = true;
   element.style.backgroundColor = PageHelper_DisabledBackgroundColor;
}

// -----------------------------------------------------------------------------
// <summary>
// Sets the innerText (IE) or textContent (Mozilla) attribute of the element.
// </summary>
// -----------------------------------------------------------------------------
function setInnerText( element, text )
{
   if (typeof(element.innerText) != "undefined")
      element.innerText = text;        // IE
   else
      element.textContent = text;      // Mozilla
}

// -----------------------------------------------------------------------------
// <summary>
// Appends to the innerText (IE) or textContent (Mozilla) attribute of the element.
// </summary>
// -----------------------------------------------------------------------------
function appendInnerText( element, text )
{
   if (typeof(element.innerText) != "undefined")
      element.innerText += text;        // IE
   else
      element.textContent += text;      // Mozilla
}

// -----------------------------------------------------------------------------
// <summary>
// Returns the innerText (IE) or textContent (Mozilla) attribute of the element.
// </summary>
// -----------------------------------------------------------------------------
function getInnerText( element )
{
   if (typeof(element.innerText) != "undefined")
      return element.innerText;        // IE
   else
      return element.textContent;      // Mozilla
}

// -----------------------------------------------------------------------------
// <summary>
// Returns attribute value. Returns "" if attribute doesn't exist.
// </summary>
// -----------------------------------------------------------------------------
function getAttributeValue( element, attributeName )
{
   if (typeof( element.attributes[ attributeName ] ) == "undefined")
      return "";
   else
      return element.attributes[ attributeName ].value;
}

// -----------------------------------------------------------------------------
// <summary>
// Sets attribute value. 
// </summary>
// -----------------------------------------------------------------------------
function setAttributeValue( element, attributeName, value )
{
   if (typeof( element.attributes[ attributeName ] ) == "undefined")
   {
      var attr = document.createAttribute( attributeName );
      attr.value = value;
      
      element.attributes.setNamedItem( attr );      
   }
   else
      element.attributes[ attributeName ].value = value;
}

function removeAttribute( element, attributeName )
{
   if (typeof( element.attributes[ attributeName ] ) != "undefined")
      element.attributes.removeNamedItem( attributeName );      
}

// -----------------------------------------------------------------------------
//
//    Cookie helpers
//
// -----------------------------------------------------------------------------


// -----------------------------------------------------------------------------
// <summary>
// Parses a cookie string which is separated by semicolons and formatted like this:
// variableName=value; variableName=value ...
// Returns string. Returns "" if not found.
// </summary>
// -----------------------------------------------------------------------------
function private_getCookieValue (cookieName)
{
   var items = document.cookie.split(";");
   
   for (var a = 0; a<items.length; a++)
   {
      var item = trim(items[a]);
      
      if (startsWith(item, cookieName))
      {
         var b = item.indexOf("=");
         
         if (b >= 0)
         {
            return trim( item.substring(b+1, item.length) );
         }
      }
   }
   
   return "";
}


// -----------------------------------------------------------------------------
// <summary>
// Parses a cookie string which is separated by semicolons and formatted like this:
// variableName=value; variableName=value ...
// Returns unescaped value. Returns "" if not found.
// </summary>
// -----------------------------------------------------------------------------
function getCookieValue (cookieName)
{
   return unescape( private_getCookieValue( cookieName ));
}

// -----------------------------------------------------------------------------
// <summary>
// Parses a cookie string which is separated by semicolons and formatted like this:
// variableName=value; variableName=value ...
// Returns unescaped array, see unescapeArray() for details. 
// Returns new Array() if not found.
// </summary>
// -----------------------------------------------------------------------------
function getCookieArray (cookieName)
{
   return unescapeArray( private_getCookieValue( cookieName ) );
}

// -----------------------------------------------------------------------------
// <summary>
// Parses a cookie string which is separated by semicolons and formatted like this:
// variableName=value; variableName=value ...
// Returns unescaped variales, see unescapeVariables() for details. 
// Returns new Array() if not found.
// </summary>
// -----------------------------------------------------------------------------
function getCookieVariables (cookieName)
{
   return unescapeVariables( private_getCookieValue( cookieName ) );
}

// -----------------------------------------------------------------------------
// <summary>
// Sets cookie value using escape().
// Don't specify path for XmlHttp requests!
// Be careful because path is case sensitive!
// </summary>
// -----------------------------------------------------------------------------
function setCookieValue (cookieName, value)
{
   document.cookie = cookieName + "=" + escape(value) + ";path=/";
}

// -----------------------------------------------------------------------------
// <summary>
// Sets cookie value without using escape().
// Don't specify path for XmlHttp requests!
// Be careful because path is case sensitive!
// Be careful because doesn't escape value!
// </summary>
// -----------------------------------------------------------------------------
function setCookieValueUnescaped (cookieName, value)
{
   document.cookie = cookieName + "=" + value + ";path=/";
}

// -----------------------------------------------------------------------------
// <summary>
// Sets cookie value using escapeArray().
// Don't specify path for XmlHttp requests!
// Be careful because path is case sensitive!
// </summary>
// -----------------------------------------------------------------------------
function setCookieArray (cookieName, arrayOfValues)
{
   document.cookie = cookieName + "=" + escapeArray(arrayOfValues) + ";path=/";
}

// -----------------------------------------------------------------------------
// <summary>
// Sets cookie value using escapeVariables().
// Don't specify path for XmlHttp requests!
// Be careful because path is case sensitive!
// </summary>
// -----------------------------------------------------------------------------
function setCookieVariables (cookieName, arrayOfKeys, arrayOfValues)
{
   document.cookie = cookieName + "=" + escapeVariables(arrayOfKeys, arrayOfValues) + ";path=/";
}

// -----------------------------------------------------------------------------
// <summary>
// Deletes the cookie.
// </summary>
// -----------------------------------------------------------------------------
function deleteCookie( cookieName )
{
   document.cookie = cookieName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

// -----------------------------------------------------------------------------
// <summary>
// Opens a resizable dialog window for modal editing purposes.
// </summary>
// -----------------------------------------------------------------------------
function openResizableDialog( url, arguments, width, height, top, left )
{
   return window.showModalDialog( url, arguments, 
      "status=yes; help=yes; resizable=yes; scroll=yes; " + 
      (isNull(top) && isNull(left) ? "center=yes; " : "") +
      (isNull(width) ? "" : "dialogWidth: " + width + "px; ") + 
      (isNull(height) ? "" : "dialogHeight: " + height + "px; ") + 
      (isNull(top) ? "" : "dialogTop: " + top + "px; ") + 
      (isNull(left) ? "" : "dialogLeft: " + left + "px"));
}

// -----------------------------------------------------------------------------
// <summary>
// Opens a standard dialog window for modal messaging.
// </summary>
// -----------------------------------------------------------------------------
function openDialog( url, arguments, width, height, top, left )
{
   return window.showModalDialog( url, arguments, 
      "status=no; help=no; resizable=no; scroll=no; " + 
      (isNull(top) && isNull(left) ? "center=yes; " : "") +
      (isNull(width) ? "" : "dialogWidth: " + width + "px; ") + 
      (isNull(height) ? "" : "dialogHeight: " + height + "px; ") + 
      (isNull(top) ? "" : "dialogTop: " + top + "px; ") + 
      (isNull(left) ? "" : "dialogLeft: " + left + "px"));
}

// -----------------------------------------------------------------------------
// <summary>
// Opens a modeless dialog window for modal messaging.
// </summary>
// -----------------------------------------------------------------------------
function openWindow( url, name, width, height, top, left, resizable, status, setFocus )
{
   var newWindow;
   
   resizable = isNull(resizable) ? true : resizable;
   setFocus = isNull(setFocus) ? false : setFocus;
   
   newWindow = window.open( url, name,
      "directories=no, location=no, menubar=no, status=yes, toolbar=no, scroll=yes" + 
         (isNull(width) ? "" : ", width=" + width ) + 
         (isNull(height) ? "" : ", height=" + height ) + 
         (isNull(top) ? "" : ", top=" + top ) + 
         (isNull(left) ? "" : ", left=" + left ) +
         (isNull(status) ? "" : ", status=" + status ) + 
         (resizable ? ", resizable=yes" : ", resizable=no" ),
      true);
      
   if (setFocus) {
      newWindow.focus();
   }
}

function getEvent( evt )
{
   return (evt) ? evt : ((window.event) ? window.event : null);
}

function getSrcElement( evt )
{
   var e = getEvent( evt );
   
   if (evt)
      return (evt.srcElement) ? evt.srcElement : evt.target;
   else
      return null;
}


// -----------------------------------------------------------------------------
// <summary>
// Shows error in the specified DIV.
// If errorMessage is empty, the indicator is set to hidden.
// If errorMessage is not empty, the inidicator is set to visible.
// Returns error message or "".
// </summary>
// -----------------------------------------------------------------------------
function showError(errorIndicator, errorMessage)
{
   if (errorIndicator != undefined && errorIndicator != null)
   {
      if (errorMessage != undefined && errorMessage != null && errorMessage != "")
      {
         if (getAttributeValue( errorIndicator, "ShowSummary" ).toLowerCase() == "true")
         {
            setVisible( errorIndicator, true );
         
            if (typeof(errorIndicator.innerText) != "undefined")
               errorIndicator.innerText = errorMessage.replace("\n", unescape("%0D0A")); // IE
            else
               errorIndicator.textContent = errorMessage.replace("\n", unescape("%0D0A")); // Mozilla
         }
         
         if (getAttributeValue( errorIndicator, "ShowMessageBox" ).toLowerCase() == "true")
         {
            window.alert( errorMessage.replace("\n", unescape("%0D0A")) );
         }
         
         return errorMessage;
      }
      else
      {
         setVisible( errorIndicator, false );

         if (typeof(errorIndicator.innerText) != "undefined")
            errorIndicator.innerText = ""; // IE
         else
            errorIndicator.textContent = ""; // Mozilla

         return "";
      }
   }
}

// -----------------------------------------------------------------------------
// <summary>
// Shows AJAX error in the specified DIV. 
// (Used for AJAX errors.)
// Uses ajaxError to determine wheter exception is occured or not and to
// get exception specific information.
// Returns error message or "".
// </summary>
// -----------------------------------------------------------------------------
function showAjaxError(errorIndicator, ajaxError, javaScriptMethodName)
{
   if (ajaxError != undefined && ajaxError != null && ajaxError != false)
   {     
      return showError( errorIndicator, 
         ResourceManager.System.getString("JavaScript.General.PageHelper.AjaxErrorFormat").
            replace("\{0\}", ajaxError.Type).
            replace("\{1\}", ajaxError.Message)
         );
   }
   else
   {
      return showError( errorIndicator, "" );
   }
}

function setReadOnly( control, readOnly )
{
   var ctr = control;
   var fromClass = "";
   var toClass = "";
   
   if (readOnly)
   {
      if (ctr.type == "checkbox")
      {
         ctr.disabled = true;         
         ctr.parentElement.disabled = true;
         
         ctr = ctr.parentElement;         
      }
      else if (ctr.type == "button" || ctr.type == "select-one")
      {
         ctr.disabled = true;
      }
      else
         setAttributeValue( ctr, "readonly", "readonly" );

      toClass = "ReadOnly";
   }
   else
   {
      if (ctr.type == "checkbox")
      {        
         ctr.disabled = false;
         ctr.parentElement.disabled = false;
         
         ctr = ctr.parentElement;
      }
      else 
      {
         ctr.disabled = false;
         removeAttribute( ctr, "readonly" );
      }

      fromClass = "ReadOnly";
   }

   ctr.className = ctr.className
      .replace("ReadOnlyCheckBox", "CheckBox")
      .replace("ReadOnlyNumberBox", "NumberBox")
      .replace("ReadOnlyTextBox", "TextBox")
      .replace("ReadOnlyDateBox", "DateBox")
      .replace("ReadOnlyDropDown", "DropDown");
   
   if (readOnly)
   {   
      ctr.className = ctr.className
         .replace("CheckBox", "ReadOnlyCheckBox")
         .replace("NumberBox", "ReadOnlyNumberBox")
         .replace("TextBox", "ReadOnlyTextBox")
         .replace("DateBox", "ReadOnlyDateBox")
         .replace("DropDown", "ReadOnlyDropDown");
   }
}

function setApplicationPath(appPath, url)
{
    if(!url.startsWith("/"))
        url = "/" + url;
    if(appPath != null && appPath != '')
    {
        return '/' + appPath + url;
    }
    return url;
}


