 /* globals */

var EU = {};
EU.txtSearch_cleared = false;
EU.txtSearch_checkvalue = function(obj) {
  if (!EU.txtSearch_cleared) {
    obj.value = '';
    EU.txtSearch_cleared = true;
  }
}

EU.Popover = {};
EU.Popover.tagId = 'a_popover';
EU.Popover.close = function() {
  // Are we in the div tag?
  var interstitialDivTag = null;
  if (window.parent &&
    window.parent.document &&
    window.parent.document.getElementById(EU.Popover.tagId)) {
    window.parent.$(EU.Popover.tagId).remove();
    return 0;
  }

  // Not in the popover
  interstitialDivTag = $(EU.Popover.tagId);
  if (interstitialDivTag!=null) {
    interstitialDivTag.remove();
  }
  return 0;
}


/*
  Popover creator
*/
EU.Popover.open = function(url, width, height, isText) {
  var interstitialDivTag = $(EU.Popover.tagId);
  var i_width = (width<=0 || undefined == width)?500:width;
  var i_height = (height<=0 || undefined == height)?400:height;

  if (interstitialDivTag==null) {
    interstitialDivTag = document.createElement('DIV');
    interstitialDivTag.style.width =  i_width + 'px';
    interstitialDivTag.style.height = i_height + 'px';
    interstitialDivTag.id = EU.Popover.tagId;
    interstitialDivTag.className = 'popover'
    document.body.insertBefore(interstitialDivTag, document.body.firstChild);
    interstitialDivTag = $(interstitialDivTag)
  }

  if (isText) {
    interstitialDivTag.innerHTML = url;
  } else {
    var c = (new Date()).getTime()
    var iHtml = "<iframe border='0' style='width:100%; height: 100%' sr" +
                "c='" + url +
                "' id='pframe" + c +
                "' name='interstitialFrame" + c + "'></iframe>";

    interstitialDivTag.innerHTML = iHtml;
  }

  interstitialDivTag.setStyle({
    'left':(document.body.clientWidth/2 - i_width/2)+'px',
    'visibility':'visible',
    'display':'block'
  });
}


EU.Popover.currentPopover=null;
EU.Popover.showPopover=function (elementName) {
  if (EU.Popover.currentPopover!=null) {
    EU.Popover.hidePopover(elementName);
  }
  $(elementName).style.zIndex=1000;
  var defaultWidth = 400;
  if ($(elementName).style.width) {
    defaultWidth = $(elementName).style.width.replace(/[a-z ]+/,"");
  }

  $(elementName).style.left = (document.body.scrollWidth/2-defaultWidth/2) + "px";

  Effect.BlindDown($(elementName));
  EU.Popover.currentPopover = elementName;
}
EU.Popover.hidePopover = function() {
  if (EU.Popover.currentPopover!=null) {
    Effect.SlideUp($(EU.Popover.currentPopover));
    EU.Popover.currentPopover = null;
  }
}

EU.Popover.togglePopover=function(elementName) {
  if (EU.Popover.currentPopover==null || EU.Popover.currentPopover!=elementName) {
    EU.Popover.showPopover(elementName);
  } else {
    EU.Popover.hidePopover(elementName);
  }
}



/*
  Spawn a popup. returns false to cancel the click.
  Usage:
  DEFAULT
    <a href="wacky.html"
       onclick="return a_popup(this)">
      Foo
    </a>
  Set width/height
    <a href="wacky.html"
       onclick="return a_popup(this, 200, 300)">
      Foo
    </a>

  Custom style - not resizeable
    <a href="wacky.html"
       onclick="return a_popup(this, 200, 300, 'titlebar,scrollbars=yes,resizable=no')">
      Foo
    </a>

  Custom style - and text
    <a href="wacky.html"
       onclick="return a_popup(this, 200, 300, 'titlebar,scrollbars=yes,resizable=no', 'doh')">
      Foo
    </a>
*/
function a_popup() {
  var a_element=null;
  var a_width=null;
  var a_height=null;
  var a_windowStyle=null;
  var a_customText=null;

  switch (a_popup.arguments.length) {
    case 5: a_customText = a_popup.arguments[4];
    case 4: a_windowStyle = a_popup.arguments[3];
    case 3: a_height = a_popup.arguments[2];
    case 2: a_width = a_popup.arguments[1];
    case 1: a_element = a_popup.arguments[0];
    default:
  }

  var aTarget = a_element.target;

  if (aTarget==null || aTarget=="") {
    aTarget = "pop";
  }


  if (a_windowStyle==null) {
    a_windowStyle = "titlebar,scrollbars=yes,resizable=yes";
  }

  if (a_width==null || a_width <=0) {
    a_width=400;
  }
  if (a_height==null || a_height <=0) {
    a_height=400;
  }

  a_windowStyle+= (",left="+((screen.availWidth - a_width) / 2));
  a_windowStyle+= (",width="+a_width);

  a_windowStyle+= (",top="+(((screen.availHeight - a_height) / 2 ) - 30));
  a_windowStyle+= (",height="+a_height);

  var w;
  if (a_customText!=null) {
    w = window.open('', aTarget, a_windowStyle);
    try {
      w.document.close();
      w.document.open();
      w.document.writeln(a_customText);
      try {
        w.document.close();
      } catch(e){}
    } catch(e){}
  } else {
    w = window.open(a_element.href, aTarget, a_windowStyle);
  }
  w.focus();

  return false;
}



EU.Cookie = {};

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
EU.Cookie.set = function(name, value, path, expires, domain, secure) {
    document.cookie= name + "=" + encodeURIComponent(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 * Returns null if cookie does not exist.
 */
EU.Cookie.get = function(name) {
  try {
    var cookies = document.cookie;
    var index = cookies.indexOf(name + "=");
    if (index == -1) return null;
    index = cookies.indexOf("=", index) + 1;
    var endstr = cookies.indexOf(";", index);
    if (endstr == -1) endstr = cookies.length;
    return decodeURIComponent(cookies.substring(index, endstr));
  } catch(e) {}
  return null;
}

/**
 * Deletes the specified cookie.
 * delete is areserved word in javascript
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 */
EU.Cookie.remove = function (name, path) {
    if (EU.Cookie.get(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}


EU.Menu = {};


EU.updateCartCount = function updateCartCount() {
  var opt = {
    method: 'post',
    onSuccess: function(t) {
      $('cartCount').innerHTML  = (t.responseText.trim());
      EU.Cookie.set('cartCount', (t.responseText.trim()), "/");
    }
  }


  new Ajax.Request('cart_count.asp', opt);
}


var s_linkTrackEvents;
EU.Omniture = {};
EU.Omniture.addLinkTrackEvents = function(myEvent) {
  if (s_linkTrackEvents != null && s_linkTrackEvents != "") {
    s_linkTrackEvents += "," + myEvent;
  } else {
    if (myEvent.indexOf('event') > 0) {
      s_linkTrackVars = 's_events';
      s_linkTrackEvents = myEvent;
    } else
    s_linkTrackEvents = myEvent;
  }
}

/* for focus fun */
EU.hack1 =  function() {
    try {
    var x = function(inputs) {
      for (var i=0; i<inputs.length; i++) {
        if (!inputs[i].type.match(/(button|radio|check|image)/)) {
          inputs[i].onfocus=function() {
            this.className+=" focussy";
          }
          inputs[i].onblur=function() {
            this.className=this.className.replace(new RegExp(" focussy\\b"), "");
          }
        }
      }
    }
    x(document.getElementById("content").getElementsByTagName("INPUT"));
    x(document.getElementById("content").getElementsByTagName("TEXTAREA"));
    x(document.getElementById("content").getElementsByTagName("SELECT"));
  } catch(aintsupported) {
  }
}
/* Set focus on first visible text field */
EU.skipHack2 = false;
EU.hack2 =  function() {
  if(EU.skipHack2) {
    return;
  }
    try {
    var x = function(inputs) {
      for (var i=0; i<inputs.length; i++) {
        if (inputs[i].type.match(/text/i)) {
          inputs[i].focus();
          return;
        }

      }
    }
    x(document.getElementById("content").getElementsByTagName("INPUT"));
  } catch(aintsupported) {
  }
}

if (window.attachEvent) window.attachEvent("onload", EU.hack1);
Event.observe(window, "load", EU.hack2);

EU.setFocusOnLoad = function(fieldName) {
  EU.skipHack2 = true;
  var f = function() {
    $$("#content select[name=#{name}],#content input[name=#{name}]".interpolate({'name':n})).each(function (t){
      t.focus();
    });
  }
  Event.observe(window, "load", f);
};





/* FLASH SUPPORT */
var flashInstalled = false;
var flashMajorVersion = 0;

function detectFlash() {
  var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
  if (plugin) {
    flashInstalled = true;
    var words = navigator.plugins["Shockwave Flash"].description.split(" ");
    for (var i = 0; i < words.length; ++i) {
      if (isNaN(parseInt(words[i])))
      continue;
      flashMajorVersion = words[i];
    }
  } else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)) {
          // test for at least version 7
    var version;
    var axo;
    var e;
    try {
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
      version = axo.GetVariable("$version");
    } catch (e) {
      version = -1;  // user does not have at least version 7
    }
    if (version == -1 ) {
      flashInstalled = false;
    } else if (version != 0) {
            // user has at least version 7 - split the version string to determine
      var tempArray         = version.split(" ");
      var tempString        = tempArray[1];
      var versionArray      = tempString.split(",");
      flashMajorVersion     = versionArray[0];
      flashInstalled = true;
    }
  }
}

function embedFlash( flashContainerId, pathToFlashFile, swfWidth, swfHeight, requiredVersion, paramString) {
      var flashText = '';
      flashText = flashText + '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
      flashText = flashText + '  codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" ';
      flashText = flashText + ' ID="Main" WIDTH="' + swfWidth + '" HEIGHT="' + swfHeight + '" ALIGN="">';
      flashText = flashText + ' <PARAM NAME=movie VALUE="' + pathToFlashFile + paramString + '"> <PARAM NAME=loop VALUE=false> <PARAM NAME=menu VALUE=false> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#FFFFFF>  <PARAM NAME=wmode VALUE=transparent> <PARAM NAME="allowScriptAccess" VALUE="sameDomain" />';
      flashText = flashText + ' <EMBED src="' + pathToFlashFile + paramString + '" loop=false menu=false quality=high bgcolor=#FFFFFF allowScriptAccess="sameDomain"  ';
      flashText = flashText + ' swLiveConnect=TRUE WIDTH="' + swfWidth + '" HEIGHT="' + swfHeight + '" WMODE=transparent NAME="Main" ALIGN=""';
      flashText = flashText + ' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">';
      flashText = flashText + ' </EMBED>';
      flashText = flashText + ' </OBJECT>';
      var popoverContent = $('popoverContent');
      if (popoverContent) {
        popoverContent.innerHTML = flashText;
      } else {
        document.getElementById(flashContainerId).innerHTML = flashText;
      }
}

function embedVideo( flashContainerId, pathToFlashFile, swfWidth, swfHeight, requiredVersion, flashVars) {
    if ( flashInstalled && flashMajorVersion>=requiredVersion ) {
      var videoText = '';
      videoText = videoText + '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
      videoText = videoText + '  codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" ';
      videoText = videoText + ' ID="Main" WIDTH="' + swfWidth + '" HEIGHT="' + swfHeight + '" ALIGN="">';
      videoText = videoText + ' <PARAM NAME=movie VALUE="' + pathToFlashFile + '"> <PARAM NAME=loop VALUE=false> <PARAM NAME=menu VALUE=false> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#FFFFFF>  <PARAM NAME=wmode VALUE=transparent> <PARAM NAME="allowScriptAccess" VALUE="sameDomain" >';
      videoText = videoText + ' <PARAM NAME=flashvars VALUE="' + flashVars + '"> ';
      videoText = videoText + ' <EMBED src="' + pathToFlashFile + '" loop=false menu=false quality=high bgcolor=#FFFFFF allowScriptAccess="sameDomain"  ';
      videoText = videoText + ' swLiveConnect=TRUE WIDTH="' + swfWidth + '" HEIGHT="' + swfHeight + '" WMODE=transparent NAME="Main" ALIGN="" flashvars="' + flashVars + '"';
      videoText = videoText + ' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">';
      videoText = videoText + ' </EMBED>';
      videoText = videoText + ' </OBJECT>';
      document.getElementById(flashContainerId).innerHTML = videoText;
    }
}

EU.init = function() {
  $$("#mainMenu li").each(function(mm) {
    if (mm.id && mm.id.match(/^menulist/)) {
      Event.observe(mm, 'mouseover', function() {
        this.addClassName('over');
      });
      Event.observe(mm, 'mouseout', function() {
        this.removeClassName('over');
      });
    }
  });
  if ($('breadCrumb') && $('ln') && $('breadCrumb').getHeight()>20) {
    $('ln').style.marginTop = '134px'
  }
  initPromoCalloutComponents();
  checkLeftNavHeight();

  if (window.location.pathname!=null && window.location.pathname.match(/eu1\/pl\//)) {
    /* The stragegy is to go as recursively deep as possible to make the change. */
    EU.dontForgetPoland1 = function(aNode, aTagName) {
      var nodes = aNode.getElementsByTagName(aTagName);
      if (nodes==null || nodes.length==0) {
        // no inner nodes
        if (aNode.innerHTML.match(/\s[izo]\s+/)) {
          aNode.innerHTML = aNode.innerHTML.replace(/\s([izo])\s+/g, " $1\&nbsp;");
        }
      } else {
        for (var i=0; i<nodes.length; i++) {
          if (nodes[i].innerHTML.match(/\s[izo]\s+/)) {
            EU.dontForgetPoland1(nodes[i], aTagName);
          }
        }
      }
    };

    EU.dontForgetPoland1(document.getElementById("content"), "P");
    EU.dontForgetPoland1(document.getElementById("content"), "TD");
  }

  $$('.s7-image').each(function(mm) {
    var i = mm.down('img');
    if (i && i.src.match(/s7d2.scene7.com/)) {
      var h = "<a class='s7-enlarge' href='javascript:void(EU.s7($(\"#{id}\")))'><img src='/commclgeu/common/includes/images/btn-mag-glass.png'></a>";
      h=h.interpolate({'id':mm.identify()});
      mm.insert(h);
    }
  });
  initCollapsables();
  $(document).fire('awi:init', {});
};
EU.s7 = function(aDiv) {
  var i = aDiv.down('img');
  var images = i.src.replace(/.+\/is\/image\/Armstrong\//, "").replace(/\?.*/,"");
  var altImages = i.readAttribute('s7-alt');
  if (altImages!=null && altImages.length>0&& altImages.indexOf(' ')==-1) {
    images += "," + altImages;
  }
  images = encodeURIComponent(images);

  var url = "/commclgeu/eu1/#{languageId}/#{countryId}/pan-zoom.asp?images=#{images}&title=#{title}&name=#{name}";
  url = url.interpolate({ 'languageId':EU.languageId,
                          'countryId':EU.countryId,
                          'title':encodeURIComponent(i.alt),
                          'name':encodeURIComponent(i.alt),
                          'images':images
                        });

  var w = window.open(url, '_blank', "status=0,toolbar=0,menubar=0,width=680,height=800,resizable=1");

  s=s_gi(s_account);
  s.linkTrackVars='events,eVar37,products';
  s.linkTrackEvents='event33';
  s.events='event33';
  s.tl(true, 'o',"S7 Enlarge")

  return false;
}

function checkLeftNavHeight() {
  if($('ln')){
    var ch = $('content').getHeight();
    var rh = $('ln').getHeight();
    if (rh>ch) {
      $('footer').style.marginTop=(rh-ch)+'px';
    }
  }
}
function initPromoCalloutComponents() {
  $$("div.promoCalloutComponent").each(function (objThis) {
    objThis.style.cursor = "pointer";

    objThis.observe('mouseover', promoCalloutComponent_onmouseover)
    objThis.observe('mouseout', promoCalloutComponent_onmouseout)
    objThis.select(".captionText")[0].setStyle({"top": "95px"});

    Event.observe(objThis, "click", function() {
      var href=this.getElementsByTagName("A")[0].href;
      s_getObjectID=href;
      location.href=href;
    });
  })
}
function promoCalloutComponent_onmouseover (e) {
  new Effect.Parallel([
    new Effect.Morph(this.select(".captionText")[0], {"style": "top: 65px;"})
  ], {
    "duration": .11
  });
}
function promoCalloutComponent_onmouseout (e) {
  if (!EU.isMouseOver(e, this)) {
    new Effect.Parallel([
      new Effect.Morph(this.select(".captionText")[0], {"style": "top: 95px;"})
    ], {
      duration: 0.11
    });
  }
}

EU.isMouseOver = function(event, obj) {
    var co = obj.cumulativeOffset();
    var dim = obj.getDimensions();
    var bottom = co.top + dim.height;
    var right = co.left + dim.width;
    var x = event.pointerX();
    var y = event.pointerY();
    if (co.left > x || right < x || co.top > y || bottom < y) {
      return false;
    }
    return true;
};

function initCollapsables() {
  $$('.collapsable').each(function(h3){
    Event.observe(h3, 'click', function(e) {
      var what = $(this).next();
      var tr = $(this);
      if (tr.hasClassName('collapsed')) {
          new Effect.BlindDown(what, {duration:0.5, afterFinish:function(){
            tr.removeClassName('collapsed')
            if (tr.up('#ln')) {
              checkLeftNavHeight();
            }
            }});
      } else {
          new Effect.BlindUp(what, {duration:0.5,afterFinish:function(){tr.addClassName('collapsed')}});
      }
    })
  });
}

EU.ql = function(itemId) {
  EU.Popover.open($$('#armstrongPageID a')[0].href + "quick-look.asp?itemId=" + itemId, 505, 525, false);

  s=s_gi(s_account);
  s.products='item;i'+itemId;
  s.linkTrackVars='events,eVar37,products';
  s.linkTrackEvents='event32';
  s.events='event32';
  s.tl(true, 'o',"Quick View")
}

$(document).observe('keyup', function(e) {
  if (e.keyCode==27) {
    EU.Popover.close();
  }
})

EU.expandAll = function() {
   $$('.line .collapsed').each(function(ob){
     new Effect.BlindDown(ob.next(), {duration:0.2});
     ob.removeClassName('collapsed');
   });
}

EU.collapseAll = function() {
   $$('.line .collapsable').each(function(ob){
     if (!ob.hasClassName('collapsed')){
       new Effect.BlindUp(ob.next(), {duration:0.2});
       ob.addClassName('collapsed');
     }
   });
}


EU.fb = function() {
   var template = 'http://www.facebook.com/sharer.php?u=#{url}&t=#{title}';
   var url = template.interpolate({'url':encodeURIComponent(window.location),
   'title':document.title});
   var a_width = 610;
   var a_height = 510;
   var a_windowStyle = "titlebar,scrollbars=yes,resizable=yes" +
   (",left=" + ((screen.availWidth - a_width) / 2)) +
   (",top=" + (((screen.availHeight - a_height) / 2 ) - 30)) +
   (",width=" + a_width) +
   (",height=" + a_height);

   window.open(url, "_blank", a_windowStyle);
   s=s_gi(s_account);
   s.linkTrackVars='prop32,products,events';
   s.linkTrackEvents='event30';
   if(s.pageName)s.prop32=s.pageName;
   s.events='event30';
   s.tl(this,'o','Share on Facebook');
   return false;
}
EU.email = function() {
  var url = "/commclgeu/eu1/#{languageId}/#{countryId}/email_a_friend.asp?url=#{url}&description=#{description}";
  url = url.interpolate({ 'languageId':EU.languageId,
                          'countryId':EU.countryId,
                          'url':encodeURIComponent(window.location),
                          'description':encodeURIComponent(document.title)
                        });

  var w = window.open(url, '_blank', "resizable=1,scrollbars=1,status=0,toolbar=0,menubar=0,width=475,height=450");
  return false;
}

 /*
 * Generic Link tracking on anchors
 * If you wish to track a link
 *  Set o_linkName and  o_linkTrackVars
 * */
$(document).observe('awi:init', function() {
   if($('share')) {
    Event.observe($('share'), 'click', function(e){
     var targetElement = $(e.element());
     if ('A'!=targetElement.tagName) {
       targetElement = targetElement.up('A');
     }

     if (targetElement!=null&&targetElement.readAttribute("o_linkName")!=null&&!targetElement.readAttribute("o_linkName").blank()) {
       o_pageName=s.pageName;
       o_products=s.products;
       o_channel=s.channel;
       s=s_gi(s_account);
       s.linkTrackVars="prop32,prop33"
       s.prop32=targetElement.readAttribute("o_linkName");
       s.prop33=s_combine(o_pageName, s.prop32);
       s.pageName=o_pageName;
       s.tl(targetElement, 'o', targetElement.readAttribute("o_linkName"));
      }
   });
  }
})

$(document).observe('awi:init', function() {
  $$("table.mineral, table.metal").each(function(tb){
    var hasDnfw = false;
    var hasDncw = false;
    tb.select('td.dnfw').each(function(td){if(td.innerHTML.length>0)hasDnfw=true});
    tb.select('td.dncw').each(function(td){if(td.innerHTML.length>0)hasDncw=true});
    if (hasDncw && !hasDnfw){tb.addClassName('showDncw')}
  });
})


