var rootFolder = "/5.70/";

function addLoadEvent( func ) 
{
  var oldonload = window.onload;
  if ( typeof window.onload != 'function' ) 
  {
    window.onload = func;
  } else 
  {
    window.onload = function() {
      oldonload();
      func();
    }
  }
} // addLoadEvent

function insertAfter( newElement,targetElement ) 
{
  var parent = targetElement.parentNode;
  if ( parent.lastChild == targetElement ) 
  {
    parent.appendChild( newElement );
  } else 
  {
    parent.insertBefore( newElement, targetElement.nextSibling );
  }
} // insertAfter

function addClass( element, value )  
{
  if ( !element.className ) 
  {
    element.className = value;
  } else 
  {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
} // addClass

function prepareDeletion()
{
  if ( !document.getElementsByTagName ) return false;
  if ( !document.getElementById ) return false;
  var allLinks = document.getElementsByTagName( 'a' );
  var numLinks = allLinks.length;
  var deleteLink;
  for ( var i = 0; i < numLinks; i++ )
  {
    if ( allLinks[ i ].className != 'delete' )
      continue;
    deleteLink = allLinks[ i ];
    deleteLink.onclick = function() { return confirm( 'Are you sure you want to delete this item?\nDeletion cannot be undone.' ); };
  }
} // prepareDeletion

function showEditDelete( spanEl )
{
  spanEl.className = 'editDelete';
} // showEditDelete

function hideEditDelete( spanEl )
{
  spanEl.className = 'hidden';
} // hideEditDelete

function hideMessage()
{
  if ( !document.getElementById ) return false;
  var messageArea = document.getElementById( 'error_message' );
  if ( !messageArea )
    messageArea = document.getElementById( 'update_message' );
  if ( messageArea )
  {
    setTimeout( function() { messageArea.className = 'hidden'; }, 60 * 1000 ); // 1 minute, eh.
	return true;
  }
  return false;
} // hideMessage

function prepareEditDelete()
{
  if ( !document.getElementsByTagName ) return false;
  if ( !document.getElementById ) return false;
  var allTables = document.getElementsByTagName( 'table' );
  var numTables = allTables.length;
  var prepTable, prepRows, allSpans, numSpans, prepSpan, prepTD;
  for ( var i = 0; i < numTables; i++ )
  {
    prepTable = allTables[ i ];
    allSpans = prepTable.getElementsByTagName( 'span' );
    numSpans = allSpans.length;
    for ( var j = 0; j < numSpans; j++ )
    {
      if ( allSpans[ j ].className != 'editDelete' )
        continue;
      prepSpan = allSpans[ j ];
      hideEditDelete( prepSpan );
      prepTD = prepSpan.parentNode.parentNode; // span -> p -> td
      prepTD.onmouseover = function() 
      { 
        var theSpans = this.getElementsByTagName( 'span' ); 
        var numSpans = theSpans.length, showSpan;
        for ( var q = 0; q < numSpans; q++ )
        {
          showSpan = theSpans[ q ];
          if ( showSpan.className == 'editDelete' )
            break;
        }
        showEditDelete( showSpan );
      };
      prepTD.onmouseout = function() 
      { 
        var theSpans = this.getElementsByTagName( 'span' ); 
        var numSpans = theSpans.length, hideSpan;
        for ( var q = 0; q < numSpans; q++ )
        {
          hideSpan = theSpans[ q ];
          if ( hideSpan.className == 'editDelete' )
            break;
        }
        hideEditDelete( hideSpan );
      };
    }
  } 
} // prepareEditDelete

function closeMe( closeEl )
{
  if ( closeEl != null ) { closeEl.parentNode.removeChild( closeEl ); }
} // closeMe

function fadeErrors( element, classCheck, tagType )
{
  if ( !element ) var element = document.getElementById( 'mainContent' );
  if ( !classCheck ) var classCheck = 'errorMessage';
  if ( !tagType ) var tagType = 'label';
  var errors = element.getElementsByTagName( tagType );
  var totErrors = errors.length;
  var errorCount = 0;
  for ( var i = 0; i < totErrors; i++ )
  {
    if ( errors[i].className == classCheck )
    {
//      alert( errors[i].id );
      Fat.fade_element( errors[i].id, 30, 3000, '#FA9761' );
      errorCount++;
    } // error class
  }  // i all errors
  errors = null; totErrors = null;
  return errorCount;
}

function popupWindow( height, width, xpos, ypos )
{
  var xPos, yPos, wHeight, wWidth, windowID, contentID, captionText, closeCallback, isBuilt = false, isHidden = false;
  
  if ( height ) wHeight = height;
  if ( width ) wWidth = width;
  
  if ( xpos ) xPos = xpos;
  if ( ypos ) yPos = ypos;
  
  this.setHeight = function ( h ) { wHeight = h; };
  this.setWidth = function( w ) { wWidth = w; };
  
  this.setX = function( x ) { xPos = x; };
  this.setY = function( y ) { yPos = y; };
  
  this.setWindowID = function ( id ) { windowID = id; };
  this.getWindowID = function() { return windowID; };
  
  this.setContentID = function ( id ) { contentID = id; };
  this.getContentID = function () { return contentID; };
  
  this.setCaptionText = function( text ) { captionText = text; };
  this.setCloseCallback = function( callbackFunc ) { closeCallback = callbackFunc; };
  
  this.makeWindow = function( caption, callbackFunc )
  {
    if ( this.isBuilt == true && this.isHidden == true )
    {
      showWindow();
      return;
    }
    windowID = 'window_' + Math.floor(Math.random()*200);
    contentID = 'content_' + Math.floor(Math.random()*200);
    var windowDiv = makeElement( 'div', 'popupWindow', windowID );
    var headerDiv = makeElement( 'div', 'headerBox', windowID + '_header' );
    var contentDiv = makeElement( 'div', 'contentBox', contentID );
    
    if ( xPos ) 
    {
      windowDiv.style.left = xPos + 'px';
      windowDiv.style.marginLeft = '0px';
    }
    if ( yPos ) windowDiv.style.top = yPos + 'px';

    if ( wHeight )
    {
      contentDiv.style.minHeight = wHeight + 'px';
      contentDiv.style.height = wHeight + 'px';
      contentDiv.style.maxHeight = 'none';
    }
    
    if ( wWidth ) 
    {
      headerFiv.style.width = wWidth + 'px';
      contentDiv.style.width = wWidth + 'px';
      windowDiv.style.marginLeft = '0px';
    }

    if ( caption )
    {
      captionText = caption;
      var captionBox = makeElement( 'div', 'captionBox' );
      var captionH3 = makeElement( 'h3' );
      var captionNode = document.createTextNode( captionText );
      captionH3.appendChild( captionNode );
      captionBox.appendChild( captionH3 );
      headerDiv.appendChild( captionBox );
      captionBox = null; captionH3 = null; captionNode = null;
    }
    if ( callbackFunc )
      this.setCloseCallback( callbackFunc );

    var closeDiv = makeElement( 'div', 'closeBox' );
    var closeLink = makeElement( 'a' );
    closeLink.href = "javascript:void(0);";
    closeLink.onclick = function () { 
      if ( closeCallback )
        closeCallback();
      closeMe( ); 
    };
    var t = document.createTextNode( "Close" );
    closeLink.appendChild( t ); 
    closeDiv.appendChild( closeLink ); 
    headerDiv.appendChild( closeDiv );
    t = null; closeLink = null; closeDiv = null;

    windowDiv.appendChild( headerDiv );
    windowDiv.appendChild( contentDiv );
  
    document.getElementById( 'mainContent' ).appendChild( windowDiv );
    isBuilt = true;
    headerDiv = null; contentDiv = null; windowDiv = null;
  };  // makeWindow
  
  this.showLoading = function( )
  {
    var loadingDiv = '<div class="loadingAnim"></div>';
    var content = document.getElementById( contentID );
    content.innerHTML = loadingDiv;
    showWindow( windowID );
    content = null; loadingDiv = null;
  }; // showLoading
  
  this.setContent = function( contentText )
  {
    var content = document.getElementById( contentID );
    content.innerHTML = contentText;
    this.showWindow( windowID );
    content = null;
  }; // setContent
  
  this.positionByElement = function ( element, offsetX, offsetY )
  {
    if ( !element ) return;
    if ( !offsetX ) var offsetX = 0;
    if ( !offsetY ) var offsetY = 0;
    var clickedLeft = getElementPosition( element, "LEFT" ); 
    var clickedTop = getElementPosition( element, "TOP" );
    
    this.setX( clickedLeft + offsetX );
    this.setY( clickedTop + offsetY );
    clickedLeft = null; clickedTop = null; offsetX = null; offsetY = null;
  }; // positionByElement
  
  this.positionWithinWindow = function ( )
  {
    var deff = document.documentElement;
	var yHeight = (deff && deff.scrollTop) || document.body.scrollTop || window.pageYOffset;
//	alert( 'scroll height ?= ' + yHeight );
    this.setY( yHeight + 25 );
	deff = null; yHeight = null;
  }; // positionWithinWindow
  
  this.resizeToFitContent = function( )
  { // height only
    var contentDiv = document.getElementById( contentID );
	var contentHeight = contentDiv.scrollHeight;
    contentDiv.style.height = ( contentHeight + 10 ) + 'px';
	contentDiv.style.maxHeight = 'none';
	contentDiv = null; contentHeight = null;
  }; // resizeToFitContent
  
  this.resizeToFitWindow = function( )
  {
	var headerDiv = document.getElementById( windowID + '_header' );
    var contentDiv = document.getElementById( contentID );
    var windowDiv = document.getElementById( windowID );
    var dims = getBrowserDimensions();
//	alert( 'browser dimensions: \n' + dims );
	headerDiv.style.width = ( dims[ 1 ] - 50 ) + 'px';
    contentDiv.style.width = ( dims[ 1 ]- 50 ) + 'px';
    contentDiv.style.height = 'auto';
    contentDiv.style.maxHeight = 'none';
    windowDiv.style.marginLeft = '-' + ( ( dims[ 1 ] - 50 ) / 2 ) + 'px';
	headerDiv = null; contentDiv = null; windowDiv = null; dims = null;
  }; // resizeToFitWindow
  
  var showWindow = function( )
  {
    isHidden = false;
    var element = document.getElementById( windowID );
    element.className = 'popupWindow';
    if ( element.focus )
      element.focus();
	element = null;
  };  // showWindow

  var hideWindow = function( ) 
  {
    isHidden = true;
    var element = document.getElementById( windowID );
    element.className = 'hidden';
  };  // hideWindow
  
  this.closeWindow = function( )
  {
    closeMe();
  };  // closeWindow
  
  var closeMe = function()
  {
    var element = document.getElementById( windowID );
    if ( element ) 
    { 
      isBuilt = false;
      isHidden = false;
      element.parentNode.removeChild( element ); 
      element = null;
    }
  };

  var getElementPosition = function ( element, offsetType )
  {
    if ( !offsetType ) var offsetType = 'LEFT';
    offsetType = offsetType.toUpperCase();
    var offset;
    var parentElement;
    if ( offsetType == "LEFT" )
      offset = element.offsetLeft;
    else
      offset = element.offsetTop;
    parentElement = element.offsetParent;
    while( parentElement != null )
    {
        if ( offsetType == "LEFT" )
          offset += parentElement.offsetLeft;
        else
            offset += parentElement.offsetTop;
        parentElement = parentElement.offsetParent;
    } // parentElement !null
    return offset;
  }; // getElementPosition

  var getBrowserDimensions = function()
  {
    if ( window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX ) 
    {
      yScroll = window.innerHeight + window.scrollMaxY;
      xScroll = window.innerWidth + window.scrollMaxX;
      var deff = document.documentElement;
      var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
      var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
      xScroll -= (window.innerWidth - wff);
      yScroll -= (window.innerHeight - hff);
    } else if ( document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth )
    { // all but Explorer Mac
      yScroll = document.body.scrollHeight;
      xScroll = document.body.scrollWidth;
    } else 
    { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      yScroll = document.body.offsetHeight;
      xScroll = document.body.offsetWidth;
    }
    return Array( yScroll, xScroll );
  };  // getBrowserDimensions
  
  var makeElement = function ( type, className, id )
  {
    if ( !type ) return;
    var newElement = document.createElement( type );
    if ( !id ) var id = type + '_' + Math.floor(Math.random()*200);
    newElement.id = id;
    if ( className ) newElement.className = className;
    return newElement;
  }; // makeElement

} // popupWindow


function updateCreditReceived( )
{
  callType = document.getElementById( 'sc_ct_id' );
  if ( callType )
  {
	needed = document.getElementById( 'sc_credit_needed' );
	received = document.getElementById( 'sc_credit_received' );
	initials = document.getElementById( 'sc_credit_initials' );
	  
	if ( callType.options[callType.selectedIndex].value == 10 || callType.options[callType.selectedIndex].value == 14 )
	{
	  if ( needed ) 
	    needed.disabled = false;
	  if ( received )
	    received.disabled = false;
	  if ( initials )
	    initials.disabled = false;
	
	} else 
	{
	  if ( needed ) 
	  {
		needed.disabled = true;
		needed.checked = false;
	  }
	  if ( received )
	  {
	    received.disabled = true;
		received.checked = false;
	  }
	  if ( initials )
	  {
	    initials.disabled = true;
		initials.selectedIndex = 0;
	  }
	}
	needed = null;
	received = null;
	initials = null;
  } // callType
} // updateCreditReceived

function attachUpdateCR()
{
  callType = document.getElementById( 'sc_ct_id' );
  if ( callType )
  {
    if ( callType.type == "select-one" )
	{
	  callType.onchange = function( e ) { updateCreditReceived(); }
	}
  } // callType
} // attachUpdateCR

addLoadEvent( prepareDeletion );
addLoadEvent( prepareEditDelete );
addLoadEvent( fadeErrors );
addLoadEvent( hideMessage );

function checkForm() {
   sc_spellCheckers.resumeAll();
   return true;
}


//addLoadEvent( attachUpdateCR );
//addLoadEvent( updateCreditReceived );

// $j = jQuery.noConflict(); // set in layout.tpl.php

function table_tbody() {
  var collapseIcon = rootFolder + 'images/minus.gif';
  var collapseText = 'Collapse this section';
  var expandIcon = rootFolder + 'images/plus.gif';
  var expandText = 'Expand this section';
  $j('table.data tbody').each( function() {
        var $section = $j(this);
        
        $j('<img />').attr( 'src', collapseIcon )
          .attr( 'alt', collapseText )
          .prependTo( $section.find( 'th:first' ).not( 'span.tt th' ) )
          .addClass('clickable')
          .css('float', 'left')
          .click( function() {
              if ($section.is('.collapsed'))
              {
                  $section.removeClass('collapsed')
                    .find('tr:not(:first) td').show();
                  $j(this).attr('src', collapseIcon)
                    .attr( 'alt', collapseText );
              } else  // collapsed
              {
                  $section.addClass('collapsed')
                    .find('tr:not(:first) td').hide();
                  $j(this).attr('src', expandIcon)
                    .attr('alt', expandText );
              } // collapsed
            } )
          .trigger('click');
    } );



}


function rpbp_form() {
    /*
    $j('.disabler input.checkbox').each(function() {
        var $cb = $j(this);
        
        $cb.click(function() {
            if ($j(this).is(':checked'))
            {
                $j('form').find('input.'+$j(this).attr('id')).attr('disabled', true).attr('value', '');
            } else
            {
                $j('form').find('input.'+$j(this).attr('id')).attr('disabled', false);
            }
          });
      });
      */
      
    $j('input#sameasaddress').each(function() {
        var $cb = $j(this);
        $cb.click(function() {
            if($j(this).is(':checked'))
            {
                $_p = $j('input#rb_address').attr('value');
                $j('input#rb_assembly_address').attr('value', $_p).attr('disabled', true);
            } else
            {
                $j('input#rb_assembly_address').attr('disabled', false);
            }
          });
      });
      
    $j('input#rb_wmn_internal').each(function() {
        var $cb = $j(this);
        $cb.click(function() {
            if ($j(this).is(':checked'))
            {
                $j('form').find('input#rb_water_meter_number').attr('disabled', true).attr('value', 'Internal');
            } else
            {
                $j('form').find('input#rb_water_meter_number').attr('disabled', false).attr('value', '');
            }
          });
      });
      
    var $rbi = $j('form').find('input[name="rb_wmn_internal"]:checked').attr('value');
    if ($rbi == 1)
    {
        $j('form').find('input#rb_water_meter_number').attr('disabled', true).attr('value', 'Internal');
    } else
    {
        $j('form').find('input#rb_water_meter_number').attr('disabled', false);
    }
    
    $j('input#rb_new_install_yes, input#rb_new_install_no').each(function() {
        var $cb = $j(this);
        $cb.click(function() {
            if ($j(this).is(':checked') && $j(this).attr('value') == 1)
            {
                $j('form').find('li#li_permit_number').show();
            } else
            {
                $j('form').find('li#li_permit_number').hide();
            }
          });
      });
    var $_rbni = $j('form').find('input[name="rb_new_install"]:checked').attr('value');
    if ($_rbni == 2)
    {
        $j('form').find('li#li_permit_number').hide();
    } else 
    {
        $j('form').find('li#li_permit_number').show();
    }
    
    $j('input#rb_test_failed').each(function() {
        var $cb = $j(this);
        $cb.click(function() {
            if ($j(this).is(':checked'))
            {
                $j('form li#li_valve1 input, form li#li_valve2 input, form li#li_dprv input, form li#li_air_inlet input, form li#li_check_valve input').each(function() {
                    $j(this).attr('disabled', true);
                  });
                $j('form').find('input#rb_date_passed').attr('value', '');
            } else
            {
                $j('form li#li_valve1 input, form li#li_valve2 input, form li#li_dprv input, form li#li_air_inlet input, form li#li_check_valve input').each(function() {
                    $j(this).attr('disabled', false);
                  });
            }
          });
      });
    
    var $fail = $j('form').find('input[name="rb_test_failed"]:checked').attr('value');
    if ($fail == 1)
    {
        $j('form li#li_valve1 input, form li#li_valve2 input, form li#li_dprv input, form li#li_air_inlet input, form li#li_check_valve input').each(function() {
            $j(this).attr('disabled', true);
          });
    } else
    {
        $j('form li#li_valve1 input, form li#li_valve2 input, form li#li_dprv input, form li#li_air_inlet input, form li#li_check_valve input').each(function() {
            $j(this).attr('disabled', false);
          });
    }
    
    $j('input#rb_replace_assembly_yes, input#rb_replace_assembly_no').each(function() {
        var $cb = $j(this);
        $cb.click(function() {
            if ($j(this).is(':checked') && $j(this).attr('value') == 1)
            {
                $j('form').find('li#li_old_sn').show();
            } else
            {
                $j('form').find('li#li_old_sn').hide();
            }
          });
      });
    
    var $_rbra = $j('form').find('input[name="rb_replace_assembly"]:checked').attr('value');
    if ($_rbra == 2)
    {
        $j('form').find('li#li_old_sn').hide();
    } else 
    {
        $j('form').find('li#li_old_sn').show();
    }
    
    $j('input#rb_type_rp, input#rb_type_svb, input#rb_type_pvb, input#rb_type_dc').each(function() {
        var $cb = $j(this);
        $cb.click(function() {
            var $_cv1 = $j('form').find('li#li_valve1');
            var $_cv2 = $j('form').find('li#li_valve2');
            var $_dprv = $j('form').find('li#li_dprv');
            var $_ai = $j('form').find('li#li_air_inlet');
            var $_ckv = $j('form').find('li#li_check_valve');
            
            $_cv1.hide();
            $_cv2.hide();
            $_dprv.hide();
            $_ai.hide();
            $_ckv.hide();
            
            switch($j(this).attr('value'))
            {
                case 'RP' :
                    $_cv1.show();
                    $_cv2.show();
                    $_dprv.show();
                    break;
                case 'SVB' :
                case 'PVB' :
                    $_ai.show();
                    $_ckv.show();
                    break;
                case 'DC' :
                    $_cv1.show();
                    $_cv2.show();
                    break;
            }
          });
      });
      
    var $_rbtp = $j('form').find('input[name="rb_type"]:checked').attr('value');
    
    if ($_rbtp)
    {
        var $_cv1 = $j('form').find('li#li_valve1');
        var $_cv2 = $j('form').find('li#li_valve2');
        var $_dprv = $j('form').find('li#li_dprv');
        var $_ai = $j('form').find('li#li_air_inlet');
        var $_ckv = $j('form').find('li#li_check_valve');
        
        $_cv1.hide();
        $_cv2.hide();
        $_dprv.hide();
        $_ai.hide();
        $_ckv.hide();
        
        switch($_rbtp)
        {
            case 'RP' :
                $_cv1.show();
                $_cv2.show();
                $_dprv.show();
                break;
            case 'SVB' :
            case 'PVB' :
                $_ai.show();
                $_ckv.show();
                break;
            case 'DC' :
                $_cv1.show();
                $_cv2.show();
                break;
        }
    }
} // rpbp_form


$j(document).ready( function() {
  
  /*
  $j('#link31711').each(function() {
      $j(this).click(function() {
          // ?rc_id=5397&sc_id=21131
          var _uri = rootFolder + 'rpbpbackflow/list/list_include.php';
          var _vars = {'rc_id' : 5397, 'sc_id' : 21131, 'ajax' : 'true'};
          
          $j.get(_uri, _vars, function(results) {
              $j.get(_uri, _vars, function(results2) {
                  $j('#test31711').html(results2);
                  return;
                });
              
              
              //$j('#test31711').html(results);
              //return;
            });
            
          return false;
        });
    });
  */
  
  $j('.checklist input.add_new').hide();
  $j('.checklist input.checkbox').each( function() {
      var $cb = $j(this);
      if ( $j(this).is(':checked') )
          $j(this).nextAll('.add_new').show().attr('disabled', false );
          
      $cb.click( function() {
          if ( $j(this).is(':checked') ) 
          {
              $j(this).nextAll('.add_new').fadeIn('fast').attr('disabled', false );
          } else
          {
              $j(this).nextAll('.add_new').fadeOut('fast').attr('disabled', true );
          }
        } );
    } );
  //$j('.checklist input.checkbox').trigger('click');
  
  $j('input#sc_credit_needed_check').each(function() {
        var $_received = $j('input#sc_credit_taking_ticket');
        if ($j(this).attr('value') == 1 && !$_received.is(':checked'))
        {
            alert('Ensure credit picking ticket is received from vendor.');
        }
    });
  
  table_tbody();
  
  rpbp_form();
  
  /*
  $j().each(function() {
    });
  
  $j().each(function() {
    });
  
  */
  
} );


