/*                          
 * Copyright 2003 Knife Edge Technologies, Inc.  All Rights Reserved.
 * 
 * This software is the proprietary information of Knife Edge Technologies, 
 * Inc. provided under license for use by "The Flying Mule."
 * No part of this file may be copied or re-used without prior written 
 * agreement from Knife Edge Technologies, Inc.
 * http://www.knifeedgetech.com   info@knifeedgetech.com
 */
xPopUp              = 100;
yPopUp              = 100;
cxPopUp             = 500;
cyPopUp             = 300;
strPopUpName        = "POPUP";
cmsSyncWait         = 1000;
cmsStatusWait       = 1000;
strDebugLevelCookie = "DEBUG_LEVEL";
cmsPrmChange        = 15000;

/* 
 * Creates a new array from a section of an existing array.  Similar to the
 * Array.slice method only this may be used with an arguments array.
 */
function utlArraySection( a, iStart, iEnd )
{
   var aNew = null;
   var i;

   // Limit range
   if (iStart < 0) 
   {
      iStart = 0;
   }

   if (iEnd > a.length)
   {
      iEnd = a.length;
   }

   // Valid range?
   if (
       (a != null) 
       && 
       (iStart < a.length)
       &&
       (iEnd > iStart)
      )
   {
      // Allocate new array and copy elements
      aNew = new Array( iEnd - iStart );
      for (i = iStart; i < iEnd; i++)
      {
         aNew[i - iStart] = a[i];
      }
   }

   return (aNew);
}


/*
 * Sets current debug level
 */
function utlSetDebug( iDebug )
{
   utlSetCookie( strDebugLevelCookie, iDebug, "/" );
}


/*
 * Gets current debug level
 */
function utlGetDebug()
{
   return (utlGetCookie( strDebugLevelCookie, 0 ));
}


/*
 * Outputs debug message if enabled
 */
function utlDebug( strMsg, iDebug )
{
   iDebugCookie = utlGetDebug();

   // Debugging enabled?
   if (iDebugCookie > 0)
   {
      // Use default level if not specified
      if (iDebug == null)
      {
         iDebug = 1;
      }
      
      // Is message of sufficient level?
      if (iDebug <= iDebugCookie)
      {
         alert( strMsg );
      }
   }
}


/*
 * Opens a Span tag if a class is specified
 */
function utlWriteSpanOpen( strClass )
{
   if (strClass != null)
   {
      document.write( "<SPAN class='" + strClass + "'>" );
   }
}


/*
 * Closes a Span tag if a class is specified
 */
function utlWriteSpanClose( strClass )
{
   if (strClass != null)
   {
      document.write( "</SPAN>" );
   }
}


/*
 * Writes a tag attribute if a value is specified
 */
function utlWriteAtt( strName, strValue )
{
   if (strValue != null)
   {
      document.write( strName + "='" + strValue + "' " );
   }
}


/*
 * Gets a field value, regardless of field type
 */
function utlGetFieldValue( fld, strValue )
{
   // Validate
   if (fld != null)
   {
      // Can we accept this value?
      if (
          ((fld.type != "checkbox") && (fld.type != "radio"))
          ||
          (fld.checked)
         )
      {
         strValue = fld.value;
      }
   }

   return (strValue);
}


/*
 * Sets a field value, regardless of field type
 */
function utlSetFieldValue( fld, strValue )
{
   // Validate
   if ((fld != null) && (strValue != null))
   {
      // What type of field?
      if (
          (fld.type == "text") 
          ||
          (fld.type == "password")
          ||
          (fld.type == "hidden")
         )
      {
         // Text field, set value
         fld.value = strValue;
      }
      else if (fld.type == "select-one")
      {
         // Single-select list, look for value as an option in list
         iopt = utlGetOptionIndex( fld, strValue, true, 0 );
         if (iopt != -1)
         {
            // Select option
            fld.selectedIndex = iopt;
         }
      }
   }
}


/*
 * Gets a Select tag Option by value, creating a copy 
 */
function utlGetOption( sel, strValue )
{   
   var opt = null;
   var iopt;

   // Find original option
   iopt = utlGetOptionIndex( sel, strValue, true, 0 );

   if (iopt != -1)
   {
      // Copy option
      opt = new Option( sel.options[iopt].text
                      , sel.options[iopt].value
                      , false
                      , false
                      );
   }
   
   return (opt);
}


/*
 * Finds the index of a Select tag Option with a specified value
 */
function utlGetOptionIndex( sel, strValue, fExact, iopt )
{
   var ioptFound;

   // Examine each option
   ioptFound = -1;
   while ((ioptFound == -1) && (iopt < sel.options.length))
   {
      // Requested value (either exact or partial)?
      if (
          (fExact && (sel.options[iopt].value == strValue))
          ||
          (!fExact && (sel.options[iopt].value.indexOf( strValue ) != -1))
         )
      {
         // Done searching
         ioptFound = iopt;
      }

      // Next option
      iopt++;
   }

   return (ioptFound);
}


/*
 * Finds the index of a string in a string array map
 */
function utlGetMapIndex( strName, astrMap, cstrMapEntry )
{ 
   // Declare local variables
   var istrMap;
   var istrFound;

   // Initialize
   istrMap   = 0;
   istrFound = -1;

   // Search until found or end of map
   while ((istrFound == -1) && (istrMap < astrMap.length))
   {
      // Matching name?
      if (strName == astrMap[istrMap])
      {
         istrFound = istrMap;
      }

      // Next entry
      istrMap += cstrMapEntry;
   }

   return (istrFound);
}


/*
 * Finds an image in a document by filename
 */
function utlFindImg( strRoot )
{
   var imgFound = null;
   var iimg     = 0;

   // Examine each image in document
   while ((imgFound == null) && (iimg < document.images.length))
   {
      // Is this the image?
      img = document.images[iimg];
      if (img.src.indexOf( strRoot ) != -1)
      {
         // Make a note of it
         imgFound = img;
      }
      else
      {
         // Next image
         iimg++;
      }
   }

   return (imgFound);
}


/*
 * Finds a link in a document by name
 */
function utlFindLink( strName )
{
   var lnkFound = null;
   var ilnk     = 0;

   // Examine each link in document
   while ((lnkFound == null) && (ilnk < document.links.length))
   {
      // Is this the link?
      lnk = document.links[ilnk];
      if (lnk.name.indexOf( strName ) != -1)
      {
         // Make a note of it
         lnkFound = lnk;
      }
      else
      {
         // Next link
         ilnk++;
      }
   }

   return (lnkFound);
}


/*
 * Gets a cookie value by name
 */
function utlGetCookie( strName, strValue ) 
{
   // Any cookies?
   if (document.cookie.length > 0)
   { 
      // Look for requested name
      strName  += "=";
      ichStart = document.cookie.indexOf( strName )       

      // Found name?
      if (ichStart != -1) 
      { 
         // Find start and end of value
         ichStart += strName.length;
         ichEnd   =  document.cookie.indexOf( ";", ichStart );

         // Last value?
         if (ichEnd == -1)             
         {
            ichEnd = document.cookie.length;
         }

         // Extract value
         strValue = unescape( document.cookie.substring( ichStart, ichEnd ) );
      }   
   }

   return (strValue);
}


/*
 * Sets a cookie value by name
 */
function utlSetCookie( strName, strValue, strPath, dtExpire )
{
   strCookie = strName + "=" + strValue;
   
   if (strPath != null)
   {
      strCookie += ";path=" + strPath;
   }

   if (dtExpire != null)
   {
      strCookie += ";expires=" + dtExpire.toGMTString();
   }

   document.cookie = strCookie;
}


/*
 * REDO: Take params
 */
function utlFixFieldStyles()
{
   for (ifrm = 0; ifrm < document.forms.length; ifrm++)
   {
      frm = document.forms[ifrm];
  
      for (iel = 0; iel < frm.elements.length; iel++)
      {
         if (
             (frm.elements[iel].type == "text")
             ||
             (frm.elements[iel].type == "password")
             ||
             (frm.elements[iel].type == "select-one")
            )
         {
            frm.elements[iel].style.borderColor     = "#909090";
            frm.elements[iel].style.borderWidth     = 1;
            frm.elements[iel].style.backgroundColor = "#FAD028";
         }
      }
   }
}


/*
 * Preloads a set of images after a specified image has loaded
 */
function utlSyncPreloadImgs( strWait, astrName, strStatusMsg )
{
   // New set of images to preload?
   if (strWait != null)
   {
      // Begin loading main image and note image set for later
      document.imgSyncWait      = new Image();
      document.imgSyncWait.src  = strWait;
      document.astrSyncName     = astrName;
      document.strSyncStatusMsg = strStatusMsg;
   }

   // Has main image completed?
   if (document.imgSyncWait.complete)
   {
      // Start preloading
      document.aimgSync = utlPreloadImgs( document.astrSyncName
                                        , document.strSyncStatusMsg 
                                        );
   }
   else
   {
      // Wait a while longer for main image
      setTimeout( "utlSyncPreloadImgs( null, null, null )", cmsSyncWait );
   }
}


/*
 * Preloads a set of images 
 */
function utlPreloadImgs( astrName, strStatusMsg )
{
   if (astrName != null)
   {
      // Create a new image array to hold preload images
      aimg = new Array();

      // Add each image in turn
      for (istrName = 0; istrName < astrName.length; istrName++)
      {
         // Create a new image object to preload image
         aimg[istrName]     = new Image();
         aimg[istrName].src = astrName[istrName];
      }

      // Displaying status?
      if (strStatusMsg)
      {
         utlShowImgStatus( aimgPreload, strStatusMsg );
      }
   }

   return (aimg);
}


/*
 * Displays a status message for a set of preloading images
 */
function utlShowImgStatus( aimg, strMsg )
{
   var cimgLoading;


   // New set of images to track?
   if (aimg != null)
   {
       // Note new set
       document.aimgStatus = aimg;
       document.strMsg     = strMsg;
   }
   else
   {
       // Continue tracking previous set
       aimg   = document.aimgStatus;
       strMsg = document.strMsg;
   }

                                      
   // Count the number of images still loading
   cimgLoading = 0;
   for (iimg = 0; iimg < aimg.length; iimg++)
   {
      if ((aimg[iimg] != null) && (!aimg[iimg].complete))
      {
         cimgLoading++;
      }
   }

   // Any images still loading?
   if (cimgLoading > 0) 
   {
      // Update status message
      window.status = strMsg + cimgLoading + " images remaining";
      setTimeout( "utlShowImgStatus( null, null )", cmsStatusWait );
   }
   else
   { 
      // Reset status message
      window.status = window.defaultStatus;
   }
}


/*
 * Gets a parameter value by name from the current location URL
 */
function utlGetURLParam( strName, strValue )
{
   // Initialize
   strParams = unescape( location.search );

   // Any params?
   if (strParams != null)
   {
      // Search each param
      fFound   = false;
      ichStart = 1;
      ichEnd   = ichStart;
      while (!fFound && (ichEnd != -1))
      {
         // Find end of param name
         ichEnd = strParams.indexOf( "=", ichStart );
   
         // Name with value?
         if (ichEnd != -1)
         {
            // Matching name?
            fFound = (strName == strParams.substring( ichStart, ichEnd ));

            // Locate value
            ichStart = ichEnd + 1;
            ichEnd   = strParams.indexOf( "&", ichStart );
            if (ichEnd == -1)
            {
               ichEnd = strParams.length;
            }
      
            // Requested param?
            if (fFound)
            {
               // Extract value
               strValue = strParams.substring( ichStart, ichEnd );
            }
            else
            {
               // Next param
               ichStart = ichEnd + 1;
            }
         }
      }
   }

   return (strValue);
}


/*
 * Gets the filename portion from a full file path
 */
function utlGetFilename( strPath )
{
   // Declare local variables
   var strName;
   var ichStart;
   var ichEnd;

   // Initialize
   strName = null;

   if (strPath != null)
   {
      // Find start of name
      ichStart = strPath.lastIndexOf( "/" );

      if (ichStart != -1)
      {
         ichStart++;
      }
      else
      {
         ichStart = 0;
      }

      // Find end of name
      ichEnd = strPath.indexOf( ".", ichStart );

      if (ichEnd == -1)
      {
         ichEnd = strPath.length;
      }

      // Extract ename
      strName = strPath.substring( ichStart, ichEnd );
   }

   return (strName);
}


/*
 * Pops up a window
 */
function utlPopUp( strURL )
{
   window.open( strURL
              , strPopUpName
              , "  width      = " + cxPopUp
              + ", height     = " + cyPopUp
              + ", top        = " + xPopUp
              + ", left       = " + yPopUp
              + ", scrollbars = 1"
              + ", resizable  = 1"
              );
}


/*
 * Sets the width of a group fields 
 * 
 * NOTE: This function must be called *after* all HTML formatting elements, 
 *       such as tables etc. have been closed.  Best called immediately before 
 *       the </BODY> tag.
 */
function utlSetFieldWidths( cx )
{
   var afld;
   var ifld;

   afld = utlArraySection( arguments, 1, arguments.length );
  
   if (afld != null)
   {
      // Measuring longest field?
      if (cx == -1)
      {
         for (ifld = 0; ifld < afld.length; ifld++)
         {
            cx = Math.max( cx, afld[ifld].offsetWidth );
         }
      }

      // Set width of each field
      for (ifld = 0; ifld < afld.length; ifld++)
      {
         afld[ifld].style.width = cx;
      }
   }
  
   return (cx);
}


/*
 * Sets a search field from a user field and optional category values
 */
function utlSetSearchField( fldSearch, strSearch, strValue, fIncValue )
{
   fldSearch.value = strSearch;

   if (fIncValue)
   {
      fldSearch.value += " " + strValue;
   }
}



/*
 * Shows the selected promotion in the promotion image link
 */
function utlShowPromotion( iprm )
{
   // Range check index (wrap around)
   iprm = Math.max( 1, (iprm % (navigator.astrPrm.length / 2)));

   // Find image link in document
   lnk = utlFindLink( "LNK_PRM" );
   if (lnk != null)
   {
      // Find string index
      istrPrm = iprm * 2;

      // Change promotion image and URL
      document.IMG_PRM.src = navigator.astrPrm[istrPrm];
      lnk.href             = navigator.astrPrm[istrPrm + 1];
   
      // Next promotion
      setTimeout( "utlShowPromotion( " + (iprm + 1) + " )", cmsPrmChange );
   }
}


/*
 * Stores a referrer URL as cookie for click-through tracker
 */
function utlTrack()
{
   strReferrer = document.referrer;
  
   if (strReferrer != null)
   {
      // Where does our domain name show up in URL (if at all)?
      ichDomainStart = strReferrer.indexOf( "flyingmule" );
      ichDomainEnd   = strReferrer.indexOf( "/", 7 );
  
      // From another domain?
      if ((ichDomainStart == -1) || (ichDomainStart > ichDomainEnd))
      {
         // Save referrrer in cookie for tracker
         utlSetCookie( "pass_referer", strReferrer, "/" );
      }
   }
}


/**
 * Writes an IFRAME tag
 */
function utlWriteIFrame( strName, strSrc, strWidth, strHeight )
{
   document.write( "<IFRAME " );
   utlWriteAtt( "name", strName );
   utlWriteAtt( "src", strSrc );
   utlWriteAtt( "width", strWidth );
   utlWriteAtt( "height", strHeight );
   document.write( "marginwidth='0' " );
   document.write( "marginheight='0' " );
   document.write( "frameborder='0' " );
   document.write( "scrolling='no'" );
   document.write( "style='visibility:hidden;'" );
   document.write( "onload='style.visibility=\"visible\";'" );
   document.writeln( " ></IFRAME>" );
}


/* 
 * Writes a rotating promotion image link
 */
function utlWritePromotion()
{
   // Write the promotion image link
   document.writeln( "<A name='LNK_PRM' href='/'><IMG name='IMG_PRM' border='0' alt='Click here for details...'></A>" );
   
   // Show first promotion
   utlShowPromotion( 1 );
}


/*
 * Writes a form for quickly adding a product to basket by product code
 */
function utlWriteAddProductForm()
{
   if (utlGetDebug() > 0)
   {
      document.writeln( '<TR>' ); 
      document.writeln( '   <TD nowrap="nowrap" class="clsBorder">' ); 
      document.writeln( '      <FORM name="AddProductForm" method="post" action="http://www.flyingmule.com/Merchant2/merchant.mvc">' ); 
      document.writeln( '         <SPAN class="clsSearch"><B>Add Product:</B></SPAN>' ); 
      document.writeln( '         <BR>' ); 
      document.writeln( '         <INPUT type="text" name="Product_Code" size="15" class="clsSearch">' ); 
      document.writeln( '         <INPUT type="image"  src="/img/pge_btn_addtocart.gif" align="absbottom" class="clsSearchImage"' ); 
      document.writeln( '         <INPUT type="hidden" name="Screen" value="BASK">' ); 
      document.writeln( '         <INPUT type="hidden" name="Action" value="ADPR">' ); 
      document.writeln( '         <INPUT type="hidden" name="Quantity" value="1">' ); 
      document.writeln( '      </FORM>' ); 
      document.writeln( '   </TD>' ); 
      document.writeln( '</TR>' ); 
   }
}


/*
 * Writes a form for quickly navigating to a product by product code
 */
function utlWriteGotoProductForm()
{
   if (utlGetDebug() > 0)
   {
      document.writeln( '<TR>' ); 
      document.writeln( '   <TD class="clsBorder">' ); 
      document.writeln( '      <FORM name="AddProductForm" method="post" action="http://www.flyingmule.com/Merchant2/merchant.mvc">' ); 
      document.writeln( '         <SPAN class="clsSearch"><B>Add Product:</B></SPAN>' ); 
      document.writeln( '         <BR>' ); 
      document.writeln( '         <INPUT type="text" name="Product_Code" size="15" class="clsSearch">' ); 
      document.writeln( '         <INPUT type="image"  src="/img/pge_btn_addtocart.gif" align="absbottom">' ); 
      document.writeln( '         <INPUT type="hidden" name="Screen" value="BASK">' ); 
      document.writeln( '         <INPUT type="hidden" name="Action" value="ADPR">' ); 
      document.writeln( '         <INPUT type="hidden" name="Quantity" value="1">' ); 
      document.writeln( '         <IMG src="/img/pge_spc.gif" width="220" height="1">' ); 
      document.writeln( '      </FORM>' ); 
      document.writeln( '   </TD>' ); 
      document.writeln( '</TR>' ); 
   }
}


/**
 * Matches multiple substrings in a string (case-sensitive)
 */
function utlMatchWords( strMatch, astrSearch, fModify )
{
   var cMatch;
   var istrSearch;


   // Initialize
   cMatch = 0;

   // Check each search string
   for (istrSearch = 0; istrSearch < astrSearch.length; istrSearch++)
   {
      // Search string found?
      if (strMatch.indexOf( astrSearch[istrSearch] ) != -1)
      {
         // Count string
         cMatch++;
      }
      else
      {
         if (fModify)
         {
            // Note search string not found
            astrSearch[istrSearch] = null;
         }
      }
   }

   // Return number of matched words
   return (cMatch);
}


/**
 * Converts a keyword search string to a Category search string
 */
function utlWordToCatSearch( cat, strSearch )
{
   var istrSearch;

   // Break search string into words
   astrSearch      = strSearch.split( " " );
   astrSearchUpper = strSearch.toUpperCase().split( " " );

   // Find category with closest matching name
   cat = cat.getChildByName( astrSearchUpper );

   // Found category? 
   if (cat != null)
   {
      // Use category id in search string
      strSearch = cat.getId( true );

      // Find matching words in name
      cat.matchName( astrSearchUpper, true );
           
      // Check each word in original search string
      for (istrSearch = 0; istrSearch < astrSearch.length; istrSearch++)
      {
         // Word not found in category name?
         if (astrSearchUpper[istrSearch] == null)
         {
            // Add to search string
            strSearch = strSearch + " " + astrSearch[istrSearch];
         }
      }
   }

   return (strSearch);
}


/**
 * Display Shipping Offer pop-up
 */
function utlShp()
{
   utlPopUp( "/shipping/" );
}
