/* hide all product containers to avoid flash 
 * of unstyled content - see line 70 (productTabsInit())
 * in conjuction with product.css - line 153
 */
 
$("html").addClass("js");

$(function(){
    var detailContent = $(".productDetailContent").size();    
    if(detailContent == 1 || detailContent == 0) {     
       $("html").removeClass("js");
    }
});
 
/* 
* variable assignment  for the following are defined in either /product/default.aspx or /product/productId/default.aspx
* path
* productId
*/

var productId = null;
var section = null; // this is the default state
var d = YAHOO.util.Dom;
var initSection;

  // Instantiate and configure Loader:
if(currentLocale.toLowerCase()=="en-us"){
  var yuiLoaderArr = ["connection","event"];
}else{
  var yuiLoaderArr = ["animation","connection","container","event","history","json"];
}
    var loader = new YAHOO.util.YUILoader(
    {
      // Identify the components you want to load.  Loader will automatically identify
      // any additional dependencies required for the specified components.
      require: yuiLoaderArr, //,"swfobject"
      base: '/app/includes/js/yui/',
      loadOptional: false,
      onSuccess: function() {
           initProductPage();
      },
      
      onProgress: function(o) { },
      onFailure: function() { }
    });
    
   /* loader.addModule({
	    name: "swfobject",
	    type: "js", 
        fullpath: "/app/includes/js/swfobject.js"
    }); */
  
  
function initProductPage(){
  var productDetailSections = YAHOO.util.Dom.getElementsByClassName('productDetailContent', 'div').length;
  if (productDetailSections <= 1) {
    initSection = YAHOO.util.History.getBookmarkedState("s") || "";
    // register the history object with our callback function and initial state

    YAHOO.util.History.register("s", initSection, function(state) {
      //load new section and set tab
      if (state.length > 0)
        getProductSectionControl(state, currentPath);
    });

    // called on page load
    YAHOO.util.History.onReady(function() {
      var state = YAHOO.util.History.getCurrentState("s");
      // get section data
      if (state.length > 0)
        getProductSectionControl(state, currentPath);
    });

    YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
  }
  productTabsInit();
}

/*
* this method/function will loop through each product navigation tab and add the
* event handlers needed to enable ajax
*/
 
function productTabsInit(){
  //document.documentElement.className = ""; // now allow all containers to be visible
  var productNavigation = d.get("productNavigation");
  var navElements = d.getElementsBy(function(e){ return (e.nodeName=="A");}, "A", productNavigation);

var productDetailSections = YAHOO.util.Dom.getElementsByClassName('productDetailContent', 'div').length;

if(productDetailSections > 1){
	$(function(){	
            $(".productDetailContent").hide(); // hide all containers
            var firstSection = $(".productDetailContent:first");
            var sections = $(".productDetailContent");
            
            $("div.br").append(sections); // place all sections inside the bordered container (div class=br)
            $(firstSection).show();
            
            var navLinks = $("#productNavigation a");
            $(navLinks).click(function(){
                $(".pdtMenu td").removeClass("selected");
                $(this).parent("td").addClass("selected");
                var idx = $(navLinks).index(this);
                pageTracker._trackPageview(currentPath + this.parentNode.id);
                OB.showHideProductDetails(idx);
            });              
        });
} else {

  for (var i=0; i<navElements.length; i++){
    section = navElements[i].parentNode.id;
    if (section == "overview") {
		section = "";
	}
    if(currentPage=="default.aspx"){
       navElements[i].setAttribute("href", "javascript:void(0)");
        YAHOO.util.Event.addListener(navElements[i], 'click', tabOnClick);
		navElements[i].setAttribute("href", "javascript:void(0)");
	    navElements[i].setAttribute("tabIndex", i+1);
      } else {
      // not on default so change tab links to point to ajaxified page
      navElements[i].setAttribute("href", "default.aspx#s=" + section);
    }
  }
   navElements[0].focus();
 }
}
// obj should be the link the user has clicked or to make active
function setActiveTab(obj, currentPath, section){
  var unselectTabs = d.getElementsBy(function(e){ return (e.nodeName=="TD");}, "TD", obj.parentNode.parentNode.id); 
  d.replaceClass(unselectTabs, "selected", " ");
  d.addClass(obj.parentNode.id, "selected");
  pageTracker._trackPageview(currentPath + section);
}

var tabOnClick = function(e){  // e is event
  // update tabs states
  YAHOO.util.History.navigate("s", this.parentNode.id);
};

function getProductSectionControl(section, currentPath){
	d.get("productSection").innerHTML = '<img src="/app/assets/images/loading_animation.gif" style="padding: 163px 0 0 435px;" />';
	var path = (currentPath.toLowerCase().indexOf(currentLocale) > 0) ? currentPath : "/" + currentLocale + currentPath;
	var sUrl = "/app/services/getProductSectionControl.ashx?path=" + path + "&section=" + section;
	var responseHtml;

	var callback = {
	  success: function(o) {
	    var responseHtml = o.responseText; //get this from cache
	    // var doFadeOut = new YAHOO.util.Anim("productSection", { opacity: { to: 0 } }, 0.2);

	    //var doFadeIn = function(type, args) {
	    d.get("productSection").innerHTML = responseHtml;
	    d.get("productSection").focus();
	    //var fade = new YAHOO.util.Anim("productSection", { opacity: { to: 1 } }, 0.2);
	    //fade.onComplete.subscribe(function(){setActiveTab(d.getFirstChild(d.get(section)), currentPath, section);});
	    //fade.animate();
	    setActiveTab(d.getFirstChild(d.get(section)), currentPath, section);
	    //};

	    if (d.inDocument("flashScript")) {
	      eval(d.get("flashScript").text);
	    }

	    addTrackingClickEvents("overlayContent");

	    if (YAHOO.util.Dom.inDocument("evalJs")) {
	      YAHOO.log(document.getElementById("evalJs").text);
	      eval(document.getElementById("evalJs").text);
	    }
	    
	    var evalJsElements = YAHOO.util.Dom.getElementsBy(
              function(el) {
                if (YAHOO.util.Dom.hasClass(el, "evalJs"))
                  return true;
                else
                  return false;
              }, "span", document,
              function(el) { // get all script elements and eval

                var scriptElements = YAHOO.util.Dom.getChildrenBy(el,
                  function(el) {
                    if (el.tagName == "SCRIPT")
                      return true;
                    else
                      return false;
                  });

                for (var i = 0; i < scriptElements.length; i++) {
                  eval(scriptElements[i].innerHTML);
                }
              });

	    //doFadeOut.onComplete.subscribe(doFadeIn);
	    //doFadeOut.animate();
	  },

	  failure: function(o) { }
	};

	var transaction = YAHOO.util.Connect.asyncRequest("GET", sUrl, callback, null);	
}

function setoverLayMenuWidth(){
    var menuTbl = d.get("productNavigation");
    if(menuTbl != null){
        var menuTd = d.getChildren(menuTbl);
        var width = Math.round(100/menuTd.length);
        for (var i=0; i<menuTd.length; i++){
           if(i == 0){d.addClass( menuTd[i],"first")} 
           if(i ==(menuTd.length -1)){d.addClass( menuTd[i],"last")} 
           d.setStyle( menuTd[i] , "width" , width+"%" ) 
        }
    }
}

function productPageInit(){
      /*  
      *   This file is shared between two locations. only call this method if we are
      *   this is running in a non overlay mode.
      */
     
      if(!d.inDocument("filterContainer") && currentPage == "default.aspx"){ //filterContainer will only exists in overlay mode
        loader.insert(); //load required js files   
      } 
      setoverLayMenuWidth();
}

var d = YAHOO.util.Dom;
function toggleImg(obj){
    
    theSelectedLi =  d.getElementsByClassName("selected" , "li" , d.getAncestorByTagName( obj ,"ul"));
    if(theSelectedLi.length ==1){
        d.removeClass(theSelectedLi[0], "selected");
    }
    var thumbSrc = d.getFirstChild(obj).src;
    stageSrc = thumbSrc.replace("_thumb", "");
    d.addClass(obj, "selected")
    d.get("stage").src =  stageSrc;
}

YAHOO.util.Event.addListener(window, 'load', productPageInit);

// used for product landing pages...
(function() { // create a namespace

  OB = {
    showHideProductDetails: function(idx) {
      var sections = $(".productDetailContent");
      sections.hide();

      if (idx >= 0) {
        var singleSection = $(sections.get(idx));
        $(singleSection).show();
      }
      else {
        sections.show();
      }
    }
  };
})();

function showNewsAndReviews() {
    $(".pdtMenu td").removeClass("selected");
    $(".pdtMenu td#news").addClass("selected");    
    OB.showHideProductDetails(2);
   }

   /*Function for popup disclaimer on Buy Now click.*/
   function DisclaimerPopUp(idName)
   {
   	document.getElementById(idName).style.display = 'block';
   	return false;

   }
   function closeDisclaimer(idName)
   {
   	document.getElementById(idName).style.display = 'none';
   }
   function ContinueToWheretobuy(buyNowURL)
   {
   	window.location.href = buyNowURL;
   	return false;
   }
