/* enterprise.js */


// create HTML5 elements for supported, non compatible IE versions
if ((navigator.appName == 'Microsoft Internet Explorer') && (navigator.userAgent.indexOf('MSIE 6.0') >= 0) || (navigator.userAgent.indexOf('MSIE 7.0') >= 0) || (navigator.userAgent.indexOf('MSIE 8.0') >= 0)) {
    document.createElement("section", "article", "video")
}
else {

}

/* global page location variable */

var pageLocation = location.href;

function pngFix() {
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);

	if (version >= 5.5 && version < 7) {
		for (var i = 0; i < document.images.length; i++) {
			var img = document.images[i];
			var imgName = img.src.toUpperCase();
			if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
				var imgID = (img.id) ? "id='" + img.id + "' " : "";
				var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				var imgStyle = "display:inline-block;" + img.style.cssText;
				if (img.align == "left") imgStyle = "float:left;" + imgStyle;
				if (img.align == "right") imgStyle = "float:right;" + imgStyle;
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
				img.outerHTML = strNewHTML;
				i = i - 1;
			}
		}
	}
}
/********************************************************************************************************/
/***************************** Home page carousel animation and stuff ***********************************/
/********************************************************************************************************/

// function to cancel hover event of slide content not intended to trigger window blinds
function hoverCancel() {
    $('.heroCarousel ul li .slideCopy.trigger p').each(function () {
        $(this).mouseover(function () {
            return false;
        });
    });
}
// function to animate 'window blinds' text on hero slides
function windowBlindsDown() {
    $('.heroCarousel ul li .heroTop').each(function () {
        $(this).hover(
        function () {

            // raise text
            $(this).animate({
                top: '317',
                height: '0'
            }, 300, function () {
                showSlideCopy($(this).next());
            });
        },
        function () {   
        }
    );
  });
}

// function to animate 'window blinds' text on hero slides
function windowBlindsUp() {
    $('.heroCarousel ul li .slideCopy.trigger').each(function () {
        $(this).hover(
        function () {
            },
        function () {
            // call separate function to hide slide copy
            hideSlideCopy(this);

            // lower blinds
            $(this).prev().animate({
                top: '0',
                height: '317'
            }, 300, function () {

            });
        }
    );
    });
}


// function to animate to NO transparency of slide copy
function showSlideCopy(slidecopy) {
    // fade in content copy
    $(slidecopy).children('div').show();
}

// function to animate to FULL transparency of slide copy
function hideSlideCopy(slidecopy) {
    $(slidecopy).children('div').hide();
 }


 // Latest News ticker - home page
 function loadTicker() {
     var tickerManager = new TickerManager('#ticker');
     jQuery('#tickerElements .tickeritem').each(function (i, e) {
         tickerManager.addMessage(e);
     });
     jQuery('#tickerElements').remove();
     tickerManager.start();
 }

/********************************************************************************************************/
/***************************** Scenarios page hero state/query string stuff *****************************/
/********************************************************************************************************/
 var scenarioID = 0; // Backwards compat for old XSLT - to be removed
 // set global scenario 'on' panel tracker variable
 var curScenarioElem = null;
 
 // function to show the correct scenario page copy content by the selected scenario
 function setScenarioOnLoad() {
 	// if we are on the scenarios page and the page location href contains query string parameters
	var pageParamIndex = pageLocation.indexOf('page=');
 	if (pageParamIndex >= 0) {
 		// extract the parameter value param from query string
 		var scenarioString = pageLocation.slice(pageParamIndex + 'page='.length);
 		if (scenarioString.indexOf('&') > -1) {
 			scenarioString = scenarioString.slice(0, scenarioString.indexOf('&'));
 		}

 		curScenarioElem = $("#" + scenarioString);

 		// When a scenario element wasn't found, check to see if the url uses the
		// old scenario<index> format
 		if (curScenarioElem.length == 0) {
 			var scenarioIndex = parseInt(scenarioString.replace(/\D/g, '')) - 1;
 			curScenarioElem = $($(".scenarioPanel")[scenarioIndex]);
 		}
 	}
 	else curScenarioElem = $(".scenarioPanel").first();

 	var indexOfScenario = $(".scenarioPanel").index(curScenarioElem) + 1;

	// Initialize the carousel
 	$('#scenariosHeroCarousel').carousel('#scrollLeft', '#scrollRight', indexOfScenario);

 	// Hide all scenarios by default
 	$(".scenarioPanel").css("display", "none");
 	// fade in correct scenario panel
 	curScenarioElem.css('display', 'block');
 	curScenarioElem.animate({ opacity: '1' }, "slow");
 }

 // function to show the correct scenario page copy content by the selected scenario
 function setScenarioOnClick(index) {
 	if (index < 1) return;

	// fade out the existing show panel and set classes
 	var sceneElem = $($(".scenarioPanel")[index - 1]);
 	curScenarioElem.animate({ opacity: '0' }, "slow", function () {
		$(this).css('display', 'none');
		sceneElem.css('display', 'block');
		sceneElem.animate({ opacity: '1' }, "slow");
	});
	curScenarioElem = sceneElem;
 }

 function scenarioMenuSelect() {
 	$("#scenarioDropDown").change(function () {
 		var selectedValue = $("#scenarioDropDown option:selected").val();
 		var pageIndex = $("#scenarioDropDown option:selected").index();
 		var pageQueryParam = "";
 		if (selectedValue === "") {
 			pageQueryParam = "scenario" + pageIndex;
 		} else {
 			pageQueryParam = selectedValue;
 		}
 		Tracking.publish('scenariosDropDown_select_click' + pageIndex);
 		var windowsIndex = pageLocation.indexOf("/windows/enterprise");
 		var localeBaseUrl = pageLocation.substring(0, windowsIndex);
 		window.location = localeBaseUrl + "/windows/enterprise/scenarios/default.aspx?page=" + pageQueryParam;
 	})
 }
/***********************************************************************************************************/
/***************************** Landing page hero subnavigation and stuff ***********************************/
 /***********************************************************************************************************/

 // add external link icon on landing pillar links

 function addExternalHero() {

     $('#heroSubnavigation li div ul li a').each(function () {
         if ($(this).attr('href').indexOf('/windows/enterprise/') >= 0) {
             return;
         }

         else {
             $(this).addClass('external');
             $(this).attr('target', '_blank');
         }

     });
 }

 function addExternalSub() {

     $('#subpageHeroSubnavigation ul li div ul li a').each(function () {
         if ($(this).attr('href').indexOf('/windows/enterprise/') >= 0) {
             return;
         }

         else {
             $(this).addClass('external');
             $(this).attr('target', '_blank');
         }
     });
 }

	// function to animate sliding doors in subnavigation heroes
	function subnavAnimate() {

		var waveStartDelay = 1000; // milliseconds between page load and wave start
		var waveItemDelay = 200; // milliseconds between each item start
		var waveDownDelay = 1000; // milliseconds between wave up and wave down
		var itemNumber = 0;

		$('#heroSubnavigation li div.wrapper').each(function () {

			var currentItem = $(this);

			// Attach hover event handlers
			currentItem.hover(
			  function () {
          		subnavAnimateUp(currentItem);
			  },
			  function () {
          		subnavAnimateDown(currentItem);
			  }
			);

			// Force one-time animation
			setTimeout(
				function () {
					subnavAnimateUp(currentItem);
				},
				waveStartDelay + (itemNumber * waveItemDelay)
			);
			setTimeout(
				function () {
					subnavAnimateDown(currentItem);
				},
				waveStartDelay + (itemNumber * waveItemDelay) + waveDownDelay
			);
			itemNumber++;
		});
	}
	function subnavAnimateUp(item) {

		var animationSpeed = 500; // milliseconds between start and end of animation

		item.children("span.arrowstatic")
			.addClass("arrowactive")
			.removeClass("arrowstatic");

		item.stop()
			.animate(
				{ marginTop: '5' },
				animationSpeed,
				function () {
					// animation complete
				}
			);
	}
	function subnavAnimateDown(item) {

		var animationSpeed = 500; // milliseconds between start and end of animation

		item.children("span.arrowactive")
			.addClass("arrowstatic")
			.removeClass("arrowactive");

		item.stop()
			.animate(
				{ marginTop: '170' },
				animationSpeed,
				function () {
					// animation complete
				}
			);
	}

  /***************************** Sub page hero subnavigation and stuff ***********************************/
  /***********************************************************************************************************/
  // function to animate sliding doors in subnavigation heroes
  function subpageNavAnimate() {
      $('#subpageHeroSubnavigation li').each(function () {
          $(this).hover(
          function () {
              $(this).children('div').children("span.arrowstatic").addClass("arrowactive");
              $(this).children('div').children("span.arrowstatic").removeClass("arrowstatic");
              $(this).children('div').children('ul').show();
          },
          function () {
              $(this).children('div').children("span.arrowactive").addClass("arrowstatic");
              $(this).children('div').children("span.arrowactive").removeClass("arrowactive");
              $(this).children('div').children('ul').hide();
          }
        );
      });
  }

  // sub page content expand/collapse
  function expando() {
  	$('.expandDiv').each(function () {
  		$(this).children('h2').click(function () {
  			$(this).next().toggle();
  			$(this).toggleClass("open");
  		});
  		$(this).children('h2').click();
  	});
  }


  /**********************************************************************************/
  /***************************** Page load kick start *******************************/
  /**********************************************************************************/

  $(document).ready(function () {

  	if ($('#heroSubnavigation').length > 0) {
  		addExternalHero();
  		subnavAnimate();
  	}

  	if ($('#subpageHeroSubnavigation').length > 0) {
  		addExternalSub();
  		subpageNavAnimate();
  	}
  	// instantiate home page specific objects
  	if ($('#homeHeroCarousel').length > 0) {
  		windowBlindsDown();
  		windowBlindsUp();
  	}

  	// instantiate page specific carousel(s)
  	if ($('#homeHeroCarousel').length > 0) {
  		$('#homeHeroCarousel').carousel('#scrollLeft', '#scrollRight', 1, { autoRotate: 10000 });
  	}

  	// sub page content carousels
  	if ($('#contentcarousel1').length > 0) {
  		$('#contentcarousel1').carousel('#contentleftscroll1', '#contentrightscroll1');
  	}

  	// webcast and tools carousels
  	if ($('#subcarousel1').length > 0) {
  		$('#subcarousel1').carousel('#subleftscroll1', '#subrightscroll1');
  	}

  	if ($('#subcarousel2').length > 0) {
  		$('#subcarousel2').carousel('#subleftscroll2', '#subrightscroll2');
  	}

  	if ($('#subcarousel3').length > 0) {
  		$('#subcarousel3').carousel('#subleftscroll3', '#subrightscroll3');
  	}

  	// featured partners carousel
  	if ($('#featuredPartners').length > 0) {
  		$('#featuredPartners').carousel('#featuredPartnersNavLeft', '#featuredPartnersNavRight', 1, { autoRotate: 10000 });
  	}

  	// scenarios hero
  	if ($('#scenariosHeroCarousel').length > 0) {
  		setScenarioOnLoad();
  	}

  	// scenario navigation drop down
  	if ($('#scenarioDropDown').length > 0) {
  		scenarioMenuSelect();
  	}

  	// expand/collapse containers
  	if ($('.expandDiv').length > 0) {
  		expando();
  	}

  	// expand/collapse containers
  	if ($('.contentScroller').length > 0) {
  		$(".contentScroller").contentScroller({ animationType: "Fade", showPreviousNextLinks: false });
  	}

  	// buttons - enable sliding doors
  	if ($('.button').length > 0) {
  		$('.button').each(function (index) {
  			$(this).html('<span>' + $(this).html() + '</span>');
  		});
  	}


  	pngFix();
  });


  // content scroller function for quotes

  (function ($) {
      $.fn.contentScroller = function (o) {
          return this.each(function () {
              var contentScroller = new ContentScroller;
              contentScroller.initialize(this, o);
          });
      };

      // class constructor
      var ContentScroller = function () {
          // defaults
          this.d = {
              animationTime: 500,
              autoCycleSpeed: 8000,
              autoCycle: true,
              animationType: "ScrollHorizontal",
              showPreviousNextLinks: true,
              hasVideoPopups: false,
              visibleSlides: 1,
              filterFunction: null
          };

          // selectors
          this.selectors = {
              slides: ".scrollerSlides",
              slideContainer: ".scrollerSlidesContainer",
              videoPlayer: ".mediaPlayerPopup",
              previousLinkClassName: "scrollerPrevious",
              nextLinkClassName: "scrollerNext",
              noScriptClassName: "scrollerSlidesContainerNoScript"
          };

          // stub out elements and counters
          this.container = null;
          this.slideContainer = null;
          this.slideList = null;
          this.slideListItems = null;
          this.slideListItemWidth = null;
          this.slideListItemHeight = null;
          this.nextLink = null;
          this.prevLink = null;
          this.count = null;
          this.current = 0;
          this.autoCyclePaused = false;
          this.isAnimating = false;
      };

      ContentScroller.prototype.initialize = function (el, o) {
          var self = this;

          // extend default values with options from user
          if (o) $.extend(self.d, o);
          if (self.d.filterFunction != null) {
              eval(self.d.filterFunction);
          }

          // cache slide objects and init counters
          self.container = $(el);
          self.slideContainer = $(self.selectors.slideContainer, self.container);
          self.slideList = $(self.selectors.slides, self.slideContainer);
          self.slideListItems = self.slideList.children("li");
          self.slideListItemWidth = self.slideListItems.width();
          self.slideListItemHeight = self.slideListItems.height();
          self.count = (self.slideListItems.length > 0) ? self.slideListItems.length : 0;

          // init slide styles
          self.setSlideStyles();

          // add prev/next links
          if (self.d.showPreviousNextLinks) {
              self.addPreviousNextLinks();
          }

          // bind events
          self.bindEvents();

          // remove downlevel class
          self.slideContainer.removeClass(self.selectors.noScriptClassName);

          // start the autocyle
          if (self.d.autoCycle) {
              self.autoCycle();
          }
      }

      //set slide positions for continous loop
      ContentScroller.prototype.setSlideStyles = function () {
          var self = this;

          self.slideListItems.css("position", "absolute");

          switch (self.d.animationType) {
              case "ScrollHorizontal":
                  for (var i = 0; i < self.count; i++) {
                      if (self.d.visibleSlides > 1) {
                          if (self.current == i)
                              slideLeftValue = 0;
                          else if ((self.current - 1 == i) || ((self.current == 0) && (i == (self.count - 1))))
                              slideLeftValue = -self.slideListItemWidth;
                          else if (i == 0 && (self.count - self.current == self.d.visibleSlides))
                              slideLeftValue = self.d.visibleSlides * self.slideListItemWidth;
                          else if ((self.count - self.current < self.d.visibleSlides) && (i < self.current))
                              slideLeftValue = (self.count - self.current + i) * self.slideListItemWidth;
                          else
                              slideLeftValue = ((i - self.current) * self.slideListItemWidth);

                          self.slideListItems.eq(i).css("left", slideLeftValue + "px");
                      }
                      else if ((self.current == 0) && (i == self.count - 1)) {
                          self.slideListItems.eq(i).css("left", -self.slideListItemWidth + "px");
                      }
                      else if ((self.current == (self.count - 1)) && (i == 0)) {
                          self.slideListItems.eq(i).css("left", self.slideListItemWidth + "px");
                      }
                      else {
                          var slideShift = (i - self.current) * self.slideListItemWidth;
                          self.slideListItems.eq(i).css("left", slideShift + "px")
                      }
                  }
                  break;
              case "ScrollVertical":
                  // set styles for vertical scrolling here
                  break;
              case "Fade":
                  self.slideListItems.hide().filter(":first").show();
                  break;
          }
      };

      ContentScroller.prototype.addPreviousNextLinks = function () {
          var self = this;
          var nextDiv = $("<div class='" + self.selectors.nextLinkClassName + "'><a href='' title='Next'><span class='off-screen'>Next Slide</span></a></div>")
			.insertAfter(self.slideContainer);
          self.nextLink = nextDiv.children("a");

          var prevDiv = $("<div class='" + self.selectors.previousLinkClassName + "'><a href='' title='Previous'><span class='off-screen'>Previous Slide</span></a></div>")
			.insertBefore(self.slideContainer);
          self.prevLink = prevDiv.children("a");
      };

      ContentScroller.prototype.bindEvents = function () {
          var self = this;

          self.container.bind("mouseenter.contentScroller", function (e) {
              self.autoCyclePaused = true;
          }).bind("mouseleave.contentScroller", function (e) {
              self.autoCyclePaused = false;
          });

          if (self.d.showPreviousNextLinks) {
              self.nextLink.add(self.prevLink).bind("click.contentScroller", function (e) {
                  e.preventDefault();
                  e.stopPropagation();
                  self.clickHandler(e, this);
              });
          }
      };

      ContentScroller.prototype.clickHandler = function (e, el) {
          var self = this;
          if (!self.isAnimating) {
              // hack for jquery 1.2.6 bug; remove timeout when jquery is upgraded
              setTimeout(function () {
                  self.animateSlides(e, el);
              }, 1);
          }
      };

      //optional option to automatically cycle through items
      ContentScroller.prototype.autoCycle = function () {
          var self = this;
          setInterval(function () {
              if (self.autoCyclePaused == false) {
                  // do not autoCycle if there are video popups and if it is visible
                  if (self.d.hasVideoPopups && $(self.selectors.videoPlayer).is(":visible")) {
                      return;
                  }
                  self.animateSlides();
              }
          }, self.d.autoCycleSpeed);
      };

      ContentScroller.prototype.animateSlides = function (e, el) {
          var self = this, animateDirection;

          self.setAnimateFlag(true);

          // update counters and animate direction
          if ($(el).parent().is("." + self.selectors.previousLinkClassName)) {
              self.current--;
              animateDirection = "+=";
          } else {
              self.current++;
              animateDirection = "-=";
          }

          if (self.current == -1) {
              self.current = self.count - 1;
          } else if (self.current >= self.count) {
              self.current = 0;
          }

          // animate slides
          switch (self.d.animationType) {
              case "ScrollHorizontal":
                  self.slideListItems.animate({ "left": animateDirection + self.slideListItemWidth + "px" }, self.d.animationTime, function () {
                      if (self.slideListItems.index(this) == self.slideListItems.length - 1) {
                          self.setSlideStyles();
                          self.setAnimateFlag(false);
                      }
                  });
                  break;
              case "ScrollVertical":
                  //TODO: Add fade animation and CSS differences
                  break;
              case "Fade":
                  self.slideListItems.filter(":visible").fadeOut(self.d.animationTime, function () {

                      self.slideListItems.eq(self.current).fadeIn(self.d.animationTime, function () {
                          if (jQuery.browser.msie)
                              jQuery(this).get(0).style.removeAttribute('filter');
                      });
                      self.setAnimateFlag(false);
                  });
                  break;
          }
      };
      /* */
      ContentScroller.prototype.setAnimateFlag = function (isAnimating) {
          var self = this;
          self.isAnimating = isAnimating;
      };

      //create option to filter the list of scroller items to a subset of items
      ContentScroller.prototype.filter = function (filterSelector) {
          var self = this;
          var filteredItems = self.slideList.children("li:has('" + filterSelector + "')");
          self.slideListItems.css("left", "-10000px");
          if (filteredItems.length > 0) {
              self.slideListItems = filteredItems;
          }
          else {
              self.slideListItems = self.slideList.children("li");
          }
          self.count = (self.slideListItems.length > 0) ? self.slideListItems.length : 0;
          self.current = 0;
          self.setSlideStyles();
      };

  })(jQuery);

  /**
* Tracking init
*/
$(function () {

    Tracking.init({ trace: false });
    Tracking.Router.init();
    Tracking.Dictionary.init();

});


/**
* Tracking core
*/
(function (Tracking, $) {
    
    var settings = { trace:false,cancelLinkClicks: false };
     
    Tracking.init = function(options) {
        $.extend(settings, options);
        
        $("body").delegate("a, img, [data-tracking]", "click", function (e) {
            var $elem = $(e.currentTarget);
            var id = ($elem.attr("id") || $elem.data("tracking") || $elem.attr("href") || $elem.attr("src"));
            Tracking.publish(id, e);
			if (settings.trace) {
				Tracking.log( 'Click event for element: ' + id );
				if (settings.cancelLinkClicks) e.preventDefault();
			}
        });

        Tracking.log("tracking initialized.");
    };
    
    Tracking.log = function () {
        if (window.console && window.console.log && settings.trace) {
            console.log(Array.prototype.slice.call(arguments));
        }
        $(".output").append("<div>" + Array.prototype.slice.call(arguments) + "</div>");
    };
 
    Tracking.subscribe = function (event, fn) {
        $(document).bind(event, fn);
    };
 
    Tracking.unsubscribe = function (event) {
        $(document).unbind(event);
    };
 
    Tracking.publish = function (event, args) {
        $({ ownerDocument: document }).trigger(event, args);
        if (settings.trace) { Tracking.log( 'tracking event published: ' + event ) }
    };

	Tracking.fireScriptRequest = function(url) {
		if (!document.getElementsByTagName || !document.createElement || !document.appendChild) 
		{
			return false;
		}

		var timestamp = new Date();
		var qs = "?qstr=random=" + Math.ceil(Math.random() * 99999999)+timestamp.getUTCFullYear()+timestamp.getUTCMonth()+timestamp.getUTCDate()+timestamp.getUTCHours()+timestamp.getUTCMinutes()+timestamp.getUTCSeconds()+timestamp.getUTCMilliseconds();
		var uri = url + qs;

		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = uri;
		document.getElementsByTagName("head")[0].appendChild(script);

		return true;
	};
} (window.Tracking = window.Tracking || {}, jQuery));



/**
* Tracking Router - wires dictionary with callbacks
*/
(function (Router, $) {

    Router.init = function () {
        Tracking.subscribe("dictionary-ready", function (e, args) {
            _addTable(args.dictionary);
        });

        Tracking.log("tracking router initialized.");
    };

    var _addTable = function (trackingDictionary) {
        var l = trackingDictionary.length;
        for (var i = 0; i<l; i++) {
            Tracking.subscribe(trackingDictionary[i].id, trackingDictionary[i].call);
        }
    };

} (window.Tracking.Router = window.Tracking.Router || {}, jQuery));



/**
* Dictionary helpers
*/
(function (Dictionary, $) {
    
    var _d = [];

    Dictionary.init = function () {
        Tracking.log("tracking dictionary initialized.");
    };

    Dictionary.add = function (id, fn) {
        _d.push({ id: id, call: fn });
    };

    Dictionary.ready = function () {
        Tracking.publish("dictionary-ready", {dictionary:_d});
    };


} (window.Tracking.Dictionary = window.Tracking.Dictionary || {}, jQuery));

