/* Everything to exec on page load */
/*
  Please scope all variables into this object RF
  - or - your own object. Keep top level namspace "clean"
*/

function _initLocale() {
    var m;
    if (m = window.location.pathname.match(/^\/flooring\/(es-us|fr-ca)/)) return m[1];
    return 'zh-cn';
}

var RF = {
    locale :  _initLocale(),
    languageId : _initLocale().substring(0,2),
    currentPopover : null,
    quickLookElement : null,
    COMPARE_TEXT: "Please select 2-4 items to compare.",

    cartAdd : function(obj) {
        /*
            s.events="scAdd";
            s.products=";" + itemId + ";1;";
            try {
              s.gs("armecommerceus");
            }catch(e){}
        */

        if(typeof obj == 'number') {
          return RF.cartAction('http://store.armstrong.com/Cart.bok?smode=add&qty=1&product_no=' + obj);
        } else if(obj.getInputs('checkbox', 'cartchk').size() > 0) {
            var noneChecked = true;
            obj.getInputs('checkbox', 'cartchk').each(function(cb) {
              if (cb.checked) {
                noneChecked = false;
                throw $break;
              }
            });
            if(noneChecked) {
                if (RF.languageId == 'en') {
                    alert('Please select an item');
                } else {
                    alert('Por favor seleccione un artículo');
                }
            } else {
              return RF.cartAction('http://store.armstrong.com/Cart.bok?' + obj.serialize());
            }
        }
    },

    /* Open the Cart window in the specific URL */
    cartAction: function(theUrl) {
        var width = 625;
        var height = 580;
        var x = (screen.availWidth - width) / 2
        var y = ((screen.availHeight - height) / 2 ) - 30;

        if (RF.languageId == 'en') {
            theUrl = theUrl + "&tsetlock=InitialSet";
        } else {
            theUrl = theUrl + "&tsetlock=SpanishSet";
        }

        var w = window.open(theUrl,
                'CART',
                "status=yes,width=" + width +
                ",height=" + height +
                ",left=" + x + ",top=" + y + ",titlebar,scrollbars=yes,resizable=yes,toolbar=yes");
        w.focus();
        return false;
    },

    cartView : function() {
        return RF.cartAction('http://store.armstrong.com/Cart.bok?rballId=1');
    },

    isMouseOver : function(element, event) {
        var cos = Element.cumulativeOffset(element);
        return (event.pageX - cos[0]) > 0 &&
               (event.pageY - cos[1]) > 0 &&
               (event.pageX - cos[0]) < Element.getWidth(element) &&
               (event.pageY - cos[1]) < Element.getHeight(element)
    },

    showQuickLookButton : function(element) {
        if (!$('quickLookElement')) {return; /*not initialized yet*/}
        if (RF.quickLookElement == null) {
            RF.quickLookElement = $('quickLookElement');
            document.body.insertBefore(RF.quickLookElement, document.body.firstChild);
            RF.quickLookElement.onmouseout = RF.hideQuickLookButton;
        }

        var pos = element.cumulativeOffset()
        RF.quickLookElement.setStyle({
            left: (pos.left+8) + 'px',
            top: (pos.top + $(element.id).getHeight()/2 - 10) + 'px'});

        RF.quickLookElement.currentSwatch = element;
        Element.show(RF.quickLookElement);
    },

    hideQuickLookButton : function(event) {
        if (null==RF.quickLookElement) {
          // we don't have the quicklook button showing yet
          return;
        }
        if (event == null) {
            event = window.event;
        }
        if (RF.isMouseOver(RF.quickLookElement, event) || RF.isMouseOver(RF.quickLookElement.currentSwatch, event)) {
            //do nothing
        } else {
            RF.quickLookElement.style.display = 'none';
        }
    },

    quickLook : function() {
        if (RF.quickLookElement.currentSwatch) {
            var itemId = RF.quickLookElement.currentSwatch.id.replace(/swatch/, "");
            if (RF.currentPopover != null) {
                RF.currentPopover.style.display = 'none';
            }

            $('quickLookBody').innerHTML = "Loading ...";

            new Ajax.Request("/flooring/" + RF.locale + "/swatch-rollover.asp?itemId=" + itemId, {
              method: 'get',
              onSuccess: function(transport) {
                $('quickLookBody').innerHTML = transport.responseText;
              },
              onFailure: function(transport) {
                if (transport.responseText != "") {
                  $('quickLookBody').innerHTML = "Please try again ... an error occured";
                }
              }
            });

            /*move the rolloverHolder as a child of root since ie6 sucks with z-index*/
            if (!$('rolloverHolder').readAttribute('moved')) {
              var r = $('rolloverHolder');
              r.writeAttribute('moved', 'Y');
              r.remove();
              var container = $$('.container')[0];
              container.up("body").insert(r);
            }

            var offsets = document.viewport.getScrollOffsets();
            var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
            var y = offsets.top + (height/2) - 250;
            if (y<90) {y=90}

            $('rolloverHolder').setStyle({
              display: 'block',
              top: y + 'px',
              height: 'auto'
            });
            if ($('rolloverHolder').readAttribute('awi_draggableset')!='Y') {
              new Draggable('rolloverHolder');
              $('rolloverHolder').writeAttribute('awi_draggableset', 'N');
            }
            o_addEventOnClick("event22","item;i" + itemId,"Quick Look");
        }
    },
    doCompare: function(locale) {
        var nodes = $$('.sampleCompareContainer .cb input');
        var itemIds = new Array();
        for (var i = 0; i < nodes.length; i++) {
            if ('compare' == nodes[i].name && nodes[i].checked) {
                itemIds.push(nodes[i].value);
            }
        }
        if (itemIds.size() < 2 || itemIds.size() > 4) {
            alert(RF.xl(RF.COMPARE_TEXT));
        } else {
            var s = "";
            for (var i = 0; i < itemIds.size(); i++) {
                if (i == 0) {
                    s = '?itemId=' + itemIds[i];
                } else {
                    s = s + '&itemId=' + itemIds[i];
                }
            }
            var theUrl = "/compare.asp";
            var width = 950;
            var height = 700;
            var x = (screen.availWidth - width) / 2
            var y = ((screen.availHeight - height) / 2 ) - 30;
            if (locale != 'zh-cn') {
                theUrl = "/" + locale + theUrl;
            }
            theUrl = "/flooring" + theUrl + s;
            var w = window.open(theUrl,
                    'COMPARE',
                    "status=yes,width=" + width +
                    ",height=" + height +
                    ",left=" + x + ",top=" + y + ",titlebar,scrollbars=yes,resizable=yes,toolbar=yes");
            w.focus();
        }
        return false;

    },
    addToIdeaFile: function(theUrl) {
        var width = 770;
        var height = 575;
        var x = (screen.availWidth - width) / 2
        var y = ((screen.availHeight - height) / 2 ) - 30;
        var w = window.open(theUrl,
                'IDEA',
                "status=yes,width=" + width +
                ",height=" + height +
                ",left=" + x + ",top=" + y + ",titlebar,scrollbars=yes,resizable=yes,toolbar=yes");
        w.focus();
        return false;
    },
    /*
      Spawn a popup. returns false to cancel the click.
      Usage:
      DEFAULT
        <a href="wacky.html"
           onclick="return RF.doPopup(this.href)">
          Foo
        </a>
      Set width/height
        <a href="wacky.html"
           onclick="return RF.doPopup(this.href, 200, 300)">
          Foo
        </a>

      Custom style - not resizeable
        <a href="wacky.html"
           onclick="return RF.doPopup(this.href, 200, 300, 'titlebar,scrollbars=yes,resizable=no')">
          Foo
        </a>

      Custom style - and text
        <a href="wacky.html"
           onclick="return RF.doPopup(this.href, 200, 300, 'titlebar,scrollbars=yes,resizable=no', 'doh')">
          Foo
        </a>
    */
    doPopup: function(a_href, a_width, a_height, a_windowStyle, a_customText, upperLeft) {
        if (a_windowStyle == undefined) {
            a_windowStyle = "titlebar,scrollbars=yes,resizable=yes";
        }

        if (a_width == undefined || a_width <= 0) {
            a_width = 400;
        }
        if (a_height == undefined || a_height <= 0) {
            a_height = 400;
        }

        if(!upperLeft) {
          a_windowStyle += (",left=" + ((screen.availWidth - a_width) / 2));
          a_windowStyle += (",top=" + (((screen.availHeight - a_height) / 2 ) - 30));
        }

        a_windowStyle += (",width=" + a_width);
        a_windowStyle += (",height=" + a_height);

        var w;
        if (a_customText != undefined) {
            w = window.open('', "_blank", 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_href, "_blank", a_windowStyle);
        }

        try {w.focus();}catch(e) {}

        return false;
    },

    doMessage:function() {
    },
    whatsThis:function(bubbleId) {
        initInfoPopup('infoPopup_image_' + bubbleId);

        $('infoPopup_image_' + bubbleId).setStyle({
            visibility: 'visible',
            display: 'block'
        });

        $('infoPopup_image_' + bubbleId).onmouseout = function() {
          $('infoPopup_image_' + bubbleId).setStyle({
              visibility: 'hidden'
          });
        };
        $('image_' + bubbleId).onmouseout = function() {
          $('infoPopup_image_' + bubbleId).setStyle({
              visibility: 'hidden'
          });
        };
    },

    insertFlash: function(id, src, width, height, requiredVersion, params) {
        if (!src) {
            alert("No source specified");
        }
        if (!width) width = 726;
        if (!height) height = 287;
        if (!requiredVersion) requiredVersion = 8;

        if (AC_FL_RunContent == 0) {
            alert("This page requires AC_RunActiveContent.js.");
        } else {
            if (DetectFlashVer(requiredVersion, 0, 0)) {
                AC_FL_RunContent(
                        'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + requiredVersion +
                                    ',0,0,0',
                        'width', width,
                        'height', height,
                        'src', src,
                        'quality', 'high',
                        'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
                        'align', 'middle',
                        'play', 'true',
                        'loop', 'true',
                        'scale', 'showall',
                        'wmode', 'window',
                        'devicefont', 'false',
                        'id', id,
                        'bgcolor', '#ffffff',
                        'name', id,
                        'menu', 'true',
                        'allowFullScreen', 'false',
                        'allowScriptAccess', 'sameDomain',
                        'movie', src,
                        'salign', ''
                        );
            }
        }

    },

    setTrail : function(element) {
       var nodes = $('breadcrumb').getElementsByTagName('A');
       if(nodes==null||nodes.length<=1) {
        return;
       }
       var cookieString = "";
       for (var i=2;i<nodes.length;i++) {
         if (i>2) {
          cookieString = cookieString + "|";
         }
         cookieString = cookieString + nodes[i].href.replace(/^.+\/flooring\//,"/flooring/") + '|' + nodes[i].innerHTML;
       }
       document.cookie="CRUMB_TRAIL=" + encodeURIComponent(cookieString) + "; path=/flooring";
       try {
         document.cookie="LNS=" + carryForwardState + "; path=/flooring";
       } catch(e){
       }
    },
    xl : function(s) {
        if (RF.languageId == 'es') {
          if (RF.COMPARE_TEXT==s) {
            return "Seleccione por favor 2-4 artículos para comparar.";
          }
        }

        return s;
    },

    getGuide: function(whichOne) {
        if(!whichOne) whichOne = 'flooring';
        RF.containerPopup('guidePopup', '/flooring/' + RF.locale + '/order-flooring-guide.do?g=' + whichOne);
    },

    closeGuide: function() {
        RF.closeContainerPopup('guidePopup');
    },

    signup: function(emailAddress) {
        RF.containerPopup('signupPopup', '/flooring/' + RF.locale + '/email-signup.asp?emailAddress=' + emailAddress);
    },

    closeSignup: function() {
        RF.closeContainerPopup('signupPopup');
    },

    emailAFriend: function() {
        var url = window.location.pathname;
        if (!window.location.search.blank()) {
          url += window.location.search;
        }
        if (!window.location.hash.blank()) {
          url += window.location.hash;
        }
        var itemDesc = $$('.titleText h1')[0].innerHTML.stripTags();
        if(itemDesc.indexOf("sIFR_callback") > -1) itemDesc = $$('.titleText h1 .sIFR-alternate')[0].innerHTML.stripTags();

        RF.containerPopup('friendPopup', '/flooring/' + RF.locale + '/email-a-friend.do?pageUrl=' + encodeURIComponent(url) + "&description=" + encodeURIComponent(itemDesc));
    },

    closeAFriend: function() {
        RF.closeContainerPopup('friendPopup');
    },

    containerPopup: function(id, src) {
        RF.hideSelects();
        var popup = new Element('iframe', {src: src, id: id, name: id, allowTransparency: false});
        var container = $$('.container')[0];
        if (container) {
            container.insert({before: popup});
            var offsets = container.viewportOffset();
            popup.setStyle({'left': (document.viewport.getWidth() / 2) - (popup.getWidth() / 2) + 'px'});
            var top = (document.viewport.getHeight() / 2) - offsets.top - (popup.getHeight() / 2);
            if(top < 50) top = 50;
            popup.setStyle({'top': top + 'px'});
        }
        return popup;
    },

    closeContainerPopup: function(id) {
        RF.showSelects();
        window.parent.document.getElementById(id).remove();
    },
    flashAssets: new Hash(),
    addFlashAsset: function (key, value){
        RF.flashAssets.set(key, value);
    },

    hideSelects: function() {
        var selects = document.getElementsByTagName('select');
        var selectCount = selects.length;
        if(selects && selectCount > 0) {
            for(var i = 0; i < selectCount; i++) {
                var thisSelect = selects[i];
                thisSelect.style.visibility = 'hidden';
            }
        }
        $$('.container object').each(function(goner) {
              goner.addClassName('invisible');goner.addClassName('madeInvisible');
            });
    },

    showSelects: function() {
        var selects = parent.document.getElementsByTagName('select');
        var selectCount = selects.length;
        if(selects && selectCount > 0) {
            for(var i = 0; i < selectCount; i++) {
                var thisSelect = selects[i];
                thisSelect.style.visibility = 'visible';
            }
        }

        selects = parent.document.getElementsByTagName('object');
        selectCount = selects.length;
        if(selects && selectCount > 0) {
            for(var i = 0; i < selectCount; i++) {
                Element.removeClassName(selects[i], 'invisible');
                Element.removeClassName(selects[i], 'madeInvisible');
            }
        }

    },
    updatePhotoDetails:function(url, text) {
      try {
        var anchor = $('infoPopup_button_photoDetails').select('a')[0];
        anchor.innerHTML = text;
        anchor.href = url;
        $$('.headerBackground img')[0].alt=text;
      } catch(e){/* guess we didn't have one */}
    },
    getCookie : function(name) {
      var dc = document.cookie;
      var prefix = name + "=";
      var begin = dc.indexOf("; " + prefix);
      if (begin == -1){
          begin = dc.indexOf(prefix);
          if (begin != 0) return null;
      }else{
          begin += 2;
      }
      var end = document.cookie.indexOf(";", begin);
      if (end == -1){
          end = dc.length;
      }
      return unescape(dc.substring(begin + prefix.length, end));
    },
    deleteCookie:function(name, path, domain) {
      if (RF.getCookie(name)) {
          document.cookie = name + "=" +
              ((path) ? "; path=" + path : "") +
              ((domain) ? "; domain=" + domain : "") +
              "; expires=Thu, 01-Jan-70 00:00:01 GMT";
      }
    }
};


// called from SWF
function getFlashAsset(key) {
    var value = RF.flashAssets.get(key);
    if(value) {
      return value;
    } else {
      alert("looking for asset " + key);
      return false;
    }
}

function printPage() {
    window.print();
}


RF.fbg = {
    maxFreeItems: 3,

    setItems:function(item, increment) {
        if (RF.fbg.countCheckboxes() > RF.fbg.maxFreeItems) {
            item.checked = false;
            if("es-us" == RF.locale) {
                alert('Usted ha seleccionado la cantidad límite de tipos de pisos. Haga clic en IR para continuar.')
            } else {
                alert('You have chosen the maximum number of floor types. Now click on Submit to continue.')
            }
        }
    },

    checkItems:function() {
        if (RF.fbg.countCheckboxes() == 0) {
            alert("Select up to three flooring categories and then select Go");
            return false;
        }
        return true;
    },

    countCheckboxes:function() {
        var itemCount = 0;
        var cBoxes = document.forms['formCompare1'].elements;
        for (i = 0; i < cBoxes.length; i++) {
            if (cBoxes[i].checked) {
                itemCount++;
            }
        }
        return itemCount;
    },

    printStyle:function() {
        printPage();
    }
}

/* called by flash on the home page */
function showCart() {
  return RF.cartView();
}

/*design gallery*/
  function dd_checkSubmit(aSelect) {
    if (aSelect.selectedIndex>0) {
      window.location.href=aSelect.options[aSelect.selectedIndex].value
    }
  }
/* optin signup */
function processOptinSignup() {

  var emailAddress = $('newsletterEmailField').value;
  if (emailAddress.blank()) {
      alert("Please enter your Email.");
  } else {
  var url = "/Web/Subscription.aspx?emailAddress=" + emailAddress;

      /*
      new Ajax.Request(url, {
      method: 'get'
      }
      */
      window.location.href=url;
  
  }
  

  return false;
}

function installDemo() {
  var id = "35756602";
  if("es" == RF.languageId) id = "35758940";
  var url = 'http://webapps.easy2.com/cm/masterflash/generic_index.asp?page_id=' + id;
  var width = 620;
  var height = 470;
  var winHorz = (screen.width - width) / 2;
  var winVert = (screen.height - height) / 2;
  winProp = 'width=' + width + ',height=' + height + ',left=' + winHorz + ',top=' + winVert + ',scrollbars=no,resizable=no';
  var Win = window.open(url, 'InstallationOverview', winProp);
  if (parseInt(navigator.appVersion) >= 4) { Win.window.focus(); }
}

function newsletterEmailFieldFocus(field) {
  if(field.value == 'Enter email address') {
    field.value = '';
  }
}

function searchFieldFocus(field) {
  if(field.value == 'Search Keyword or Item #' || field.value == 'Términos de búsqueda') {
    field.value = '';
  }
}

function uiCleanup() {
  $$('input[type=checkbox]').each( function(objThis){objThis.setStyle({"border":"0px"})});
  $$('.swatchDiv').each( function(objThis) {
      if (!objThis.hasClassName('discontinued')) {
        var img = objThis.select('img')[0];
        Event.observe(img, "mouseover", function(){RF.showQuickLookButton(this)});
        Event.observe(img, "mouseout", RF.hideQuickLookButton);
      }
    });

  $$(".hasmore .trigger").each(function(objThis) {
    Event.observe(objThis, "click", function(event) {
      var container = this.up(".hasmore");
      if (container.hasClassName('show-more')) {
        container.removeClassName('show-more');
      } else {
        container.addClassName('show-more');
      }
      event.preventDefault();
    });
  });

  /* detect home pressed on search */
  if ($('searchTextField')) {
    $('searchTextField').writeAttribute('dirty', 'N');
    Event.observe($('searchTextField'),"keypress", function(){this.writeAttribute('dirty', 'Y')});
    Event.observe($$('.toolbarIcon')[0], "click", function(){
      if ("Y"==$('searchTextField').readAttribute('dirty')) {
        s=s_gi(s_account);
        s.tl(this,'o','Clicked Home icon for search');
      }
    });
  }
  Event.observe(window, "unload", function() {if($('rolloverHolder'))$('rolloverHolder').setStyle({display: 'none'});});
}

function initSearch() {
    Event.observe($('searchTextField'),"focus", function(){Effect.Appear('txtSearchButton', { duration: 0.25 })});
    Event.observe($('searchTextField'),"blur", function(){Effect.Fade('txtSearchButton', { duration: 0.25 })});
}

RF.canLaunchInterstial=function() {
		if (RF.getCookie("UT")==null ||
        RF.getCookie("LIC")!=null ||
        RF.getCookie("interstitial")!=null ||
        $(document.body).hasClassName('nointerstitial')||
        RF.languageId != 'en') {
        	return false;
    }
    return true;  
}

Event.observe(window, "load", function() {
      if(!RF.canLaunchInterstial())
				return;
				
      var icb  = function(event) {
          /* recheck in case multiple tabs / windows open */
          if(!RF.canLaunchInterstial())
						return;

          event.preventDefault();
          RF.launchInterstitial(this.href);
      };

      $$('.content a').each( function(objThis) {
          if (objThis.href!=null && objThis.href.match(/\.pdf$/i) && !objThis.hasClassName('nointerstitial')) {
            Event.observe(objThis, "click", icb);
          }
        });
 });


RF.launchInterstitial=function(pdfFileName){
    document.cookie = "interstitial=Y; path=/flooring";
    RF.containerPopup('interstitialPopup', '/flooring/' + RF.locale + '/interstitial.asp?pdf=' + pdfFileName);
}
RF.closeInterstitialPopup=function(pdfFileName){
   RF.closeContainerPopup('interstitialPopup');
}

RF.swatchMicroFormatCleanup=function(anId){
  $$('#swatchContainer' + anId + ' .swatchDiv')[0].setStyle({
    'background' : 'url(' + $('swatch' + anId).src + ') center center no-repeat'
  });
  $('swatch' + anId).src = '/flooring/i/images/overlay-results-swatch.gif';
}

function hideVideo(){
   RF.closeContainerPopup('videoFrame');
  }
function showVideo() {
    RF.containerPopup('videoFrame', '/flooring/' + RF.locale + '/video.asp');
}
function fbShare() {
    var template = 'http://www.facebook.com/sharer.php?u=#{url}&t=#{title}';
    var url = template.interpolate({'url':encodeURIComponent(window.location),
                                    'title':document.title});
    RF.doPopup(url, 650, 510);
    s=s_gi(s_account);
    s.linkTrackVars='prop23,products,events';
    s.linkTrackEvents='event26'; 
    if(s.pageName)
    	s.prop23=s.pageName;
    s.events='event26';
    s.tl(this,'o','Share on Facebook');  
    return false;
}

