(function() {
  var $Fn   = Neaux.Function;
  var $Elem = Neaux.Html.Element;
  var HOME_THUMB_FOCUS_DELAY = 300;
  var HOME_TAB_FOCUS_DELAY = 400;
  var HOME_CACHE_IMAGES = ['home_gears.jpg','home_globe.jpg','home_target.jpg'];
  var HOME_BANNER_SECTIONS = ['target','globe','gears'];
  var CONTACT_SUCCESS_MSG = 'Your request was submitted successfully.  We will contact you shortly.';
  var DM_EMAIL = 'dmsales@datamasons.com';

  var tmpOverlay = null;
  
  DM = {
    server: null,               // XmlHttpRequest object
    menuHome: null,             // The Home menu anchor
    menuNodes: [],              // Node hierarchy path to current page 
    
    // Home Page Only
    homeThumb: null,            // Thumbnail on banner corresponding to currently displayed banner image
    homeTab: null,              // Active tab on lower tab panel
    homeThangPending: null,     // Candidate tab for pending selection (timed hover handling)
    homeThangPendingTID: null,  // Timer ID to select pending tab upon expiration

    // To adjust the heights of the inner page content areas (align left,right sections)
    TweakContentHeight: function() {
      var left = $ID('content_left').offsetHeight;// + 168;
      var right = $ID('content_right').offsetHeight;
      var max = left > right ? left : right;
      var target = left > right ? 'content_right' : 'content_left';
      $ID(target).style.height = max + 'px';
    },
    
    // To do menu-y things that CSS can't intuitivelt do, to wit - highlight current menu
    TweakMenu: function( aMenuID) {
      // Get all of the anchors in the menu hierarchy, iterate through them until 
      // the href attribute matches the page name
      var anchors = document.getElementById(aMenuID).getElementsByTagName('a');
      for ( var i = 0; i < anchors.length; ++i) {
        if ( window.location.href == anchors[i].href)
          break;
      }

      DM.menuHome = anchors[0]; // Save this for breadcrumb generation

      // -- HGL - Changed my mind here.  Will not hightlight menu for default invocation of Home Page.
      //          Delete code after we determine that this is OK.
      // If there wasn't a match, set the current page to the home page(first anchor). 
      // This happens when http:/www.example.com , i.e, no file name, is requested.
      // var thePage = ( i < anchors.length) ? i : 0;
      // var ptr = anchors[thePage];

      // For a page not in the menu (including default home page access) don't highlight
      if ( i == anchors.length) return;

      // Now we go walk back up the tree and get the node hierarchy and save it for later (e.g., for breadcrumbs)
      var ptr = anchors[i];
      while( ptr && ptr.id != aMenuID) {
        if ( ptr.nodeName.toLowerCase() == 'li')
          DM.menuNodes.push(ptr);
        ptr = ptr.parentNode;
      }
      // Put 'em in top-down order
      DM.menuNodes.reverse();

      // Highlight the menu items with active context
      for ( var i in DM.menuNodes) {
        var theNode = DM.menuNodes[i].getElementsByTagName('a')[0];
        $Elem.Style(theNode, { backgroundColor: '#1c588e', color: '#fff' });
      }
    },
    
    SetBreadcrumbs: function() {
      // Some pages may not have a breadcrumb area (e.g. home page)
      var theBca = $ID('breadcrumb_area');
      if ( !theBca) return;
 
      var theFrag = document.createDocumentFragment();
      var theClone = DM.menuHome.cloneNode(true);
      $Elem.Style();
      theFrag.appendChild(theClone);
      for ( var i in DM.menuNodes) {
        var theNode = DM.menuNodes[i].getElementsByTagName('a')[0];
        if ( theNode == DM.menuHome) continue;
        theFrag.appendChild(document.createTextNode(' > '));
        theClone = theNode.cloneNode(true);
        theClone.style.cssText = '';
        theFrag.appendChild(theClone);
      }
      theBca.replaceChild( theFrag, theBca.firstChild);
    },

    // Optimize image loads - preload initially hidden images on home page
    CacheImages: function( aImgList) {
      for ( var i in aImgList) {
        var img = new Image();
        img.src = 'images/'+aImgList[i];
      }  
    },

    InitHomeBanner: function() {
      DM.homeThumb = 'target';
      var thumb = Math.floor(Math.random()*HOME_BANNER_SECTIONS.length);
      DM.SetHomeThumb($ID(HOME_BANNER_SECTIONS[thumb]));
    },

    SetHomeThumb: function( aNewThumb) {
      if ( aNewThumb.id != DM.homeThumb) {
        // Get the current and target banner selections (indexed by thumb name)
        var theSource = typeof DM.homeThumb == 'string' ? $ID('banner_' + DM.homeThumb) : null;
        var theTarget = $ID('banner_' + aNewThumb.id);
        // Assigning the thumb name as the content_top class name swaps the background image
        $ID('content_top').className = aNewThumb.id;
        // Make the target visible & the current banner invisible
        theTarget.style.display = 'block';
        if (theSource) theSource.style.display = 'none';
        // Clear the thumb_selected class from previous banner thumbnail
        if ( DM.homeThumb) {
          $ID( DM.homeThumb).className = null;
          $ID( DM.homeThumb).offsetParent.getElementsByTagName('a')[0].className = null;
        }
        DM.homeThumb = aNewThumb.id;
        // Set the thumb_selected class from previous banner thumbnail
        aNewThumb.className = 'thumb_selected';
        aNewThumb.offsetParent.getElementsByTagName('a')[0].className = 'link_selected';
      }
    },

    SendForm: function( aRequestID, aFrmName, aCallbackFn) {
      if ( !DM.server) DM.server = new Neaux.HttpRequest( { action: 'assets/datamasons.php'} );
      var theElms = $ID(aFrmName).elements;
      var theMap = { dm_command: aRequestID };
      for ( var i=0; i < theElms.length; ++i) {
        var elm = theElms[i];
        if ( !elm.name) continue;
        theMap[elm.name] = elm.value;
      }
      $ON( DM.server, 'RequestComplete', aCallbackFn);
      var theData = Neaux.Http.EncodeQueryString(theMap);
      DM.server.Send( { data: theData } );
    },

    SetHomeTab: function( aNewTab) {
      if ( aNewTab.id != DM.homeTab) {
        //$ID( aNewTab.id).className = aNewTab.id != 'evl' ? 'tab tab_selected' : 'tab tab_selected_end';
        $ID( aNewTab.id).className = 'tab tab_selected';
        $ID( 'c_'+aNewTab.id).style.display = 'block';
        if ( DM.homeTab) {
          $ID( DM.homeTab).className = 'tab';
          $ID( 'c_'+DM.homeTab).style.display = 'none';
        }
        DM.homeTab = aNewTab.id;
      }
    },
    HandleHomeTopContent: function( aEvt) {
      if ( aEvt.target.tagName.toLowerCase() != 'img') return;
      if ( aEvt.target.id == DM.homeThumb) return;   // Already on this thumb - outta here
      switch( aEvt.type) {
        case 'mouseover':
          DM.homeThangPendingTID = $Fn.Defer(DM.HandleHomeThumbTimeout, HOME_THUMB_FOCUS_DELAY, this);
          DM.homeThangPending = aEvt.target;
          break;
        case 'mouseout':
        case 'click':
          if ( DM.homeThangPendingTID) {
            $Fn.CancelDeferred( DM.homeThangPendingTID);
            DM.homeThangPendingTID = null;
            DM.homeThangPending = null;
          }
          if ( aEvt.type == 'click') DM.SetHomeThumb(aEvt.target);
          break;
      }
    },
    HandleHomeTab: function( aEvt) {
      if ( aEvt.target.id == 'tab_box') return;   // Not a tab - nothing to do
      if ( aEvt.target.id == DM.homeTab) return;  // Already on this tab - outta here
      if ( aEvt.target.id == 'sm' || aEvt.target.id == '' || aEvt.target.className == 'js_nohover') return;  // Not executable - social media tab

      switch( aEvt.type) {
        case 'mouseover':
          DM.homeThangPendingTID = $Fn.Defer(DM.HandleHomeTabTimeout, HOME_TAB_FOCUS_DELAY, this);
          DM.homeThangPending = aEvt.target;
          break;
        case 'mouseout':
        case 'click':
          if ( DM.homeThangPendingTID) {
            $Fn.CancelDeferred( DM.homeThangPendingTID);
            DM.homeThangPendingTID = null;
            DM.homeThangPending = null;
          }
          if ( aEvt.type == 'click') DM.SetHomeTab(aEvt.target);
          break;
      }
    },

    HandleHomeThumbTimeout: function() {
      var theThumb = DM.homeThangPending;
      DM.homeThangPendingTID = null;
      DM.homeThangPending = null;
      DM.SetHomeThumb(theThumb);
    },
    HandleHomeTabTimeout: function() {
      var theTab = DM.homeThangPending;
      DM.homeThangPendingTID = null;
      DM.homeThangPending = null;
      DM.SetHomeTab(theTab);
    },

    DoContactFormResults: function() {
      if ( DM.server.OK()) {
        var theResponse = DM.server.Text();
        var theStatus = theResponse.indexOf('ERROR:');
        var theStatusText = CONTACT_SUCCESS_MSG;
        var theMsgArea = $ID('frm_contact_message_area');
//alert(theResponse);
        if ( theStatus >= 0) {
          theStatus += 'ERROR:'.length;
          theStatusText = 'Please make the following corrections:<br/>' + theResponse.substr(theStatus);
          $ID('btn_send').disabled = false;
        }
        else {
          var frm = $ID('frm_contact')
          frm.reset();
          frm.style.display = 'none';
          theMsgArea.style.padding = '8px 0';
        }
        theMsgArea.innerHTML = theStatusText;
        theMsgArea.style.color = theStatus < 0 ? '#56a0c7' : '#ff0000';
        theMsgArea.style.textAlign = 'center';
        theMsgArea.style.display = 'block';
      }
      else {
        alert( 'An Unknown Server Error Occurred');
        $ID('btn_send').disabled = false;
      }
    },
    HandleContactForm: function( aEvt) {
      $ID('btn_send').disabled = true;
      DM.SendForm( 'contact', 'frm_contact', DM.DoContactFormResults);
    },
    ShowOverlay: function( aContent) {
      var theOverlay = $ID('_nw_overlay');
      var scr = Neaux.Html.Viewport();
      if ( !theOverlay) {
        theOverlay = $Elem.Create( { tagName: 'div', id: '_nw_overlay', style: { position: 'absolute', top: '0px', 
              left: '0px', height: '100%', width: '100%', zIndex: 100, backgroundImage: 'url(images/popup_bg.png)', 
              backgroundRepeat: 'repeat', display: 'none', width: scr.width+'px', height: scr.height+'px' } }, document.body );
      }
      $Elem.Style(aContent, { position: 'absolute', top: '0px', left: '0px', visibility: 'hidden', display: 'block', zIndex: 200 });
      var newTop = Math.ceil((scr.height - aContent.offsetHeight)/2) + 'px';
      var newLeft = Math.ceil((scr.width - aContent.offsetWidth)/2) + 'px';
      $Elem.Style(aContent, { top: newTop, left: newLeft, visibility: 'visible' });
      theOverlay.style.display = 'block';
      aContent.style.display = 'block';
    },
    InitEmail: function() {
      //$ID('txt_email_to').value = DM_EMAIL;
      $ID('lnk_email_launch').href = 'mailto:'+DM_EMAIL;
      $ON('header_email','click',DM.HandleEmailClick);
      $ON('frm_email_close','click',DM.HideEmailForm);
      $ON('btn_send_email','click',DM.DoEmailForm);
      $ON('lnk_email_launch','click', function() { DM.HideEmailForm() } );
    },
    HandleEmailClick: function(aEvt) { DM.ShowEmailForm(); aEvt.preventDefault(); },
    ShowEmailForm: function() {
      DM.ShowOverlay($ID('frm_email_container'));
      $ID('btn_send_email').disabled = false;
    },
    HideEmailForm: function() { 
      $ID('_nw_overlay').style.display = 'none'; 
      $ID('frm_email_container').style.display = 'none' 
    },
    DoEmailForm: function() {
      $ID('btn_send_email').disabled = true;
      DM.SendForm( 'email', 'frm_email', DM.DoEmailFormResults);
    },
    DoEmailFormResults: function() {
      if ( DM.server.OK()) {
        var theResponse = DM.server.Text();
        var theStatus = theResponse.indexOf('ERROR:');
        var theStatusText = CONTACT_SUCCESS_MSG;
        var theMsgArea = $ID('frm_email_message_area');
        if ( theStatus >= 0) {
          theStatus += 'ERROR:'.length;
          theStatusText = 'Please make the following corrections:<br/>' + theResponse.substr(theStatus);
          $ID('btn_send_email').disabled = false;
        }
        else {
          $ID('frm_email').reset();
          $ID('frm_email_body').style.display = 'none';
          theMsgArea.style.padding = '8px 0';
        }
        theMsgArea.innerHTML = theStatusText;
        theMsgArea.style.color = theStatus < 0 ? 'black' : 'red';
        theMsgArea.style.textAlign = 'center';
        theMsgArea.style.display = 'block';
      }
      else {
        alert( 'An HTTP Error Occurred');
        $ID('btn_send_email').disabled = false;
      }
    },
    InitChat: function() {
      var theChat = $ID('_lpChatBtn');
      theChat.href = 'https://server.iad.liveperson.net/hc/19101582/?cmd=file&file=visitorWantsToChat&site=19101582&byhref=1&imageUrl=https://server.iad.liveperson.net/hcp/Gallery/ChatButton-Gallery/English/General/1a/';
      theChat.target='chat19101582';
      theChat.onClick = function() {
        window.open('https://server.iad.liveperson.net/hc/19101582/?cmd=file&file=visitorWantsToChat&site=19101582&imageUrl=https://server.iad.liveperson.net/hcp/Gallery/ChatButton-Gallery/English/General/1a/&referrer='+escape(document.location),'chat19101582','width=475,height=400,resizable=yes');
        return false;
      }
    },
    InitSearch: function() {
      var theSearch = $ID('img_search');
      $ON('img_search','click', function( aEvt) {
        $ID('cse-search-box').submit();
        return aEvt.preventDefault();
      });
    },
    ToggleCaseStudy: function() {
      var cas = $ID('v_case'), vid = $ID('v_video'), aut = $ID('v_auto'), theCookie, theValue;
      if (!cas) return;
      theCookie = new Neaux.Cookie( { name: 'home_erp_switch' } );
      theValue = theCookie.Read() || 0;
      cas.style.display = (theValue % 3 == 0) ? 'block' : 'none';
      aut.style.display = (theValue % 3 == 1) ? 'block' : 'none';
      vid.style.display = (theValue % 3 == 2) ? 'block' : 'none';
      //window.status = 'Cookie: ' + theValue;
      theCookie.Write( { name: 'home_erp_switch', value: ++theValue, lifetime: 60 * 24 * 365 });
    },

    // Start gets executed on all pages
    Start: function() {
      // If there a contact form, listen for a click on the submit button
      if ( $ID('frm_contact')) $ON('btn_send','click',DM.HandleContactForm);
      if ( $ID('frm_partner_container')) $ON('btn_send_partner','click', DM.HandlePartnerForm);
      if ( $ID('frm_wp_container')) $ON('btn_send_wp','click', DM.DoWhitepaperRetrieval);
      if ( $ID('wp_fetch_link')) DM.GetWhitepaperLink();
      /*
      if ( $ID('whitepaper_box')) {
        var wpc = $ID('whitepaper_box').removeChild($ID('frm_wp_container'));
        document.body.appendChild(wpc);
        $ON('whitepaper_action,whitepaper_icon','click',DM.HandleWhitepaperRequest);
      }
      */
      // Save the current menu context & highlight current menu item (can't do with CSS)
      DM.TweakMenu('header_nav');
      DM.SetBreadcrumbs();
      DM.InitEmail();
      //DM.InitChat();
      DM.InitSearch();
    },
    // StartHome gets executed on the home page only
    StartHome: function() { 
      DM.CacheImages(HOME_CACHE_IMAGES);
      DM.homeTab = 'erp';
      DM.ToggleCaseStudy();
      $ON('content_top_right', 'mouseover,mouseout,click', DM.HandleHomeTopContent);
      $ON('tab_box', 'mouseover,mouseout,click', DM.HandleHomeTab);
    },
    toString: function() { return '[DM]'; }
  };

  DM.HandlePartnerForm = function( aEvt) {
    $ID('btn_send_partner').disabled = true;
    DM.SendForm( 'partner', 'frm_partner', DM.DoParterFormResults);
  }
  DM.DoParterFormResults = function() {
    if ( DM.server.OK()) {
      var theResponse = DM.server.Text();
      var theStatus = theResponse.indexOf('ERROR:');
      var theStatusText = CONTACT_SUCCESS_MSG;
      var theMsgArea = $ID('frm_wp_message_area');
      if ( theStatus >= 0) {
        theStatus += 'ERROR:'.length;
        theStatusText = 'Please make the following corrections:<br/>' + theResponse.substr(theStatus);
        $ID('btn_send_partner').disabled = false;
        theMsgArea.innerHTML = theStatusText;
        theMsgArea.style.color = theStatus < 0 ? 'black' : 'red';
        theMsgArea.style.textAlign = 'center';
        theMsgArea.style.display = 'block';
      }
      else {
        $ID('frm_partner').reset();
        document.location = 'thank_you_partner.html';
      }
    }
    else {
      alert( 'An HTTP Error Occurred');
      $ID('btn_send_partner').disabled = false;
    }
  };



  /****** NEW CONTENT ******/
  DM.GetWhitepaperLink = function() {
    var theWhitepaper = 'DataMasons_AutomotiveEDI_WhitePaper.pdf';
    var theAnchor = $ID('wp_fetch_link');
    theAnchor.href = 'whitepapers/' + theWhitepaper;
    theAnchor.innerHTML = 'Understanding Automotive EDI';
  };
  DM.HandleWhitepaperRequest = function( aEvt) { 
    //DM.ShowWhitepaperForm(); 
    //$ON('frm_wp_close','click', DM.HideWhitepaperForm);
    $ON('btn_send_wp','click', DM.DoWhitepaperRetrieval);
    //aEvt.preventDefault(); 
  };
  DM.ShowWhitepaperForm = function( aEvt) {
    DM.ShowOverlay($ID('frm_wp_container')); 
  };
  DM.HideWhitepaperForm = function() { 
    $ID('_nw_overlay').style.display = 'none'; 
    $ID('frm_wp_container').style.display = 'none';
  };
  DM.DoWhitepaperRetrieval = function() {
    $ID('btn_send_wp').disabled = true;
    DM.SendForm( 'whitepaper', 'frm_wp', DM.DoWhitepaperFormResults);
  };
  DM.DoWhitepaperFormResults = function() { 
    if ( DM.server.OK()) {
      var theResponse = DM.server.Text();
      var theStatus = theResponse.indexOf('ERROR:');
      var theStatusText = CONTACT_SUCCESS_MSG;
      var theMsgArea = $ID('frm_wp_message_area');
      if ( theStatus >= 0) {
        theStatus += 'ERROR:'.length;
        theStatusText = 'Please make the following corrections:<br/>' + theResponse.substr(theStatus);
        $ID('btn_send_wp').disabled = false;
        theMsgArea.innerHTML = theStatusText;
        theMsgArea.style.color = theStatus < 0 ? 'black' : 'red';
        theMsgArea.style.textAlign = 'center';
        theMsgArea.style.display = 'block';
      }
      else {
        $ID('frm_wp').reset();
        //DM.HideWhitepaperForm();
        document.location = 'thank_you.html';
      }
    }
    else {
      alert( 'An HTTP Error Occurred');
      $ID('btn_send_wp').disabled = false;
    }
  };
})();


