 /**
 * @depends prototype.js
 * @depends effects.js
 * @depends g-ext.js
 */

// getCookie added for redirect functionality

function getCookie (name) {
  name = name + '=';
  var value;
  var cookies = document.cookie.split(';');
  cookies.each(function(cookie) {
    while (cookie.charAt(0) == ' ')
      cookie = cookie.substring(1, cookie.length);

    if (cookie.indexOf(name) == 0) {
      value = cookie.substring(name.length, cookie.length);
      throw $break;
    }
  });
  return value;
};

/* added for free shipping functionality */
function setCookie (name, value) {
	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) + "; path=/";
};
 
/* added for free shipping functionality */
function setCookie (name, value) {
	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) + "; path=/";
};


// check if cookies are enabled for the browser,
// would rather do this in ASP but
//server side assumes they are always enabled
(function checkSiteCookie() {
  setCookie("test","site");
  if(getCookie("test") == null || getCookie("test") != "site")
   document.location = "/enable_cookies.html";
  else {
   var urlSite = location.href.split('/')[3];
   if((getCookie("site") == null) || (urlSite==null) || (decodeURI(getCookie("site").toLowerCase())!=urlSite.toLowerCase())) {
     var d = location.href;
     d = d.replace("#", "%23");
     document.location = d.replace("/"+urlSite+"/", "/guccicampaign.asp?page="+"/"+urlSite+"/");
   }
  }
})();

var Menu = {
  
  MAIN_MENU: 0,
  SUB_MENU: 1,
  PAGE_MENU: 2,
  
  initialize: function(id){
    this.id                = id;
    this.locale            = 'de';
    this._animation        = false;
    this.currentMenuPanel  = 0;
    this._defaultMenuPanel = 0;
    this.MENU_TIMEOUT      = 1000;
    this._menuPanelTimeout = null;
    this._activeSubMenu    = -1;
    
    // Searching for menu elements
    this.menus = $$('#menu-left, #menu-right');
    if(this.menus.length == 0) return;
    
    // Collect main menu containers, hiding them
    this.menuContainers = $$('#menu-left div.main, #menu-right div.main').invoke('hide');
    this.parse();
    
    this.menus.each(function(menu){
      menu.observe('mouseout',this.startPanelTimeout.bindAsEventListener(this));
      menu.observe('mousemove',this.clearPanelTimeout.bindAsEventListener(this));
      menu.delegate('click', {
        'a.submenu': function(event) {
          /* Navigating to sub menus */
          event.stop();
          Menu.openSubmenu(event.element().readAttribute('rel'));
        },
        'a.menusubmenu': function(event){
          /* Allow switching to shopping submenu directly from another submenu by a mouse click */
          event.stop();
          Menu.changeSubmenu(event.element().readAttribute('rel'));
        },
        'a.level-up-link': function(event){
          /* Level up link */
          event.stop();
          Menu.showMenuPanel(0);
        }
      });
    }.bind(this));
    
    if(!Object.isUndefined(arguments[1])) {
      this._defaultMenuPanel = arguments[1];
      if(this._activeSubMenu > -1 && this._defaultMenuPanel == this.SUB_MENU) {
        Menu.openSubmenu(Menu._activeSubMenu, {animation:false});
      } else {
        Menu.showMenuPanel(arguments[1], {animation:false});
      }
    }
    
    // Defer showing main menu to avoid flickering effect
    (function(){
      this.menuContainers.invoke('show');
    }.bind(this)).defer();

	this.addLinks();
  },
  
  startPanelTimeout: function(event){
    var p = Event.localPointer(event, event.findElement('.menu'));
    if(p[0]>0 && p[0]<236 && p[1]>0 && p[1]<504) return;
    
    this.clearPanelTimeout();
    this._menuPanelTimeout = setTimeout(function(){
      if(Menu._changedSubmenu) {
		if (Menu._defaultMenuPanel != Menu._activeSubMenu && Menu.currentMenuPanel == Menu.SUB_MENU && Menu._activeSubMenu != -1)
	    	Menu.changeSubmenu(Menu._activeSubMenu);
		else
			Menu.changeSubmenu(Menu._defaultMenuPanel);
	  }
      else {
        if (Menu.currentMenuPanel == Menu.SUB_MENU && Menu._activeSubMenu!=-1)
          Menu.openSubmenu(Menu._activeSubMenu, {animation:false});
        else
          Menu.showMenuPanel(Menu._defaultMenuPanel, { restore: true });
      }
    }, Menu.MENU_TIMEOUT);
  },
  clearPanelTimeout: function(){
    if(this._menuPanelTimeout) {
      clearTimeout(this._menuPanelTimeout);
      this._menuPanelTimeout = null;
    }
  },
  addLinks: function() {
		
		if (typeof phoneassistance != 'undefined' && phoneassistance && $('links') != null && Menu.id != 'homepage') {
			var linkul = $('links');

	  		var phoneelement = document.createElement('li');
	  		var phonelink = document.createElement('a');
	  		var phonetext = document.createTextNode('877.482.2430');

	  		phonelink.setAttribute("href",'/'+getCookie('site')+'/'+getCookie('language')+'/'+getCookie('site')+'/'+'about-gucci/legal-notices/assistance.html');

			phonelink.appendChild(phonetext);
	  		phoneelement.appendChild(phonelink);
	  		linkul.insertBefore(phoneelement,$$('#links li')[0]); 
		}
		
		if (typeof freeshipping != 'undefined' && freeshipping && $('links') != null) {
			var linkul = $('links');

	  		var freeshipelement = document.createElement('li');
	  		var freeshiplink = document.createElement('a');
	  		var freeshiptext = document.createTextNode(Gucci.getTerm('free shipping'));

	  		freeshiplink.setAttribute("href","#");
	  		freeshiplink.onclick = function() {Gucci.openPopup('/'+getCookie('site')+'/'+getCookie('language')+'/'+getCookie('site')+'/'+'popup_freeshipping.shtml'); return false;};

	  		freeshiplink.appendChild(freeshiptext);
	  		freeshipelement.appendChild(freeshiplink);
	  		linkul.insertBefore(freeshipelement,$$('#links li')[0]);
		}
		
		if (typeof giftcardpromo != 'undefined' && giftcardpromo && $('links') != null && Menu.id != 'homepage') {
			var linkul = $('links');

	  		var giftcardelement = document.createElement('li');
	  		var giftcardlink = document.createElement('a');
	  		var giftcardtext = document.createTextNode('gift card');

	  		giftcardlink.setAttribute("href",'/'+getCookie('site')+'/'+getCookie('language')+'/'+getCookie('site')+'/gift-card/');

			giftcardlink.appendChild(giftcardtext);
	  		giftcardelement.appendChild(giftcardlink);
	  		linkul.insertBefore(giftcardelement,$$('#links li')[0]); 
		}
		
		if (Engine.isMSIE8 && typeof ie8warning != 'undefined' && ie8warning && $('links') != null) {
			var linkul = $('links');
			
			var ie8element = document.createElement('li');
	  		var ie8link = document.createElement('a');
	  		var ie8text = document.createTextNode('problem viewing images?');
			
			ie8link.setAttribute("href","#");
	  		ie8link.onclick = function() {Gucci.openPopup('/'+getCookie('site')+'/'+getCookie('language')+'/'+getCookie('site')+'/'+'popup_ie8fix.shtml'); return false;};

	  		ie8link.appendChild(ie8text);
	  		ie8element.appendChild(ie8link);
	  		linkul.insertBefore(freeshipelement,$$('#links li')[0]);
		}
  },
  parse: function(){
    function _renderBlock(block){
      var html = '';
      if(block.item) block.item.each(function(item){
        html += _renderItem(item);
      });
      
      if(block.list) block.list.each(function(list){
        html += _renderList(list);
      });
      
      return html;
    };
    
    function _renderList(list){
      var html = '';
      if(list.item) list.item.each(function(item){
        html += _renderItem(item);
      });
      if(list.submenu) list.submenu.each(function(submenu){
        html += _renderSubmenu(submenu);
      });
      
      return html;
    };
    
    function _renderItem(item, subklass){
      var klass = item.klass || '';
      
      if(Menu.id == item.id) {
        Menu._activeSubMenu = currentSubmenu;
        klass = klass + ' active';
      }
      
      if(!klass.include('menuspacer')) {
        if(klass.include('menusubmenu') || klass.include('menuheader'))
          href = '#';
        else
          href = (item.secure ? "https://" : 'http://') + location.host + item.url;
        
        if(!klass.include('menuheader') && subklass && !item.klass)
          klass = klass + ' ' + subklass;
        
        rel = (klass.include('menusubmenu') ? item.url.toString() : '');
        text = item.name.gsub(/\n/,'<br/>').gsub(/\s/,'&nbsp;');
        
        linkTag = '<a href="' + href + '" class="' + klass.strip() + '" rel="' + rel + '" name="' + text + '">' + text + '</a>';
        return '<p class="' + ((item.pklass) ? item.pklass : '') + '">' + linkTag + '</p>';
        
      } else return '<p>&nbsp;</p>';
    };
    
    function _renderSubmenu(submenu){
      currentSubmenu++;
      
      var klass = 'submenu ' + submenu.klass || '';
      var pklass = submenu.pklass || '';
      
      var wrapper = '<p class="' + pklass + '"><a href="#" class="' + klass + '" rel="' + currentSubmenu.toString() + '" name="' + submenu.name.gsub(/\n/,'') + '">' + submenu.name.gsub(/\n/,'<br/>') + '</a></p>';
      
      Menu._subMenus.push('');
      Menu._subMenus[currentSubmenu] = [];
      if(submenu.item){
        submenu.item.each(function(itemInstance){
          Menu._subMenus[currentSubmenu].push(_renderItem(itemInstance, submenu.subklass));
        });
      };
      return wrapper;
    };
    
    var currentSubmenu = -1;
    Menu._subMenus  = [];
    // Injecting HTML into DOM
    Menu.menuContainers.invoke('insert', Menu.items.block.map(_renderBlock).join('<br/>'));
  },
  openSubmenu: function(submenu, options){
    if(Menu._animation) return;

    var submenuHTML = Menu._subMenus[submenu].join('') + '<p class="level-up"><a href="#" class="level-up-link">' + Menu.items.term.main + '</a></p>';
    Menu.menus.each(function(menu){
      menu.down('div.submenu').update(submenuHTML);
    });
    Menu.showMenuPanel(1, options);
  },
  
  /* Switches from one submenu to another submenu without pointing to main menu */
  /* Uses for quick access to the Shop submenu */
  changeSubmenu: function(submenu){
    if(Menu._animation) return;
    
    Menu._changedSubmenu = Menu._changedSubmenu ? false : true; // Toggling _changedSubmenu
    
    Menu.menus.each(function(menu){
      var subemenu_element = menu.down('div.submenu');
      if(subemenu_element){
        subemenu_element.fade({
          duration: 0.4,
          afterFinish: function() {
            Menu.openSubmenu(submenu);
            subemenu_element.appear({duration: 0.4});
          }
        });
      }
    });
  },
  showMenuPanel: function(panel, options){
    if(Menu._animation) return;
    Menu._animation = true;
    var options =  Object.extend({
       animation: true,
       restore:   false,
       custom:    false
    }, arguments[1] || {});
    
    var fxs = $A([
      Menu.menus[0] ? new Effect.Morph(Menu.menus[0].down('div.scroll'), { style: {left: -(Menu.menus[0].getWidth() * panel) + 'px'}, sync: true }) : null,
      Menu.menus[1] ? new Effect.Morph(Menu.menus[1].down('div.scroll'), { style: {right: -(Menu.menus[0].getWidth() * panel) + 'px'}, sync: true }) : null
    ]).compact();
    
    new Effect.Parallel(fxs, {
      transition: options.animation ? Effect.Transitions.cubic : Effect.Transitions.full,
      duration: 0.6,
      afterFinish: function(fx){
        Menu.currentMenuPanel = panel;
        Menu._animation = false;
      }
    });
  },
  positionOverlay: function(){
	var overlay = $('overlay_panel');
	if (!overlay) return;

	var targetleft;
	var panelwidth = overlay.getWidth();

	if ((document.viewport.getWidth()/2) <= (panelwidth/2))
		targetleft = 0;
	else {
		if (Engine.isMSIE)
			targetleft = (document.viewport.getWidth()/2) - (panelwidth/2) - $('layout').cumulativeOffset()[0];
		else
			targetleft = (document.viewport.getWidth()/2) - (panelwidth/2);
	}	
	var scrollOffsets = document.viewport.getScrollOffsets();
	targetleft += scrollOffsets.left;

	overlay.setStyle({left:targetleft + 'px'});
  },
  showOverlay: function(){
	var content = $('content');

	if (Object.isElement($('overlay_screen')) || typeof content == 'undefined')
		return false;	

	var overlayscreen = new Element('div',{'id': 'overlay_screen'});
	if (document.viewport.getWidth() > content.getWidth())
		overlayscreen.setStyle({width:document.viewport.getWidth() + 'px'});
	else
		overlayscreen.setStyle({width:content.getWidth() + 'px'});	

	var overlay = new Element('div',{'id': 'overlay_panel'});

	var targetleft;
	var panelwidth = 420;

	if ((document.viewport.getWidth()/2) <= (panelwidth/2))
		targetleft = 0;
	else {
		if (Engine.isMSIE)
			targetleft = (document.viewport.getWidth()/2) - (panelwidth/2) - $('content').cumulativeOffset()[0];
		else
			targetleft = (document.viewport.getWidth()/2) - (panelwidth/2);
	}
	overlay.setStyle({left:targetleft + 'px'});
	overlay.setStyle({top:parseInt((Position.getPageSize().window.height - 504)/2) + 'px'});

	Event.observe(window,'scroll',this.positionOverlay);
	if (Engine.isMSIE){
		$('content').appendChild(overlayscreen);
		$('content').appendChild(overlay);
		overlayscreen.setStyle({height: document.viewport.getHeight() + 'px'});	
		overlayscreen.setStyle({top:-$('content').cumulativeOffset()[1] + 'px'});	
		overlayscreen.setStyle({left:-$('content').cumulativeOffset()[0] + 'px'});	
	}
	else {
		$$('body')[0].appendChild(overlayscreen);
		$$('body')[0].appendChild(overlay);
	}
	overlayscreen.appear({duration: 1.5, from: 0, to: 0.7});
	overlay.appear({duration: 1.5, from: 0, to: 0.95});
	
	// kill force overlay cookie immediately
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime()-1000);
	document.cookie = "forceCountryRedirectOverlay=''; expires=" + expire.toGMTString() + "; path=/";
	document.cookie = "forceCountryRedirectDefaultSite=''; expires=" + expire.toGMTString() + "; path=/";
	document.cookie = "forceCountryRedirectPromoCode=''; expires=" + expire.toGMTString() + "; path=/";
	
	return overlay;
  },
  showCountryRedirectPanel: function(countrylinks){
		
	var countryoverlay = this.showOverlay();
	if (!countryoverlay)
		return;
	var countryselections = new Element('div',{'id':'coverlay_display'});
	var searchurl;
	Object.values(countrylinks).each(function(e) {
		searchurl = e[0];
		if (e[0].indexOf('#') > -1)
			searchurl = e[0].substring(0,e[0].indexOf('#')-1);
		if (document.location.href.indexOf(searchurl) != -1) {
			var removecode = "Menu.removeOverlay();";
			if (searchurl != e[0])
				removecode += " Shop.goToAndOpen(\'" + e[0]  + "\');";
			if (Engine.isMSIE)
				countryselections.appendChild(new Element('a',{'class': 'country','href':'javascript:' + removecode,'style':'opacity: 0; cursor: pointer;'}).update(e[1]));
			else {
				removecode += " return false;";
				countryselections.appendChild(new Element('a',{'class': 'country','href':'#','onclick':removecode,'style':'opacity: 0; cursor: pointer;'}).update(e[1]));
			}
		}
		else
			countryselections.appendChild(new Element('a',{'class': 'country','href':e[0],'style':'opacity: 0;'}).update(e[1]));
	countryselections.appendChild(new Element('br'));
	});

	setTimeout(function() {
		$$('div#coverlay_display a.country').each(function(e,i) {
		 		setTimeout(function() {
		 		          new Effect.Appear(e);
		 		       }, 100*i);
		});
	}, 1000);

	countryoverlay.appendChild(new Element('p').update('please select a country'));
	countryoverlay.appendChild(countryselections);
  },
  checkOverlay: function(){
	if (document.cookie.indexOf('forceCountryRedirectOverlay=') != -1){

		// set promo references
		var promocode = "";
		if (document.cookie.indexOf('forceCountryRedirectPromoCode=') != -1){
			var tempindex = document.cookie.indexOf('forceCountryRedirectPromoCode=');
			if (document.cookie.indexOf(';',tempindex) < 0)
				promocode = document.cookie.substring(tempindex+30);
			else
				promocode = document.cookie.substring(tempindex+30,document.cookie.indexOf(';',tempindex));
			promocode = promocode.replace(/%2F/g,'/').replace(/%2D/g,'-');
			document.cookie = "forceCountryRedirectPromoCode=''; expires=" + expire.toGMTString() + "; path=/";
			
			var exdate = new Date();
			exdate.setDate(exdate.getDate()+30);
			document.cookie= "promotion=" + escape(promocode) + "; expires="+exdate.toGMTString(); + "; path=/"; 
		}

		var ccookies = new Array();
		ccookies[0] = ['forceCountryRedirectat','at','austria'];
		ccookies[1] = ['forceCountryRedirectbe','be','belgium'];
		ccookies[2] = ['forceCountryRedirectca%2Den','caen','canada - english'];
		ccookies[3] = ['forceCountryRedirectcn','cn','中国 - 简体'];
		ccookies[4] = ['forceCountryRedirectcn%2Den','cnen','china - english'];
		ccookies[5] = ['forceCountryRedirectch','ch','switzerland'];
		ccookies[6] = ['forceCountryRedirectde','de','germany'];
		ccookies[7] = ['forceCountryRedirectfr','fr','france'];
		ccookies[8] = ['forceCountryRedirectie','ie','ireland'];
		ccookies[9] = ['forceCountryRedirectit','it','italy'];
		ccookies[10] = ['forceCountryRedirectjp','jp','japan'];
		ccookies[11] = ['forceCountryRedirectkr','kr','korea'];
		ccookies[12] = ['forceCountryRedirectnl','nl','netherlands'];
		ccookies[13] = ['forceCountryRedirectuk','uk','united kingdom'];
		ccookies[14] = ['forceCountryRedirectus','us','united states'];
		ccookies[15] = ['forceCountryRedirectint','int','all other countries'];

		var clinks = new Object();
		for (var i = 0; i < ccookies.length; i++){
			var tempindex;
			tempindex = document.cookie.indexOf(ccookies[i][0] + '=');
			if (tempindex != -1) {
				var targetlink;
				if (document.cookie.indexOf(';',tempindex) < 0)
					targetlink = document.cookie.substring(tempindex+ccookies[i][0].length+1);
				else
					targetlink = document.cookie.substring(tempindex+ccookies[i][0].length+1,document.cookie.indexOf(';',tempindex));
				targetlink = targetlink.replace(/%2F/g,'/').replace(/%2D/g,'-').replace(/%23/g,'#');
				clinks[ccookies[i][1]] = [targetlink,ccookies[i][2]];
			}
		}	

		this.showCountryRedirectPanel(clinks);
	}
  },
  removeOverlay: function(pageName){
	Event.stopObserving(window,'scroll',$('overlay_panel'));
	$('overlay_screen').fade({duration: 1, afterFinish: function() { $('overlay_screen').remove(); } });
	$('overlay_panel').fade({duration: 0.3, afterFinish: function() { $('overlay_panel').remove(); } });	
	if (typeof startVideo == 'function') {
		startVideo();
	}
  }
};

if(getCookie('language')=='korean'){
  document.write('<link rel="stylesheet" href="/stylesheets/gucci-kr.css" type="text/css" media="screen"/>');
}

if(getCookie('language')=='chinese'){
  document.write('<link rel="stylesheet" href="/stylesheets/gucci-cn.css" type="text/css" media="screen"/>');
}

if(getCookie('language')=='german'){
  document.write('<link rel="stylesheet" href="/stylesheets/gucci-de.css" type="text/css" media="screen"/>');
}

if(getCookie('language')=='japanese'){
  document.write('<link rel="stylesheet" href="/stylesheets/gucci-jp.css" type="text/css" media="screen"/>');		
}
	
Element.observe(document,"dom:loaded", function() { Menu.checkOverlay(); });