var TheFlip = function () {
    
    return {
        
        culture: undefined,
        siteType: undefined,

        settings: {}
        
    };
} ();


TheFlip.RegionSelector = function () {

    var regionSelectorSpecialPagesForStore = ["promos/freeshipping.aspx", "designs/faq.aspx", "support/faq.aspx"];
    var regionSelectorSpecialPagesForWww = ["terms.aspx", "support/warranty.aspx", "support/"];

    return {

        initRegionSelector: function () {
            if (document.getElementById('regionSelector')) {
                var div = document.getElementById('regionSelector').getElementsByTagName('div');
                for (i = 0; i < div.length; i++) {
                    div[i].onmouseover = function () {
                        this.className = 'menuItem over';
                    }
                    div[i].onmouseout = function () {
                        this.className = 'menuItem out';
                    }
                }
            }
        },


        // Navigates to a culture-selected homepage.
        // Some pages are considered as exception and navigats to a culture-specific version of current page (FAQ, Terms and Condition, Contact Us...)
        regionSelected: function (culture, redirectPatternUrl) {

            var redirectUrl = redirectPatternUrl;

            var docLocation = document.location;
            var relativePath = docLocation.pathname.toLowerCase();

            var fullRelativePathWithoutCulture = relativePath.replace(/^\/en-us|^\/en-gb|^\/en-ca|^\/fr-ca|^\/fr-fr|^\/de-de|^\/ar-me|^\/en-me|^\/en-au|^\/es-es|^\/nl-nl|^\/en-nz/i, "");
            fullRelativePathWithoutCulture = fullRelativePathWithoutCulture.replace(/^\//i, "");

            if ((relativePath.indexOf('default-fr-ca.aspx') != -1) && (culture != 'en-ca')) {
                fullRelativePathWithoutCulture = 'support/';
            }
            if ((relativePath.indexOf('warranty-fr-ca.aspx') != -1) && (culture != 'en-ca')) {
                fullRelativePathWithoutCulture = 'support/warranty.aspx';
            }

            redirectUrl = redirectUrl.replace("{FullRelativePathWithoutCulture}", fullRelativePathWithoutCulture);
            redirectUrl = redirectUrl.replace("{SelectedCulture}", culture);

            var destinationCulture = redirectUrl.substring(1, 6);

            try {
                set_cookie('region', destinationCulture, 30, '/', '.theflip.com', '');
            }
            catch (err) { };

            this.performRedirect(destinationCulture, redirectUrl);

            if (relativePath.indexOf('ar-me') > 0) {
                $('#regionSelectorBtn a').attr('dir', 'rtl');
            } else {
                $('#regionSelectorBtn a').attr('dir', '');
            }
        },



        // Navigates either to corresponding page (specified in redirectUrl) or to culture-selected homepage
        performRedirect: function (culture, redirectUrl) {
            var specialPages = null;
            if (TheFlip.siteType == "store") {
                specialPages = regionSelectorSpecialPagesForStore;
            }
            else if (TheFlip.siteType == "marketing") {
                specialPages = regionSelectorSpecialPagesForWww;
            }

            var navigateToSelectedCultureHomePage = true;
            if (specialPages) {
                for (var specialPageIndex in specialPages) {
                    var specialPage = specialPages[specialPageIndex];
                    if (redirectUrl.toLowerCase().indexOf(specialPage.toLowerCase()) >= 0) {
                        navigateToSelectedCultureHomePage = false;
                        break;
                    }
                }
            }

            document.location = (navigateToSelectedCultureHomePage) ? "/" + culture + "/" : redirectUrl;
        }

    };
} ();

function openSubNav(obj) {
    if (child = obj.getElementsByTagName("ul")[0]) child.style.display = "block";
}

function closeSubNav(obj) {
    if (child = obj.getElementsByTagName("ul")[0]) child.style.display = "none";
}

function initializeNav() {
    if (document.getElementById("nav")) {
		for( var i=0; (li = document.getElementById("nav").getElementsByTagName("li")[i]); i++ ){
				if ( li.getElementsByTagName("ul") ){
					li.onmouseover = function(){ openSubNav(this); }
					li.onmouseout = function(){ closeSubNav(this); }
			}
		}
	}

    var section = getActiveSection();

	if( section && document.getElementById("nav_"+section) )
		document.getElementById("nav_"+section).getElementsByTagName("a")[0].className = "selected";
}

function getActiveSection() {
	var urlPathName = window.top.location.pathname; // example: /en-us/buy/
	var activeTabRegexRules = 
	  {
        "home": [ /^\/[^\/]+\/?$/i ],
        "products": [ /^\/[^\/]+\/products/i ],
        "buy": [ /^\/[^\/]+\/buy/i , /store/i ],
        "buzz": [ /^\/[^\/]+\/buzz/i ],
        "support": [ /^\/[^\/]+\/support/i, /app/i, /cgi-bin/i ]
    };
    for (var section in activeTabRegexRules) {

        for (var regExRuleIndex in activeTabRegexRules[section]) {
            var regExRule = activeTabRegexRules[section][regExRuleIndex];
            if (urlPathName.match(regExRule)) return section;
        }
    }
    return null;
}









function getWindowHeight() {
    var windowHeight = 0;
    if (typeof (window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
    }
    else {
        if (document.documentElement && document.documentElement.clientHeight) {
            windowHeight = document.documentElement.clientHeight;
        }
    }
    return windowHeight;
}

function hideMenu(menuId) {
	document.getElementById(menuId).style.top = '-100000px';
	document.getElementById('regionContainer').style.overflow = 'hidden';
	document.getElementById(menuId).style.display = 'none';
}
  function clearCallIn(menuId) {
	  var codeString = 'window.clearTimeout(timeoutId' + menuId + ')';
	  document.getElementById('regionContainer').style.overflow = 'visible';
	  eval(codeString);  
  }
  function callIn(menuId) {
	var codeString = 'window.timeoutId' +menuId + ' = setTimeout("hideMenu(\''+menuId+'\')",1000)';
	eval(codeString);
  }
  function showMenu(menuId) {
      if (document.getElementById) {
          var windowHeight = getWindowHeight();
          if (windowHeight > 0) {
              var contentHeight = document.getElementById('mainContent').offsetHeight;
              if (TheFlip.siteType == "store") {
                  document.getElementById(menuId).style.top = 97 + 'px';
              } else {
                  document.getElementById(menuId).style.top = -47 + 'px';
                  //document.getElementById(menuId).style.top = 1 + 'px';
              }
              document.getElementById(menuId).style.display = 'block';
			  document.getElementById('regionContainer').style.overflow = 'visible';
          }
      }
	  timeOutName = eval('window.timeoutId'+menuId);
	  if (timeOutName) {
		  clearCallIn(menuId);
	  }
  }
  function pageTrackerEvent(arg1, arg2, arg3, arg4) {
      if (window.pageTracker) pageTracker._trackEvent(arg1, arg2, arg3, arg4);
  }

  function trackAtlas(id) {
      var prtcol = (("https:" == document.location.protocol) ? "https://" : "http://");
      var str = '<iframe src="' + prtcol + 'view.atdmt.com/iaction/' + id + '" width="1" height="1" frameborder="0" scrolling="No" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0"></iframe>';
      document.getElementById("spotlight_target").innerHTML = str;
      return true
  }

  function initializeShoppingBag(culture, storeUrl, cartUrl) {
      var shoppingBagLink = $("#shoppingBagImageLink");
      var numberOfItems = getNumberOfItemsInShoppingCart(culture);
      shoppingBagLink.text(numberOfItems);
      var shoppingBagUrl = (numberOfItems != null && numberOfItems.length > 0) ? cartUrl : storeUrl;
      shoppingBagLink.attr("href", shoppingBagUrl);
      $("#shoppingBagTextLink").attr("href", shoppingBagUrl);
  }

  function getNumberOfItemsInShoppingCart(culture) {

      var numberOfItems = getCookie("ITEMS_" + culture);
      if (numberOfItems == "0") return "";
      if (null != numberOfItems && numberOfItems.length >= 3) return "99+";
      return numberOfItems;
  }


  function getCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
          var c = ca[i];
          while (c.charAt(0) == ' ') c = c.substring(1, c.length);
          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
      }
      return null;
  }
