<!--
/////////////////////////////////////////////////
// Written by Paul Lo, organized on 8/27/08
/////////////////////////////////////////////////

/////////////////////////////////////////////////
// JQuery Section - predefined
/////////////////////////////////////////////////

// please fill in your own domain, e.g. www.dlink.com
var cookieDomain = "domain=" + document.domain;

//var cookieDomain = "domain=www.dlink.com.au";
var $j = jQuery;
$j(document).ready(function()
{ 
   var mouseX;
	var mouseY;
	
	//-------- get mouse position --------
	$j().mousemove(function(e)
	{
	   mouseX = e.pageX;
	   mouseY = e.pageY;
   });     
   
   //-------- google tracking --------
   $j("a,input.common-tracking").click(function()
   {
      var id = $j(this).attr("id");
      var trackingUrl = "";
      var parentId = "";
      var model = ""; // product page only
      
      if($j(this).parent().length > 0)
      {
         parentId = $j(this).parent().attr("id");
      }
      
      if($j("body").find("input[type='hidden']#hiddenModel").length > 0)
      {
         model = $j("body").find("input[type='hidden']#hiddenModel").val();
      }
      
      // master top navigations
      if(id == "topNavHHO")
      {
         trackingUrl = "/?overlay=HHO";
      }
      else if(id == "topNavSMB")
      {
         trackingUrl = "/?overlay=SMB";
      }
      else if(id == "topNavLB")
      {
         trackingUrl = "/?overlay=LB";
      }
      else if(id == "topNavGov")
      {
         trackingUrl = "/?overlay=GE";
      }
      else if(parentId == "overview") // product page resources
      {
         trackingUrl = "/products/?pid=" + model + "&tab=0";
      }
      else if(parentId == "resources")
      {
         trackingUrl = "/products/?pid=" + model + "&tab=1";
      }
      else if(parentId == "accolades")
      {
         trackingUrl = "/products/?pid=" + model + "&tab=2";
      }
      else if(parentId == "workswith")
      {
         trackingUrl = "/products/?pid=" + model + "&tab=3";
      }
      else if(parentId == "addToCart")
      {
         trackingUrl = "/products/" + model + "/addToCart";
      }
      else if(parentId == "findRetailers")
      {
         trackingUrl = "/products/" + model + "/findRetailers";
      }
      else if(parentId == "demo")
      {
         trackingUrl = "/products/" + model + "/dpod";
      }
      else if(parentId == "productSelector")
      {
         var rid = $j(this).attr("rid");
         trackingUrl = "/solutionflashes/?type=1&rid=" + rid;
      }
      else if($j(this).attr("rel") == "product_showTv")
      {
         var vid = $j(this).attr("data");
         trackingUrl = "/products/" + model + "/dlinktvID=" + vid;
      }
      else if($j(this).parents("div[rel='image_download_content']").length > 0) // image download
      {
         var type = "lowResImage";
         var rel = $j(this).find("span").attr("rel");
         
         if(rel == "image_HighRes")
            type = "highResImage";
         
         trackingUrl = "/products/" + model + "/" + type;
      }
      else if($j(this).hasClass("support-download-resources")) // support resources on product page
      {
         // covers emulator, manual, qig, drivers, apps & firmwares
         var dlPath = $j(this).attr("href");
         if(typeof(dlPath) != 'undefined' && dlPath.length > 0)
         {
            trackingUrl = dlPath;
         }
      }
      else if($j(this).hasClass("frameUrl")) // category pages
      {
         if($j(this).hasClass("category-mainbutton"))
         {
            var rid = $j(this).attr("rid");
            trackingUrl = "/solutionflashes/?type=1&rid=" + rid;
         }
         else if($j(this).hasClass("support-read")) // kb or faq
         {
            var rel = $j(this).attr("rel");
            if(typeof(rel) != 'undefined' && rel.length > 0)
            {
               if(rel.indexOf("faqDetail") != -1)
                  rel.replace("faqDetail", "faq");
                  
               trackingUrl = rel;
            }
         }
      }
      else if($j(this).hasClass("solution-mainbutton")) // category pages
      {
          var rid = $j(this).attr("rid");
          trackingUrl = "/solutionflashes/?type=0&rid=" + rid;
      }
      else if($j(this).hasClass("builder-mainbutton")) // category pages
      {
          var rid = $j(this).attr("rid");
          trackingUrl = "/solutionflashes/?type=2&rid=" + rid;
      }
      else if($j(this).hasClass("categoryTVlink")) // category pages
      {
          var vid = $j(this).attr("rel");
          trackingUrl = document.location + "&vid=" + vid;
      }
      else if($j(this).hasClass("casestudy-detail")) // category pages
      {
         var rid = $j(this).attr("rid");
         trackingUrl = "/casestudies/?csid=" + rid;
      }
      else if($j(this).hasClass("common-tracking")) // commmon tracking
      {
         var url = $j(this).attr("href");
         if(typeof(url) != 'undefined' && url.length > 0)
         {
            // faq page top 20
            if($j(this).attr("id") == 'faqTop20')
            {
               url = url + "top20";
            }
         }
         else // special cases, most likely tag input
         {
            var rel = $j(this).attr("rel"); 
            if(typeof(rel) != 'undefined' && rel.length > 0)
            {
               url = rel;
            }
         }
         
         if(url.length > 0)
         {
				trackingUrl = url;
         }
      }
      
      if(trackingUrl.length > 0)
      {
         pageTracker._trackPageview(trackingUrl);
      }
   });

   //---------------Master Page----------------------
   // overlay hp set default
   $j(".set-default").click(function()
   {
      var checked = $j(this).children(":checkbox").attr('checked');
      var cookieVal = $j(this).children(":checkbox").attr("value");

      if(typeof(checked) == 'undefined' || checked == true)
      {
         // check clicked cb and uncheck other cbs
		   $j(".set-default :checkbox").attr("checked", "");
		   $j(this).children(":checkbox").attr("checked", "checked");
			 
			// set cookie
			setHPCookie(cookieVal, cookiePkg);
	   }
   });
   
   // home page preference options panel for the first time
   $j(".set-hp-default-prompt").click(function()
   {
      var selectedHp = $j(".hpSelection input:radio:checked");
      if(selectedHp.length > 0)
      {
         var hp = selectedHp.val();
         
         // set cookie
			setHPCookie(hp, cookiePkg);
			
			// fade away
			var prompt = $j("#hpSetting");
		   var body = $j("#entry-overlay-body, #entry-overlay-content");
		   
		   if(prompt.length > 0 && body.length > 0 && $j(":animated").length == 0)
		   {
		      // reload flash
		      var containerId = "introContainer";
		      var flash = $j("object#" + containerId);
		      if(flash.length > 0)
		      {
		         flash.replaceWith("<div id=\"" + containerId + "\"></div>");
		         
		         var flashvars = {};      
					flashvars.myURL = hp;
			      
					generateCommonFlash("introContainer", "/main.swf", 950, 443, null, flashvars);
		      }
		      
		      // overlay set default cb
		      var setDefault = $j(".set-default :checkbox[value='" + hp + "']");
		      if(setDefault.length > 0)
		      {
		         setDefault.attr("checked", "checked");
		      }
		      
		      // top nav tabs state
		      var topTabs = $j("#defaultTopNavWrapper a[rel='master_overlay_tab']");
		      if(topTabs.length > 0)
		      {
		         var selectedOn = $j(topTabs.get(hp-1));
		         // change page title
		         document.title = "D-Link - " + selectedOn.attr("title");
		         
		         if(topTabs.hasClass("on")) // remove default on tab
		         {
		            var currentOn = topTabs.filter(".on");
		            if(currentOn.length > 0)
		            {
		               if(currentOn.attr("id") != selectedOn.attr("id"))
		               {
		                   currentOn.removeAttr("class");
		               }
		            }
		         }
		         
		         selectedOn.attr("class", "on");
		      }
		      
		      $j("#header").css({"z-index":276});
		      prompt.fadeOut(300);
		      body.fadeOut(200);
		   }
      }
      
      return false;
   });
   
   // master bottom navigation, hover over effect
   $j(".btmNav").hover(function()
   {
      var infoId = $j(this).attr("rel");
      var content = $j("#" + infoId);
      
      $j("#footer").css("zIndex", "300");
      $j("#" + infoId).fadeIn(500);
   }, function()
   {
      var infoId = $j(this).attr("rel");
      var content = $j("#" + infoId);
       
      $j("#footer").css("zIndex", "");
      content.fadeOut(200);
   });
   
   // search box, close all search results, other than this one
   $j("input.searchBoxFormat").focus(function()
   {
      if($j("div.searchResult").hasClass("on"))
      {
         $j("div.searchResult").removeClass("on").addClass("off");
      }
      
      // show the result when there's text in the box
      if($j(this).val().length > 0)
      {
         var result = $j(this).parent().siblings("div.searchResult");
         if(result != null && result.html().length == 0) // don't call ws if there's already results
         {
            GetSearchResult($j(this).val(), $j(this).parent("div.searchWrapper, div.searchWrapper-wh").siblings("div.searchResult").attr("id"), $j(this).attr("rel"));
         }
         else
         {
            // show 
            result.removeClass("off").addClass("on");
         }
      }
      
   }).keydown(function(event) // key press
   {
      var key = event.keyCode;
      if(key == 13) // enter
      { 
         $j("input,a").blur();
         var term = $j(this).val();
         var type = $j(this).attr("rel");
         
         var resultList = $j(this).parent("div.searchWrapper, div.searchWrapper-wh").siblings("div.searchResult");
         var selected = resultList.find("ul.searchresults li.selected");
         var resultItemAction = function(link)
         {
            if(!link.hasClass("frameUrl"))
            {
               var dest = link.attr("href");
               if(document.location)
	            {
					   document.location = dest;
					}
					else
					{
					   document.location.url = dest;
					}
            }
            else
            {
               FrameUrl(link.get(0));
            }  
         };
         
         // no results or no result is selected
         if(!resultList.hasClass("on") || selected.length == 0) 
         {
            var resultCounts = resultList.find("ul.searchresults li").length;
            
            if(type == 'WWWProducts')
            {
					var searchDest = "/search/?qry=" + encodeURIComponent(term);
               
               if(document.location)
	            {
					   document.location = searchDest;
					}
					else
					{
					   document.location.url = searchDest;
					}
					return;
            }
            
            // there's a such product model, typed in full and found in db
            if(resultCounts == 1 && resultList.hasClass("on")) 
            {
               var selectedItem = resultList.find("ul.searchresults li a");
               resultItemAction(selectedItem);
            }
            else if(resultList.hasClass("on")) // more than one results
            {
               alert("Please pick a result from the list.");
            }
            else if(!resultList.hasClass("on")) // no results
            {
               if(term != null && term.length > 0)
               {
                  alert("No results found for the search term. Please enter a new one.");
               }
               else
               {
                  alert("Please enter a search term");
               }
            }
         }
         else // list is showing & item is selected
         {
            var link = selected.children("a");
			   resultItemAction(link);
         }
      }
   });
   
   // kb item click
   $j("a.product-kb-item").click(function()
   {
      var url = $j(this).attr("rel");
      var detailFrame = $j("#kbDetailFrame").attr("src", url);
   });
   
   // master top nav, controls tabs that should slide
   $j("a[rel='master_overlay_tab']").click(function()
   {
      var tab = $j("#" + this.id + "_content");
      var commonPanel = $j("#defaultPanesShadowWrapper");
      var contentDisplay = $j(tab).css("display");

      if(contentDisplay == "none")
      {
         $j(tab).siblings().hide();
         $j("a[rel='master_overlay_tab']").removeClass('on');
         $(this).addClassName('on');
         commonPanel.slideDown(500, function()
         {
            tab.css({display:"block"});
         });
      }
      else
      {
         $(this).removeClassName('on');
         tab.css({display:"none"});
         commonPanel.slideUp(250);
      }
   });
   
   // close the slided down window on top nav
   $j("#closeButton").click(function()
   {
      $j("div[rel='overlay_content']").css({display:"none"});
      $j("a[rel='master_overlay_tab']").removeClass("on");
      $j("#defaultPanesShadowWrapper").slideUp(250);
   });
   
   //------ world wide offices page ------
   // not being used
   $j("a.show-hp-pref").click(function()
   {
      ShowHpPreferenceOptions();
   });
   
   // controls top resource section on product page
   $j("ul.product-top-resources > li").click(function()
   {
      if($j(this).hasClass("disable"))
         return false;
   
      var commonpanel = $j("#tabWrapper");
      var rel = $j(this).attr("rel");
      
      var content = $j("div[rel='" + rel + "_content']");
      
      // only 2 buttons at the bottom should be related
      var bottomResources = $j("#dlinktv, #findRetailers");
      
      DLinkTV.defaultToIntro('tvContainer');
      
      // to open
      if(content.css("display") == "none")
      {
         $j(this).addClass("on");
         $j(this).siblings().removeClass("on");
         
         // remove bottom resource status
         bottomResources.removeClass("on");
         content.siblings().css({display:"none"});
         
         commonpanel.slideDown(250, function()
         {
            content.fadeIn(300);
         });
      }
      else
      {
         // to close
         content.fadeOut(150, function()
         {
            commonpanel.slideUp(250);
         });
         $j(this).removeClass("on");         
      }
   });
   
   // control how sub category items slide out when mouse over, slide in
   // when mouse out
   $j("a.biz-category-listItem").mouseover(function()
   {
      if($j(":animated").length > 0)
         return;
   
      // change to content parent's parent instead of ID
      var group = $j(this).attr("name");
      $j("a.biz-category-listItem[name='" + group + "']").removeClass("on");
      
      // don't stay on
      if(typeof($j(this).attr("rel")) != 'undefined' && $j(this).attr("rel").length > 0)
      {
			var content = $j("#" + $j(this).attr("rel"));
			// sub pane
			var sub = $j(this).parents("div.double-panes-left:first").siblings("div.double-panes-right:first");
			if(content.length == 0) // no sub content?
			{
			   if(sub.hasClass('open'))
			   {
					// close all
					sub.children(":nth-child(2)").fadeOut(200, function()
					{
					   sub.animate({backgroundPosition:"-365px 0"},300, function()
						{
							sub.removeClass('open');
					   });
					});
					
					sub.children(":nth-child(2)").children().each(function()
					{
					   $j(this).css("display", "none");
					});
			   }
			}
			else // there's sub content
			{
			   if(content.css("display") != "block") // not the same one selected
				{
					if(typeof(content.css("display")) == "undefined")
					{
						// hides all sub section if this element doesn't have a sub
						var rightContent = sub.children(":nth-child(2)");
						rightContent.children().each(function()
						{
							$j(this).css("display", "none");
						});
					}
					else
					{
						content.parent().children().each(function()
						{
							$j(this).css("display", "none");
						});
				      
						if(!sub.hasClass('open'))
						{
							sub.addClass('open');
							sub.animate({backgroundPosition:"-184px 0"},500, function()
							{
								content.parent().fadeIn(300, function()
								{
								});
							});
						}
						content.css("display", "block");
					}
				}   
			}
      }
   });
   
   //---------------Prodict Page----------------------
   // control items inside those 4 tabs in the product page,
   // such as features in the overview, firmware in the support...etc.
   $j(".controller-index").click(function()
   {
      var contentId = "#" + $j(this).attr("rel");
      if(typeof($j(contentId)) != 'undefined' && $j(contentId).length > 0)
      {
         $j(this).parents("div.group-parent").find("a.linkOn").removeClass("linkOn");
         $j(this).addClass("linkOn");
         var siblingsCnt = $j(contentId).siblings().length;
         
         if($j(contentId).css("display") != 'block')
         {
            if(siblingsCnt > 0)
            {
					$j(contentId).siblings().slideUp(200,function()
					{
						$j(contentId).slideDown(500, function()
						{              
						});
					});
				}
				else
				{
					$j(contentId).slideDown(500);
				}
         }
         else
         {
            $j(this).removeClass("linkOn");
            $j(contentId).slideUp(500, function()
            {
            });
         }
      }
   });
   
   // not being used
   $j("#dlinktv").click(function()
   {
      if($j(this).hasClass("disable"))
         return false;
      
      var commonpanel = $j("#tabWrapper");
      var content = $j("div[rel='" + this.id + "_content']");
      
      if(content.css("display") == "none")
      {
         content.siblings().css({display:"none"});
         $j(this).addClass("on");
         
         // bottom resource nav
         $j(this).siblings().removeClass("on");
         // top resource nav
         $j("ul.product-top-resources > li").removeClass("on");
         
         //=====
         // show primary video on load
         var tvplayer = content.find("div#tvPlayer");
         var primaryId = content.attr("data");
         
         if(tvplayer.length > 0)
         {
				if(primaryId != null && primaryId > 0 && tvplayer.css("display") == "block")
				{
					DLinkTV.updateMovieSrcLink(primaryId,"tvContainer");
				}
         }
         //=====
         
         commonpanel.slideDown(250, function()
         {
            content.fadeIn(300);
         });
      }
      else
      {
         // set back to default when closing
         DLinkTV.defaultToIntro('tvContainer');
         content.fadeOut(150, function()
         {
            commonpanel.slideUp(250);
         });
         
         $j(this).removeClass("on");
      }
   });
   
   // content overlay close button
   $j("a.contentOverlayCloseBtn").click(function()
   {
      ContentOverlay.Close();
   });
   
   // dlink tv and list switch, not being used
   $j("a[rel='product_showTvList']").click(function()
   {
      var tvList = $j("div[rel='product_tvList']");      
      DLinkTV.defaultToIntro('tvContainer');
      
      $j(this).parent().fadeOut(500, function()
      {
         tvList.fadeIn(800);
      });
   });
      
   // dlink tv list, not being used
   $j("a[rel='product_showTv']").click(function()
   {
      var tvList = $j("div[rel='product_tvList']");
      var tvId = $j(this).attr("data");
      
      DLinkTV.updateMovieSrcLink(tvId,"tvContainer");
      tvList.fadeOut(500, function()
      {
         $j("#tvPlayer").fadeIn(800);
      });
   });
      
   // image scroller, swap main images, 
   // update download panel content
   $j("img[rel='product_thumbnail']").click(function()
   {
      var mainImage = $j("img[rel='product_mainImage']");
      var imageSrc = $j(this).attr("src");//$j(this).get(0).src;
      var title = $j(this).attr("title");
       
      // main image swap, change href & alt 
      if(imageSrc.length > 0)
      {
         var mainImageSrc = imageSrc.replace("_thumb.jpg", ".png");
         mainImage.attr("src", mainImageSrc);
         mainImage.attr("alt", $j(this).attr("alt"));
         mainImage.attr("title", title);
      }
       
      // change resolution size text & download paths
      var lowResSpan = $j("span[rel='image_LowRes']");
      var highResSpan = $j("span[rel='image_HighRes']");
      var webSize = $j(this).attr("web");
      var printSize = $j(this).attr("print");
      var thumbImageFullPath = $j(this).attr("src"); // http://....somthing.jpg
      var thumbImagePathEndIndex = thumbImageFullPath.lastIndexOf("/"); 
      var thumbnailFullName = thumbImageFullPath.substring(thumbImagePathEndIndex + 1); // somthing.jpg
      var downloadPath = null;
      var webDownload = null;;
      var printDownload = null;
       
      if(lowResSpan != null)
      {
         lowResSpan.each(function(i)
         {
            $j(this).html(webSize);
            webDownload = $j(this.parentNode);
            if(webDownload != null)
            {
               if(downloadPath == null)
               {
                  // ftp path
                  var path = webDownload.attr("href");
                  var pathEndIndex = path.lastIndexOf("/");
                  downloadPath = path.substring(0, pathEndIndex + 1);
               }
                
               if(downloadPath != null)
                  webDownload.attr("href", downloadPath + thumbnailFullName.replace("_thumb", ""));
            }
         });
      }
          
      if(highResSpan != null)   
      {
         highResSpan.each(function(i)
         {
            $j(this).html(printSize);
            printDownload = $j(this.parentNode);
            if(printDownload != null && downloadPath != null)
            {
               printDownload.attr("href", downloadPath + thumbnailFullName.replace("_thumb.jpg", ".tif"));
            }
         });
      }
   });
    
   // show the image downloading panel, sliding up
   $j("#product_imageDownload").click(function()
   {
      var imageContent = $j("div[rel='image_download_content']");
       
      if(imageContent.css("display") == "none")
      {
         imageContent.show(1, function()
         {
            $j(this).animate({top:"0px"}, 800);
         });
      }
      else
      {
         imageContent.animate({top:"32px"}, 800, function()
         {
            $j(this).hide();
         });
      }
   });
   
   //----------- general functions -----------
   // product selector link
   // rel = url, a.productSelectorLink
   $j("select.ddl-link").change(function()
   {
      var url = $j(this).attr("rel");
      
      var exUrl = $j(this.options[this.selectedIndex]).attr("rel");
      
      if(typeof(exUrl) != 'undefined' && exUrl.length > 0)
         url = exUrl;
      
      var val = this.options[this.selectedIndex].value;
      
      if(val != null && val != -1)
      {
         location.href = url + val;
      }
   });
   
   // all link, image link, or input that might cause an action
   // to show an iframe with specified URL
   $j("a.frameUrl, input.frameUrl").click(function()
   {
      var url = $j(this).attr("rel");
      ContentOverlay.ShowProductSelector(url);
            
      return false;
   });
   
   // all Tree Node Sign Click, not being used
   $j("div.treeExpandSign > a").click(function()
   {
      var treeTitle = $j(this).parent().next();
      if(treeTitle != null)
         $j(treeTitle).click();
   });
   
   // all Neutral(no content, downloads only) attributes addon
   // not being used
   $j.each($j("div.treeNeutralSign > a"), function()
   {
      var treeTitle = $j(this).parent().next();
      if(treeTitle != null)
      {
         var href = $j(treeTitle).attr("href");
         var target = $j(treeTitle).attr("target");
         
         // if resource only has downloadable files, fill in href & target
         // attrs, or else if resource is a clickable, then add the click
         // event to the current element
         if(typeof(href) == 'undefined' || href == null || href.length == 0)
         {
            $j(this).click(function()
            {
               if($j(treeTitle).click)
                  $j(treeTitle).click();
            });
         }
         else
         {
             $j(this).attr("href", href);
             $j(this).attr("target", target);
         }
      }
   });
   
   // all Tree Nodes Click
   // <a> with rel='treeview_link' with a <div> as
   // immediate sibling for the content
   // not being used
   $j("a[rel='treeview_link']").click(function()
      {
         var sectionToShow = $j(this).parent().next();
         var signSpan = $j(this).prev();
         
         if($j(signSpan).hasClass("treeExpandSign"))
         {
             // <a>
             var signLink = signSpan.children(":first");
             
             if($j.trim($j(signLink).html()) == "+")
             {       
                $j(signLink).html("-");
                $j(signLink).css({marginLeft: "2px"});
             }
             else
             {
                $j(signLink).html("+");    
                $j(signLink).css({marginLeft: ""});  
             }
             
             $j(sectionToShow).slideToggle(300);
         }
      });
  
   //----------- company press template -----------
   // use to control tabs such as those on /sales/where2buy
   $j(".supportContent").click(function()
   {
      var rel = $j(this).attr("rel");
      var title = $j(this).attr("title");
      var id = $j(this).attr("id");
      var hasFrame = $j(this).hasClass("frameContent");
      var hasSearch = $j(this).hasClass("searchContent");
      
      if(typeof(rel) != 'undefined' && rel.length > 0)
      {
         var contentId = "#" + id + "_content"; 
         var contentBody = $j("#" + rel + " div.company-landing");

         $j(this).siblings("a.linkOn").removeClass("linkOn");
         
         if(!$j(this).hasClass("linkOn"))
            $j(this).addClass("linkOn");
          
         if(hasFrame)
         {
            contentId = "#frame_content";
            var src = $j(this).attr("url");
            
            if(hasSearch)
            {
               var term = $j(this).prev("input").val();
               src = src + term;
            }
            
            $j(contentId).children("iframe").attr("src", src);
         }
         
         if(contentBody.css("display") != 'block' || contentBody.css("display") == '')
         {
            contentBody.slideDown(500, function()
            {
					if($j(contentId).css("display") != 'block')
					{
						$j(contentId).siblings().css("display", "none");
						$j(contentId).fadeIn(300, function()
						{
						   
						});
					}
            });
         }
         else
         {
            if($j(contentId).css("display") != 'block')
				{					 
					$j(contentId).siblings().css("display", "none");
					$j(contentId).fadeIn(300, function()
					{ 
					});
				}
         }
         
         return false;
      }
   });

   //----------- find your product page -----------
   $j(".category-mainbutton").click(function()
   {
      var id = "prompt";
      var prompt = $j("#" + id);
		if(!$j(this).hasClass("frameUrl") && $j(":animated").length == 0)
		{
		   var rel = $j(this).attr("rel");
		   var rid = $j(this).attr("rid");
		   var cid = $j(this).attr("cid");
		   
			// show popup option
			if(prompt.length == 0) // not created yet
			{
				$j("body").append("<div id=\"" + id + "\" class=\"find-product-prompt\" style=\"width:224px;height:134px;\"><h3 class=\"page-title\" style=\"margin:15px 5px 9px 12px;font-size:12pt;\"></h3><a class=\"option-buttons frameUrl\">Product Selector</a><a class=\"option-buttons product-list\" style=\"margin-top:10px;\">List of Products</a></div>");
            
				prompt = $j("#" + id); // reassign
            var bodyHt = $j("#containerBody").css("height").replace("px","");
            var bodyWd = $j("#containerBody").css("width").replace("px","");
            var pmptHt = prompt.css("height").replace("px","");
            var pmptWd = prompt.css("width").replace("px","");	            
            var left = $j("#containerBody").offset().left + Math.floor(bodyWd/2-pmptWd/2);
            var top = $j("#containerBody").offset().top + Math.floor(bodyHt/2-pmptHt/2);

				prompt.css({left:left,top:top,"z-index":1000});
           
				// register event
				prompt.find(".frameUrl").click(function()
				{
					FrameUrl($j(this));
					prompt.fadeOut(150);
					
					// google tracking
					var rid = $j(this).attr("rid");
					if(typeof(rid) != 'undefined')
					{
					   pageTracker._trackPageview("/solutionflashes/?type=1&rid=" + rid);
					}
				});
			}
         
         if(typeof(rel) != 'undefined' && typeof(rid) != 'undefined')
         {
			   var psLink = prompt.find(".frameUrl");
			   psLink.attr("rel", rel);
			   psLink.attr("rid", rid);
			}
			
			if(typeof(cid) != 'undefined')
			{
            var productList = prompt.find(".product-list");
            productList.attr("href", "/products/category/?cid=" + cid);
         }
         
			// change text
			prompt.find(".page-title").html("find " + $j(this).text());
         
			prompt.fadeIn(300);
		}
		else
		{
			if(prompt.length > 0 && prompt.css("display") != "none")
			{
				prompt.fadeOut(150);
			}
		}
   });

	//----------- product category page -----------
	// customized tooltip for resources
	$j("a.tooltip").hover(function()
	{
		var off = $j(this).offset();
		var popupId = $j(this).attr("popup");
	   
		if(popupId != null && popupId.length > 0 && $j("#" + popupId).length > 0)
		{
			$j("div.popupToolTip").css({'position':'absolute','left': off.left + "px",'top': off.top + "px",'z-index':'300'});
			$j("div.popupToolTip div.popupWrapper").css({'display':'block'});
			$j("#" + popupId).css({'display':'block'});
		}

	}, function()
	{
		var popupId = $j(this).attr("popup");
		$j("div.popupToolTip div.popupWrapper").css({'display':'none'});
		$j("#" + popupId).css({'display':'none'});
	});
    
   // illustration transition from bw to color   
   $j("#illustSwapZone").hover(function()
   {

   },function()
   {
      $j(this).data("position", "out");
      var illust = $j("#sec_illustration");
      if(illust.length > 0)
      {
         illust.fadeIn(600);
      }
   }).mousemove(function(e)
   {
      var illust = $j("#sec_illustration");
      $j(this).data("position", "in");
      var position = $j(this).data("position");

      if(illust.length > 0)
      {
         setTimeout(function()
         {
            // if timein value is the same, means user has stayed
            // in the zone for at least .8 sec
            var currentPos = $j(this).data("position");
            if(position == currentPos && illust.is(":not(:animated)") && illust.css("display") != 'none')
            {
               illust.fadeOut(600);
            }
         }.bind(this), 700);
      }
   });
      
   // mini d-link tv switch, not being used
   $j("a.categoryTVlink").click(function()
   {
      var tvId = $j(this).attr("rel");
      var tvplayer = $j("#tvplayerWrapper");
      
      // change the link of "view in full size" on top
      var swapFullSizeID = function() 
      {
         var viewInFull = tvplayer.find("#fullSizeTv");
         if(viewInFull.length > 0)
         {
				var url = viewInFull.attr("rel");
				viewInFull.attr("href", url + tvId);
         }
      };
      
      // not playing, sohw tv
      if(tvplayer.css("display") == "none")
      {
         $j(this).addClass("clicked");
         DLinkTV.updateMovieSrcLink(tvId,"tvplayer");
         swapFullSizeID();         
         tvplayer.show(500);
      }
      else // playing
      {
         // clicking on the same one that's playing
         if($j(this).hasClass("clicked"))
         {
            $j(this).removeClass("clicked");
            DLinkTV.defaultToIntro("tvplayer");
            tvplayer.hide(500);
         }
         else // clicking on a different episode
         {
            $j("a.categoryTVlink").removeClass("clicked");
            $j(this).addClass("clicked");
            swapFullSizeID();
            DLinkTV.updateMovieSrcLink(tvId,"tvplayer");
         }
      }
   });
      
   //----------- solution page -----------
   // search "go" click
   $j("a[rel='solution_go']").click(function()
   {
      var zip = $j("div.province-selection-text").html();
      
      if(zip.length == 0 || zip == 'Please pick a province')
      {
         alert("Please pick a province");
         return false;
      }
   });
   
   // search box, press enter 
   $j("input[rel='solution_zip']").keydown(function(event)
   {
      if(event.keyCode == 13)
      {
         $j("a[rel='solution_go']").focus();
      }
   });
    
   //----------- press inquiry page -----------
   $j("a.pi-item").click(function()
   {
      var html = $j(this).html();
      $j("#prContentHeader").html(html);
       
      // update comment header text
      var cmtHeader = $j(this).attr("cmtText");
      $j("#prCmtText").html(cmtHeader);
      
      // update pr type
      $j("#templateRightContent").next("input[type='hidden']").val(html);
   });
    
   //----------- all forms client check -----------
   function FormInputEmptyCheck(formid, rel, fieldname)
   {
      // textbox or textarea
      var ctrl = $j("#" + formid + " *[rel='" + rel + "']");
      var val = ctrl.val();
       
      if(typeof(val) == 'undefined' || val.length == 0) // input box
      {
         alert("Please fill in " + fieldname);
         return false;
      } 
       
      return true; 
   }
    
   function FormCheckBoxCheck(formid, rel, msg)
   {
      var ctrl = $j("#" + formid + " input[rel='" + rel + "']");
      var checked = ctrl.attr("checked");
      
      if(!checked)
      {
         alert(msg);
         return false;
      } 
       
      return true; 
   }
    
   // form on /products/ip-surveillance/free-site-survey/
   $j("*.free-site-survey-submit").click(function()
   {
      return (FormInputEmptyCheck("siteSurvey", "fn", "first name") && 
              FormInputEmptyCheck("siteSurvey", "ln", "last name") &&
              FormInputEmptyCheck("siteSurvey", "company", "company name") && 
              FormInputEmptyCheck("siteSurvey", "title", "job title") && 
              FormInputEmptyCheck("siteSurvey", "email", "email") && 
              FormInputEmptyCheck("siteSurvey", "phone", "phone number") && 
              FormInputEmptyCheck("siteSurvey", "address", "address") && 
              FormInputEmptyCheck("siteSurvey", "city", "city") && 
              FormInputEmptyCheck("siteSurvey", "state", "state") &&
              FormInputEmptyCheck("siteSurvey", "zip", "zip"));
   });
    
   // form on /business/test-drive/
   $j("*.test-drive-submit").click(function()
   {
      return (FormInputEmptyCheck("testDriveForm", "companyname", "company name") && 
              FormInputEmptyCheck("testDriveForm", "name", "name") &&
              FormInputEmptyCheck("testDriveForm", "resellername", "reseller name") && 
              FormInputEmptyCheck("testDriveForm", "companyaddress", "company address") && 
              FormInputEmptyCheck("testDriveForm", "title", "job title") && 
              FormInputEmptyCheck("testDriveForm", "city", "city") &&
              FormInputEmptyCheck("testDriveForm", "state", "state") &&
              FormInputEmptyCheck("testDriveForm", "zip", "zip") &&
              FormInputEmptyCheck("testDriveForm", "companyweb", "company web") &&  
              FormInputEmptyCheck("testDriveForm", "companyemail", "company email") && 
              FormInputEmptyCheck("testDriveForm", "companyPhone", "company phone number"));
   });
   
   // form on /government-education/try-before-you-buy/
   $j("*.try-before-you-buy-submit").click(function()
   {
       var inputFormName = "trybeforeyoubuyform";
       return (FormInputEmptyCheck(inputFormName, "companyname", "Agency name") && 
              FormInputEmptyCheck(inputFormName, "companyaddress", "Agnecy address") && 
              FormInputEmptyCheck(inputFormName, "name", "your name") &&
              FormInputEmptyCheck(inputFormName, "title", "job title") && 
              FormInputEmptyCheck(inputFormName, "city", "city") &&
              FormInputEmptyCheck(inputFormName, "state", "state") &&
              FormInputEmptyCheck(inputFormName, "zip", "zip") &&
              FormInputEmptyCheck(inputFormName, "email", "email") && 
              FormInputEmptyCheck(inputFormName, "phone", "phone number"));
   });
   
   // form on /contactus/feedback/ 
   $j("*.feedback-submit").click(function()
   {
      return (FormInputEmptyCheck("feedBackForm", "email", "email") && 
              FormCheckBoxCheck("feedBackForm", "terms", "You must agree to the D-Link's terms and conditions to submit your feedback."));
   });
   
   // form on /business/government-education/contact/
   $j("*.govEd-contact-submit").click(function()
   {
      return(FormInputEmptyCheck("govedContactForm", "fn", "first name") && 
             FormInputEmptyCheck("govedContactForm", "ln", "last name") && 
             FormInputEmptyCheck("govedContactForm", "agency", "agency/school name") && 
             FormInputEmptyCheck("govedContactForm", "email", "email") && 
             FormInputEmptyCheck("govedContactForm", "phone", "phone number") && 
             FormInputEmptyCheck("govedContactForm", "address", "address") && 
             FormInputEmptyCheck("govedContactForm", "city", "city") && 
             FormInputEmptyCheck("govedContactForm", "state", "state") && 
             FormInputEmptyCheck("govedContactForm", "zip", "zip"));
   });
    
   // form on /giveaway/monthly-giveaway
   $j("*.giveaway-submit").click(function()
   {
      if($j("select[rel='state']").val() == "")
      {
         alert("Please select a state");
         return false;
      }
       
      if($j("input[rel='email']").val().indexOf("@") == -1 ||
	      $j("input[rel='email']").val().indexOf(".") == -1)
	   {
         alert("Please enter a valid email.");
	      $j(this).focus();
         return false;
		}
    
      return(FormInputEmptyCheck("giveawayForm", "fn", "first name") && 
             FormInputEmptyCheck("giveawayForm", "ln", "last name") && 
             FormInputEmptyCheck("giveawayForm", "email", "email") &&  
             FormInputEmptyCheck("giveawayForm", "zip", "zip") &&
             FormCheckBoxCheck("giveaways2ndForm", "terms", "You must agree to the D-Link's terms and conditions to sign up for D-News."));
   });
   
   // form on business/care-support-packages 
   $j("*.care-support-submit").click(function()
   {
      return(FormInputEmptyCheck("careSupportPkgForm", "fn", "first name") && 
             FormInputEmptyCheck("careSupportPkgForm", "ln", "last name") && 
             FormInputEmptyCheck("careSupportPkgForm", "email", "email") &&  
             FormInputEmptyCheck("careSupportPkgForm", "company", "company name") &&
             FormInputEmptyCheck("careSupportPkgForm", "title", "job title") &&
             FormInputEmptyCheck("careSupportPkgForm", "phone", "phone number") &&
             FormInputEmptyCheck("careSupportPkgForm", "address", "address") &&
             FormInputEmptyCheck("careSupportPkgForm", "city", "city") &&
             FormInputEmptyCheck("careSupportPkgForm", "state", "state") &&
             FormInputEmptyCheck("careSupportPkgForm", "zip", "zip"));
   });
   
   // form on business/secure-link/warrantyform/
   $j("*.warranty-submit").click(function()
   {
      return(FormInputEmptyCheck("warrantyForm", "fn", "first name") && 
             FormInputEmptyCheck("warrantyForm", "ln", "last name") && 
             FormInputEmptyCheck("warrantyForm", "company", "company name") && 
             FormInputEmptyCheck("warrantyForm", "email", "email") && 
             FormInputEmptyCheck("warrantyForm", "phone", "phone number") && 
             FormInputEmptyCheck("warrantyForm", "address", "address") && 
             FormInputEmptyCheck("warrantyForm", "city", "city") && 
             FormInputEmptyCheck("warrantyForm", "state", "state") && 
             FormInputEmptyCheck("warrantyForm", "zip", "zip") &&
             FormInputEmptyCheck("warrantyForm", "date", "date of purchase") &&
             FormInputEmptyCheck("warrantyForm", "place", "place of purcharse") &&
             FormInputEmptyCheck("warrantyForm", "parts", "part number(s)") &&
             FormInputEmptyCheck("warrantyForm", "serial", "serial number(s)"));
   });
    
   //----------- /support/supportscope/ page ----------- 
   $j("*.dynamic-swap").click(function()
   {
      var rel = $j(this).attr("rel");
       
      $j("#" + rel).siblings("*[rel='swapContent']").slideUp(300, function()
      {
         $j("#" + rel).slideDown(500);
      });
   });
   
   //
});
/////////////////////////////////////////////////
// JQuery Section - predefined end
/////////////////////////////////////////////////

//////////////////////////////////////////////////
// Common Functions
//////////////////////////////////////////////////
function LoadSwappedIllust()
{
	$j(document).ready(function()
	{     
		var swapIllust = $j("#swappedIllust");
		var illust = $j("#sec_illustration");
		
		if(illust.length > 0 && swapIllust.length > 0)
		{
			var style = illust.attr("style");
			swapIllust.attr("style", style); // copy over the style
		  
			var bkImg = swapIllust.css("background-image");
			var indOfExt = bkImg.lastIndexOf(".");
			var path = bkImg.substring(0, indOfExt) + "_over" + bkImg.substring(indOfExt);
			swapIllust.css({"background-image" : path});
		}
   });
}

function EntrySelection()
{
   $j("body").append($j("#flashContainer"));
}

function GetDisplayObj()
{
   var display = {};
   $j(document).ready(function()
	{
		var btmBndId = "bottomBound";
		var rightBndId = "rightBound";

		$j("body").append("<div id=\"" + btmBndId + "\" style=\"height:1px;position:absolute;bottom:0px;width:1px\"><!-- comment --></div><div id=\"" + rightBndId + "\" style=\"width:1px;position:absolute;right:0px;height:1px;\"><!-- comment --></div>");
	   
		display.height = $j("#" + btmBndId).offset().top + 1;
		display.width = $j("#" + rightBndId).offset().left + 1;
   });
   return display;
}

function LoadOverlayBlock(id, idToAppend, width, height, positions, direction, speed)
{
   $j(document).ready(function()
	{
	    if(positions != null)
	    {
	       var pos = "";
	       var op = 0.33;
	       //var speed = 700;
	       if(speed == null)
	          speed = 700;
	       
	       if(positions.bottom != null)
	       {
	          pos += "bottom:" + positions.bottom + "px;";
	       }
	       
	       if(positions.top != null)
	       {
	          pos += "top:" + positions.top + "px;";
	       }
	       
	       if(positions.left != null)
	       {
	          pos += "left:" + positions.left + "px;";
	       }
	       
	       if(positions.right != null)
	       {
	          pos += "right:" + positions.right + "px;";
	       }
	       
	       if(idToAppend.indexOf("$") == -1) // $ not found, so it's a tag name, or else it's an id
	          idToAppend = "#" + idToAppend;
	       else
	          idToAppend = idToAppend.replace("$", "");

			 $j(idToAppend).append("<div id=\"" + id + "_shadow\" style=\"width:" + width + ";position:absolute;z-index:9999;height:" + height + "px;overflow:hidden;" + pos + "\"><div id=\"" + id + "\" style=\"position:relative;background-color:black;\"><!-- ie6 --></div></div>");
			 
			 if(direction != null )
			 {
				 if(direction == "up")
				 {
					 $j("#" + id).fadeTo(speed, op).css({height: height + "px",bottom:"-" + height + "px"}).animate({bottom:"0px"}, "slow");
				 }
				 else if(direction == "down")
				 {
				    $j("#" + id).fadeTo(speed, op).css({height: height + "px",top:"-" + height + "px"}).animate({top:"0px"}, "slow");
				 }
				 else if(direction == "right")
				 {
				    $j("#" + id).fadeTo(speed, op).css({height: height + "px",left:"-" + width}).animate({left:"0px"}, "slow");
				 }
				 else if(direction == "left")
				 {
				    $j("#" + id).fadeTo(speed, op).css({height: height + "px",right:"-" + width}).animate({right:"0px"}, "slow");
				 }
			 }
	    }
	});
}

function classSwitch(control, classToAdd, classToRemove)
{
   control = $(control);
   control.addClassName(classToAdd);
   control.removeClassName(classToRemove);
}

//////////////////////////////////////////////////
// Close HomePage Setting @ Default page
//////////////////////////////////////////////////
// sync HP setter radio button selection & each Tab default check box
function syncCheck(value, pkg)
{
   cookieHPPair.each(function(pair)
   {
      if(pair.value == value)
      {
         $(pair.key).checked = true;
      }
   });
   
   setHPCookie(value, pkg);
}

function generateCommonFlash(id, url, width, height, params, flashvars, attributes, showAlternative)
{      
   if(showAlternative == null)
      showAlternative = false;

   if(params == null)
      params = {};

   /* common params */
   params.allowScriptAccess = "sameDomain";
   params.quality = "high";
   params.bgcolor = "#ffffff";
   params.wmode = "transparent";
   
   var exIntall = null;
   
   if(!showAlternative)
      exIntall = "/expressInstall.swf";
      
   if(url.substring(0,1) != '/' && url.indexOf('http') == -1)
      url = "/" + url;
   
   swfobject.embedSWF(url, id, width, height, "9.0.0", exIntall, flashvars, params, attributes);
}

//----------- D-Link TV Function, not being used -----------
/*
   DLinkTV variable contains functions and settings to play embedded D-Link TV
   - CreatMovie is called on page loading to creat the object
   - UpdateMovieSrcLink is called to change the src of the playing video
   - DefaultToIntro is called to switch the playing video to the Intro video
*/
var DLinkTV =
{
   player: null,
   vid: 0,
   settings: 
   {
      playerID: "www_dlinkTV",
      width: 400,
      height: 300,
      size: 1,
      tvContainerID: "tvContainer"
   },
   createMovie: function(containerId, width, height)
   {
 	   var flashvars = {};
      var attributes = {};
      var params = {};
      
      params.menu = "false";
      params.allowScriptAccess = "always";
      params.wmode = "transparent";
 	   generateCommonFlash(containerId, "/player_www.swf?vid=", width, height, params, flashvars, attributes);
   },
   updateMovieSrcLink: function(id, containerId)
   { 
      var player = $(containerId);
      if(player != null)
      {
         var timeout = 1000;
            
         if(player.tagName.toLowerCase() == 'object')
         {
            setTimeout(function()
            {
               if(player.playMovie)
               {
                  player.playMovie(id);
                  DLinkTV.vid = id;
               }
            }, timeout);
         }
      }
   },
   defaultToIntro: function(containerId)
   {
      if(DLinkTV.vid != 0)
      {
         this.updateMovieSrcLink(0, containerId);
      }
   }
};

//----------- D-Link Home Page Cookie Setting -----------
var cookieHPValues = {HHO:1, SMB:2, LB:3, GOV:4, NA:0};
var cookieHPPair = $H();

// cookie settings
var cookiePkg = 
{
   name: 'dlinkHPSetting',
   value: cookieHPValues.NA,
   expDays: 365,
   expires: 3600000 * 24 * this.expDays
};

function setHPCookie(value, pkg)
{
   if(value != null)
      pkg.value = value;
   
   var exDate = new Date();
   exDate.setDate(exDate.getDate() + pkg.expDays);
   
   if(cookieDomain.length > 0)
      cookieDomain = ";" + cookieDomain;
   
   document.cookie = pkg.name + "=" + escape(pkg.value) + cookieDomain + ";expires=" + exDate.toGMTString() + ";path=/";
}

function getHPCookie(cookieName)
{
   if (document.cookie.length>0)
   {
      var start = document.cookie.indexOf(cookieName + "=");
      if (start!=-1)
      { 
         start = start + cookieName.length+1; 
         end = document.cookie.indexOf(";", start);
         if (end==-1) end=document.cookie.length;
            return unescape(document.cookie.substring(start,end));
      } 
   }
   return "";
}

//called when the check box on each tab is clicked, and
//set the cookie; if unchecked, set HHO as Default
function checkHP(control, value, pkg)
{
   if(control != null && pkg != null)
   {
      if(value == null)
         value = cookieHPValues.NA;
         
      if(control.checked)
      {
         setHPCookie(value, pkg);
         
         // uncheck all other options
         cookieHPPair.each(function(pair)
         {
            var ctrl = $(pair.key);
            if(ctrl.id != control.id)
            {
               ctrl.checked = false;
            }
         }.bind(this));
      }
      else
      {
         setHPCookie(cookieHPValues.NA, pkg);
      }
   }
}

//----------- Image Scroller ----------
var scroller = 
{
   scroll: function(direction,pkg,booster)
   {
      var thisPkg = pkg;
      if(thisPkg == null || direction == null)
         return;
         
      if(booster == null)
         booster = 1;   
         
       if(direction == "left")
       {
           this.clearScroll(thisPkg);
           if(thisPkg.imageCount > thisPkg.imageToShow)
           {
              this.scrollLeft(thisPkg, booster);
           }
       }
       else
       {
           this.clearScroll(thisPkg);
           if(thisPkg.imageCount > thisPkg.imageToShow)
           {
              this.scrollRight(thisPkg, booster);
           }
       }
   },
   scrollLeft: function(pkg, booster) // should be on the right arrow
   {
      var thisPkg = pkg;
      if(thisPkg == null)
         return;
         
      var currentPosition = Number($(thisPkg.thumbnailWrapper).getStyle("left").replace("px","")) - (thisPkg.scrollSpeed*booster);
      var positionInPixel = currentPosition + "px"; 

      if(currentPosition >= thisPkg.leftBnd)
      {
         $(thisPkg.thumbnailWrapper).setStyle({left: positionInPixel});

         if(thisPkg.scrollInterval == null)
         {
            thisPkg.scrollInterval = setInterval(function(){this.scrollLeft(thisPkg, booster);}.bind(this), 10);
         }
      }
      else
      {
         var leftEnd = thisPkg.leftBnd + "px";
         $(thisPkg.thumbnailWrapper).setStyle({left: leftEnd});
         clearInterval(thisPkg.scrollInterval);
         thisPkg.scrollInterval = null;
      }   
   },
   scrollRight: function(pkg, booster)
   {
      if(pkg == null)
         return;
         
      var currentPosition = Number($(pkg.thumbnailWrapper).getStyle("left").replace("px","")) + (pkg.scrollSpeed*booster);
      var positionInPixel = currentPosition + "px"; 

      if(currentPosition < pkg.rightBnd)
      {
         $(pkg.thumbnailWrapper).setStyle({left: positionInPixel});

         if(pkg.scrollInterval == null)
         {
            pkg.scrollInterval = setInterval(function(){this.scrollRight(pkg, booster);}.bind(this), 10);
         }
      }
      else
      {
         var rightEnd = pkg.rightBnd + "px";
         $(pkg.thumbnailWrapper).setStyle({left: rightEnd});
         clearInterval(pkg.scrollInterval);
         pkg.scrollInterval = null;
      }   
   },
   clearScroll: function(pkg)
   {
      clearInterval(pkg.scrollInterval);
      pkg.scrollInterval = null;
   }
};

//----------- Product Page Quote Rotator ----------
function rotate(pkg)
{
     var control = $(pkg.control);
     var rotationText = pkg.rotationText;
     
     if(control.getStyle("opacity") != 0)
     {
        control.setStyle({opacity:0, filter:"alpha(opacity=0)"});
     }
      
     if(Object.isUndefined(control.rotateIndex))
     {
        control.rotateIndex = 0;
        var displayText = rotationText[control.rotateIndex];
        control.innerHTML = displayText;
     }
     
     control.opCount = 0;
     
     control.opInterval = setInterval(function()
     {
        control.opCount = control.opCount + 1;
           
        var nowOp = control.opCount/10;
        var nowFilter = control.opCount*10;
        nowFilter = "alpha(opacity=" + nowFilter.toString() + ")";
        
        if(nowOp > 1)
        {
             clearInterval(control.opInterval);
             control.opCount = 10;
             
             setTimeout(function()
             {  
                control.opInterval = setInterval(function()
                {
                   control.opCount = control.opCount - 1;
                   
                   var nowOp = control.opCount/10;
                   var nowFilter = control.opCount*10;
                    
                   nowFilter = "alpha(opacity=" + nowFilter.toString() + ")";
                   
                   if(nowOp < 0)
                   {
                        clearInterval(control.opInterval);
                   
                        control.rotateIndex = control.rotateIndex + 1;
                        
                        if(control.rotateIndex >= rotationText.length)
                           control.rotateIndex = 0;
                           
                        var displayText = rotationText[control.rotateIndex];
                        control.innerHTML = displayText;
                           
                        rotate(pkg);
                   }
                   else
                   {
                      control.setStyle({opacity:nowOp, filter:nowFilter});
                   }
                   
                }, 100);
             
                
             }, 
             pkg.timeout);
        }
        else
        {
           control.setStyle({opacity:nowOp, filter:nowFilter});
        }
     }.bind(this), 150);
}

//////////////////////////////////////////////////
//  Search Box Ajax functions
//////////////////////////////////////////////////
function GetSearchResult(term, resultBoxId, searchMethod)
{
  var target = $(resultBoxId);
  
  if(term.length > 1)
  {
	  Dlink_New_Site.WS.MasterProcesses.Search(term, searchMethod,
	  function(result) // succeeded
	  {
		  target.innerHTML = result; 
		  target.scrollTop = 0;
	         
		  if(!target.hasClassName('on') && result.length > 0)
		  {
			  classSwitch(target, 'on', 'off');
		  }
		  else if(result.length == 0)
		  {
			  classSwitch(target, 'off', 'on');			  
		  }                              
	  }.bind(this));
  }
}

function searchboxStateChange(searchBox, resultBoxId, searchMethod)
{
   searchBox = $(searchBox);
   if(searchBox.beforeValue != null)
   {
      if(searchBox.beforeValue == searchBox.value)
         return;
   }
   
   var currentDate = new Date();
   var currentTime = currentDate.getTime();
   var interval = 0;
   
   if(typeof(searchBox.lastTime) != 'undefined' && searchBox.lastTime != null)
   {
      interval = Math.ceil(currentTime-searchBox.lastTime);
   }
   else
   {
      searchBox.lastTime = currentTime;
   }
   
	var resultBox = $(resultBoxId);
	if(searchBox.value.length < 2)
	{    
		if(!resultBox.hasClassName('off'))  
			classSwitch(resultBox, 'off', 'on');
		resultBox.innerHtml = '';
	}
	else // if there are more than 1 char
	{
	   // if the value stays the same after 1 sec, get result or
		// if the interval between each char typed is >= 1 sec
	   if(interval >= 1000)
	   {
	      GetSearchResult(searchBox.value, resultBoxId, searchMethod);
		   searchBox.lastTime = currentDate.getTime();
	   }
	   else
	   {
	      // get search term before time out
	      var currentVal = searchBox.value;
	      setTimeout(function()
			{
			   // compare terms between 1 sec timeout, if the same,
			   // means it's stopped for at least 1 sec
				if(currentVal == searchBox.value)
				{
					GetSearchResult(searchBox.value, resultBoxId, searchMethod);
					searchBox.lastTime = currentDate.getTime();
				}
			}.bind(this), 1000);
	   }
	}
}

// change search result item state on the list when mouse is hovered over
function searchMouseHover(searchItem)
{
   searchItem = $(searchItem);
   searchItem.siblings().each(function(sibling)
   {   
      $(sibling).removeClassName('selected');
   });
   searchItem.addClassName('selected');
}

// check if the user key in numbers
function isNumberKey(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return true;
}

// make dynamic data be able to perform actions
function FrameUrl(element)
{
   $j(document).ready(function()
   { 
      var url = $j(element).attr("rel");
      
      // kb tracking for search box
      if($j(element).hasClass("support-read"))
      {
         if(typeof(url) != 'undefined' && url.length > 0)
         {
            pageTracker._trackPageview(url);
         }
      }
      
		ContentOverlay.ShowProductSelector(url);
		return false;
   });
}

function LoadProductInterruption(url)
{
   if(swfobject.hasFlashPlayerVersion("9.0.0"))
   {
		$j(document).ready(function()
		{
			var productContentBody = $j("div.generalContentBody");
			if(productContentBody.length > 0)
			{
				var contentBody = $j("#contentBody");
	         
				if(contentBody.length > 0)
				{
					contentBody.prepend("<div id=\"productInterruption\"><div id=\"interruptionContent\"></div><div style=\"position:absolute;right:0px;top:0px;z-index:10;\"><a onclick=\"CloseProductInterruption('div.generalContentBody', '#productInterruption');\" href=\"javascript:void(0);\">Proceed to product information >></a></div></div>");
					var interruption = $j("#productInterruption");
					if(interruption.length > 0)
					{
						interruption.css({width:"930px",height:"410px",border:"solid 0px black",position:"absolute",left:"10px",display:"none","padding-top":"15px"});
						generateCommonFlash("interruptionContent", "http://images.dlink.com/new/products/dir-685/interruptad.swf", 930, 412, null, null);
					}
					
					interruption.fadeIn(500);	                  
				}
			}
		});
   }
}

function CloseProductInterruption(productContentBodyId, interruptContentId)
{
   var productBody = $j(productContentBodyId);
   var interrputContent = $j(interruptContentId);
   
   interrputContent.fadeOut(500,function()
   {
      $j("#contentBody").remove("#productInterruption");
      productBody.fadeIn(500);
   });
}

///////////////////////////////////////////////////////////
/// dlinkshop json call for product
///////////////////////////////////////////////////////////
function AsyncLoadShop(url)
{
   $j(document).ready(function()
   {
       $j.getScript(url,null,function(data)
       {
          $j("#contentBody").append("<script type=\"text/javascript\">" + data + "<//script>");
       });
   });
}
function DlinkShopProduct(result)
{
   var inStock = result.stockStatus;
   var buyLink = result.buyLink;
   var buyHref = null;
   var shortDesc = result.shortDescription;
   var price = result.price;
   var unitPrice = null;
   var pid = result.productID;
   
   if(typeof(buyLink) != 'undefined') // found
   {
      //buyHref = buyLink.href;
      buyHref = "http://www.dlinkshop.com/store/dlink/en_US/buy&productID=" + pid;
   }
   
   if(typeof(price) != 'undefined')
   {
      unitPrice = price.unitPrice;
   }
   
   // in stock or backorder
   inStock = true;
   
   var product = {price:unitPrice,href:buyHref,instock:inStock};
   return product;
}
function OnRegularPriceSucceed(result)
{
   var product = DlinkShopProduct(result);
   
   if(product.instock)
   {
      SetDlinkShopPrice(product);
   }
}
function OnRefurbPriceSucceed(result)
{
   var product = DlinkShopProduct(result);
   
   if(product.instock)
   {
      SetDlinkShopRefurbPrice(product);
   }
}
function SetDlinkShopPrice(product)
{
   $j(document).ready(function()
   {
		try
		{
		   var price = product.price;
		   var buylink = product.href;
		   $j("#resource2").prepend("<a id=\"addToCart\" class=\"btm-resource\" href=\"" + buylink + "\"><span class=\"regular-price\" style=\"line-height:normal;\">" + price + "</span><br/>Add to Cart</a>");
		}
		catch(e) {}
   });
}
function SetDlinkShopRefurbPrice(product)
{
   $j(document).ready(function()
   {
      try
		{
			var price = product.price;
			var buylink = product.href;
			$j("#addToCart").after("<a class=\"extra-link\" href=\"" + buylink + "\"><span class=\"refurb-price\">" + price + "</span><br/>Refurbished</a>");
		}
		catch(e) {}
   });
}

// show pref page options
function ShowHpPreferenceOptions()
{
	$j(document).ready(function()
   {
      var containerHt = $j("#containerBody").height();
      var containerWd = $j("#containerBody").width();
      var topNavHt = $j("#defaultTopNavWrapper").css("height");
      
      if($j("#entry-overlay-body,#entry-overlay-content").length == 0)
      {
         // 2 layers
      
			$j("#mainHome").append("<div id=\"entry-overlay-body\"></div>");
			$j("body").append("<div id=\"entry-overlay-content\"></div>");
			$j("#header").css({"z-index":274});
			
			$j("#entry-overlay-content,#entry-overlay-body").css({position:"absolute","z-index":274,top:0,left:0,height:"100%",width:"100%",display:"none","background-color":"white"}).fadeTo(10, 0.33, function()
			{
				$j(this).fadeIn("slow",function()
				{
					var panel = $j("#hpSetting");
					var pWd = panel.width();
					var pHt = panel.height();
					var mLeft = Math.ceil(containerWd/2 - pWd/2);
					var mTop = Math.ceil(containerHt/2 - pHt/2);
	            
					$j("#hpSetting").css({margin:mTop + "px 0px 0px " + mLeft + "px"}).fadeIn(600);
				});
			});      
      }
      else
      {
         $j("#entry-overlay-body,#entry-overlay-content").fadeIn("slow", function()
         {
            $j("#hpSetting").fadeIn(600);
         });
      }
      return false;
   });
}

// make search result list accessible from keyboard with up & down & enter
function keyboardDown(e, resultId)
{
   var keynum;
   var result = $(resultId);
   var isSelected = false;
   var resultList = result.down(0); // ul
   var tb = Event.element(e);
   
   if(result == null)
      return;

   // get keycode for different browser
   if(window.event) // IE
   {
      keynum = e.keyCode;
   }
   else if(e.which) // Netscape/Firefox/Opera
   {
      keynum = e.which;
   }
   
   
   if(keynum == 40 && result != null && result.hasClassName('on')) // key arrow down
   { 
      resultList.childElements().each(function(element, index)
      {
         if($(element).hasClassName('selected'))
         {				    
            if(index < resultList.childElements().length - 1)
            {
               $(element).removeClassName('selected');
               $(element).next(0).addClassName('selected');               
            }
            
            result.scrollTop = result.scrollTop + 16;
            
            isSelected = true;
            throw $break;
         }
      });
      
      if(!isSelected)
         resultList.down(0).addClassName('selected');
   }
   else if(keynum == 38 && result != null && result.hasClassName('on')) // key arrow up
   {
      resultList.childElements().each(function(element, index)
      {
         if($(element).hasClassName('selected'))
         {
            if(index > 0)
            {
               $(element).removeClassName('selected');
               $(element).previous(0).addClassName('selected');
            }
            else
            {
               $(element).removeClassName('selected');
            }
            
            if(result.scrollTop >= 16)
            {
               result.scrollTop = result.scrollTop - 16;
            }
            else if(result.scrollTop > 0 && result.scrollTop < 16)
            {
               result.scrollTop = 0;
            }
            
            isSelected = true;
            throw $break;
         }
      });
      
      if(!isSelected)
         resultList.up(0).addClassName('selected');
   }
}
//////////////////////////////////////////////////
//  Product Selector functions
//////////////////////////////////////////////////
var ContentOverlay =
{
   overlaySection: "#contentOverlaySection",
   Open: function() 
   {
      $j(this.overlaySection).show(500, function()
      {
         var illustration = $j("div.categoryIllustration");
         
         if(illustration.length > 0 && typeof(illustration.css("background")) != 'undefined')
            illustration.hide();
      });
   },
   Close: function() 
   {
      var overlaySec = this.overlaySection;
      var illustration = $j("div.categoryIllustration");
      if(illustration.length > 0 && illustration.css("display") != 'block')
      {
         illustration.show(10, function()
         {
            $j(overlaySec).hide(500);
         });
      }
      else
      {
         $j(overlaySec).hide(500);
      }

      // make frame url empty
      this.ShowProductSelector(null);
   },
   HideSiblings: function(sectionId)
   {
      var sec = $j("#" + sectionId);
      sec.siblings(":not(a)").hide();
      sec.show();
   },
   ShowProductSelector: function(url)
   {
      if(url != null && url.length > 0)
      {
         this.Open();
      }
      
      if(url == null)
         url = '';
         
      if($j("#productSelectorSection").length > 0)
      {
			this.HideSiblings("productSelectorSection");
			$j("#productSelectorFrame").attr("src", url);
      }
   },
   ShowProductFAQ: function(sectionId, faqId)
   {
      if($j("#" + faqId).length > 0)
      {
         this.Open();
         this.HideSiblings(sectionId);
         this.HideSiblings(faqId);
         $j("#" + faqId).slideDown(300);
      }
   },
   ShowGeneralSection: function(sectionId)
   {
      this.Open();
      this.HideSiblings(sectionId);
   }
};

//----------- pop up for retailer map ----------
function popup(width,height,url,name)
{
   window.open(url,name,"width=" + width + ",height=" + height + ",toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1");
}

function mapPopup(url)
{
   popup(900,520,url,"Map");
}

//======================= support page pop up 
// no delay
function doPopup(url) 
{
   url = "/support/" + url;
   popup(300,300,url,"DlinkReg");
}

// don't put the whole path, just the value, e.g. pid
function valueUrlEncode(url)
{
   var reserved = new Array("$", "&", "+", ",", "/", ":", ";", "=", "?", "@");
   var coded = new Array("%24", "%26", "%2b", "%2c", "%2f", "%3a", "%3b", "%3d", "%3f", "%40");
   
   for(var i = 0; i < reserved.length; i++)
   {
      url = url.replace(reserved[i], coded[i]);
   }
   return unescape(url);
}

// End DLink.js
//////////////////////////////////////////////////
// -->
