// jQuery initialization script
(function($) { 
  $(function() {
    
    $('#smallLovePodsLink').bind('mouseenter',function(){
			$('#smallLovePodsDescr').css('display','block');
		}).click(function(){ return false; });
		$('#smallLovePodsDescr').bind('mouseleave',function(){
			$(this).css('display','none');
		});
	
	});
})(jQuery);



// initialize when the dom have been loaded
document.observe('dom:loaded',function(){
	product = new productHandler();
	bracelet = new productBracelet();

	$$('div.item').each(function(el){
		el.onmouseover  = function(){ this.className = 'active'; }
		el.onmouseout  = function(){  this.className = 'item';  }
	});
	
	// activate country navigation
	countryNavigation.init();
	
	// activate topmenu javascript layer
	menuEffects.init()
	
	// activate searchbutton states
	searchStates.init()
	
	// activate the popup for lovepods search
//	lovePodsSearchPopup();

	//var oLink = $('smallLovePodsLink'), oDescr = $('smallLovePodsDescr');
	//if (oLink && oDescr) {
	//	Event.mouseEnter('smallLovePodsLink',function(){
	//		$('smallLovePodsDescr').show();
	//	});
	//	Event.mouseLeave('smallLovePodsDescr',function(){
	//		$('smallLovePodsDescr').hide();
	//	});
	//}
});

productHandler = Class.create();
productHandler.prototype = {
	overlayActive:false,
	newOverlayActive:false,
	activeOverlay:null,
	initialize:function(){
		var products = $$('.productItem');
		products.each(this.setOverlay.bind(this));
		
		var products = $$('.mMyBraceletBuilds');
		products.each(this.setOverlay.bind(this));
		
		var newProducts = $$('.newProduct');
		newProducts.each(this.setNewOverlay.bind(this));
	},
	setOverlay:function(obj){
		Event.observe(obj,'mouseover',this.showOverlay.bind(this,obj))
		Event.observe(obj,'mouseout',this.hideOverlay.bind(this,obj))
		var infoDiv = document.getElementsByClassName('productInfo', obj);
		if(infoDiv[0]) {
			Event.observe(infoDiv[0],'mouseover',this.setOverlayActive.bind(this,obj))
			Event.observe(infoDiv[0],'mouseout',this.setOverlayDeactive.bind(this,obj))
		}
	},
	showOverlay:function(obj,Event){
		if(!this.newOverlayActive) {
			var infoDiv = obj.getElementsByClassName('productInfo');
			if(infoDiv[0]) {
					infoDiv[0].setStyle({display:'block'});
					this.activeOverlay = infoDiv[0];
			}
		}
	},
	hideOverlay:function(obj,Event){
		if(!this.newOverlayActive) {
			var infoDiv = obj.getElementsByClassName('productInfo');
			if(infoDiv[0]) {
					infoDiv[0].setStyle({display:'none'});
					this.activeOverlay = null;
			}
		}
	},
	setNewOverlay:function(obj){
		Event.observe(obj,'mouseover',this.toggleNewOverlay.bind(this,obj))
		Event.observe(obj,'mouseout',this.toggleNewOverlay.bind(this,obj))
	},
	toggleNewOverlay:function(obj,Event){
		var infoDiv = obj.getElementsByClassName('newProductInfo');
		if(infoDiv[0]) {
			if(infoDiv[0].getStyle('display') == 'none') {
				if(this.activeOverlay) {
					this.activeOverlay.setStyle({display:'none'});
				}
				infoDiv[0].setStyle({display:'block'});
				this.newOverlayActive = true;
			} else if(!this.overlayActive) {
				//Effect.Fade(infoDiv[0], { transition: Effect.Transitions.sinodal });
				infoDiv[0].setStyle({display:'none'});
				this.newOverlayActive = false;
			}
		}
	},
	setOverlayActive:function(obj){
		this.overlayActive = true;
	},
	setOverlayDeactive:function(obj){
		this.overlayActive = false;
	}
}

productBracelet = Class.create();
productBracelet.prototype = {
	overlayActive:false,
	newOverlayActive:false,
	activeOverlay:null,
	initialize:function(){
		var products = $$('.mMyBraceletBuilds');
		products.each(this.setOverlay.bind(this));
	},
	setOverlay:function(obj){
		Event.observe(obj,'mouseover',this.showOverlay.bind(this,obj))
		Event.observe(obj,'mouseout',this.hideOverlay.bind(this,obj))
		var infoDiv = obj.getElementsByClassName('braceletInfo');
		if(infoDiv[0]) {
			Event.observe(infoDiv[0],'mouseover',this.setOverlayActive.bind(this,obj))
			Event.observe(infoDiv[0],'mouseout',this.setOverlayDeactive.bind(this,obj))
		}
	},
	showOverlay:function(obj,Event){
		if(!this.newOverlayActive) {
			var infoDiv = obj.getElementsByClassName('braceletInfo');
			if(infoDiv[0]) {
					infoDiv[0].setStyle({display:'block'});
					this.activeOverlay = infoDiv[0];
					obj.setStyle({
						background: "url(/images/backgrounds/bg_mybracelets.png) repeat-x 0 0",
						border: "2px solid #f3f2ee",
						margin: "8px 0 8px 38px"
					});
			}
		}
	},
	hideOverlay:function(obj,Event){
		if(!this.newOverlayActive) {
			var infoDiv = obj.getElementsByClassName('braceletInfo');
			if(infoDiv[0]) {
					infoDiv[0].setStyle({display:'none'});
					this.activeOverlay = null;
					obj.setStyle({
						background: "transparent",
						border: "none",
						margin: "10px 0 10px 40px"
					});
			}
		}
	},
	setNewOverlay:function(obj){
		Event.observe(obj,'mouseover',this.toggleNewOverlay.bind(this,obj))
		Event.observe(obj,'mouseout',this.toggleNewOverlay.bind(this,obj))
	},
	toggleNewOverlay:function(obj,Event){
		var infoDiv = obj.getElementsByClassName('newbraceletInfo');
		if(infoDiv[0]) {
			if(infoDiv[0].getStyle('display') == 'none') {
				if(this.activeOverlay) {
					this.activeOverlay.setStyle({display:'none'});
				}
				infoDiv[0].setStyle({display:'block'});
				this.newOverlayActive = true;
			} else if(!this.overlayActive) {
				//Effect.Fade(infoDiv[0], { transition: Effect.Transitions.sinodal });
				infoDiv[0].setStyle({display:'none'});
				this.newOverlayActive = false;
			}
		}
	},
	setOverlayActive:function(obj){
		this.overlayActive = true;
	},
	setOverlayDeactive:function(obj){
		this.overlayActive = false;
	}
}







/* topmenu foldout menu with display effects */
var menuBigTimer;
var menuEffects = {
	menuTimer:"", // the timer object - is set through startTimer
	timeout:3000, // the amount of time for the menuTimer - time allowed away from menu
	menuActive:false, // is there a menu activated?
	menuObjectActive:"", // which menu item is the mouse over?
	menuAnimActive:false, // is there an animation running?
	init:function(){ // initialize the entire menu effects
		var oMenu = $("menu");
		if (!oMenu) return;
		
		$$("ul#menu li").each(function(el){ // set the mouseover and mouseout events on every list item in the menu
			Event.observe(el,"mouseover",function(e){
				clearTimeout(menuBigTimer);
				menuEffects.showList(this);
				Event.stop(e);
			});
			Event.observe(el,"mouseout",function(e){
				menuEffects.menuActive = false;
				menuBigTimer = setTimeout("menuEffects.hideList()",menuEffects.timeout);
				Event.stop(e);
			});
		});

		$$("ul#menu ul").each(function(el){ 
			Element.setStyle(el,{
				opacity:0,
				display: "block"
			});
		});
		
		$$("ul#menu div").each(function(el){ // set
			var newDim = el.previous().getDimensions();
			var newRight = newDim["width"];
			
			// if it's level2, then add one px. to the right position
			if (el.previous().hasClassName("level2")){ newRight = (newDim["width"]+1) }
			
			// set the elements position and width correctly
			Element.setStyle(el.previous(),{
				width: newDim["width"] + "px",
				right: "-" + newRight + "px",
				left: "auto"
			});
			
			// set the height of the overlay box
			Element.setStyle(el,{
				height: newDim["height"] + "px",
				width: newDim["width"] + "px",
				display: "none",
				right: "-" + newRight + "px"
			});
		});
		
		var listObjects = [oMenu,oMenu.select("ul")].flatten();
		listObjects.each(function(ul){
			var allWidths = new Array();
			ul.childElements().each(function(li){
				allWidths[allWidths.size()] = li.getDimensions()["width"];
			});
			var highestWidth = allWidths.sort().last();
			if (155 < highestWidth){
				ul.childElements().each(function(li){
					li.setStyle({
						width: highestWidth + "px"
					});
				});
			}
		});
		
		var i = 0;
		$$("ul#menu ul").each(function(el){ // set 
			Element.setStyle(el,{
				display: "none",
				opacity:1
			});
		});
	},
	showList:function(oThis){ // show the submenu for the current list item
		this.menuObjectActive = oThis;
		this.hideSiblingsListNow();
		this.menuActive = true;
		var oList = this.menuObjectActive.getElementsByTagName("ul")[0];

		if (oList){
			if (Element.getStyle(oList,"display") == "none"){ // only start the animation if the element is not already displayed
				if (this.menuAnimActive){
					this.hideSiblingsListNow();
				}
				this.menuAnimActive = true;
				var overlay = oThis.select("div")[(oThis.select("div").length-1)];
				Element.show(overlay);
				Element.show(oList);
								
				var r = Effect.Fade(overlay, {
					duration: 0.5,
					from: 1.0,
					to: 0.0,
					afterFinish:this.afterMenuAnim.bind(this,r)
				});
			}
		}
	},
	hideList:function(){ // start the hide sequence, if we aren't over the menu anymore 
		if (!this.menuActive){
			this.hideListNow();
		}
	},
	hideListNow:function(){ // hide the list right now
		var AllInlineMenus = $$("#menu ul");
		var i = 0;

		AllInlineMenus.each(function(el){
			if (Element.getStyle(el,"display") == "block"){
				var overlay = Element.next(el,"div");
				Effect.Appear(overlay, {from: 0.0, to:1.0, duration: 1, queue: {scope: "hideListNowOverlayFade"+i, limit: 3} });
				Effect.Fade(el, {from: 1.0, to:0.0, duration: 0.1, queue: {scope: "hideListNowOverlayFade"+i, position: 'end', limit: 3} });
				Effect.Fade(overlay, {from: 1.0, to:0.0, duration: 0.1, queue: {scope: "hideListNowOverlayFade"+i, position: 'end', limit: 3} });
				i++;
			}
		});
	},	
	hideSiblingsListNow:function(){ // hide all the siblings menus
  		var AllInlineMenus = this.menuObjectActive.up().select("ul");
  		var RelevantMenus = AllInlineMenus;
			RelevantMenus.each(function(el){
  			if (Element.getStyle(el,"display") == "block" && !el.descendantOf(menuEffects.menuObjectActive)){
  				var overlay = Element.next(el,"div");
  				Element.hide(el);
  				Element.hide(overlay);
					this.menuAnimActive = false;
  			}
  		});
	},
	afterMenuAnim:function(a,b){
		this.menuAnimActive = false;
	}
}

// country site navigation
var countryNavigation = {
	countryMenuCounter:false,
	timeout: 3000,
	subMenus:false,
	init:function(){
		var menu = $("globalNav");
		if (menu){
			var listItems = menu.select("li.area");
			listItems.each(function(el){
				var subMenu = el.select("div")[0];
				if (subMenu){
					// activate mouseover effect on elements with submenus
					el.observe("mouseover", function(){
						clearTimeout(countryNavigation.countryMenuCounter);
						countryNavigation.openMenu(subMenu);
					});
					el.observe("mouseout", function(e){
						countryNavigation.countryMenuCounter = setTimeout("countryNavigation.hideMenus()",countryNavigation.timeout);
						Event.stop(e);
					});
					if (!this.subMenus) this.subMenus = new Array; // if subMenus is false, create an array
					this.subMenus[this.subMenus.length] = subMenu;
				}
			});
		}
	},
	openMenu:function(subMenu){
		if (subMenu.getStyle("display") != "block"){
			// hide all other menus 
			subMenus.without(subMenu).each(function(el){
					Effect.Fade(el,{duration:.5});
			});
			Effect.Appear(subMenu,{duration:.5});
		}
	},
	hideMenus:function(){
		// hide every menu 
		subMenus.each(function(el){
			Effect.Fade(el,{duration:.5});
		});
	}
}

// activate the different states of the search button
var searchStates = {
	inpText:"",
	btn:"",
	init:function(){	    
		var container = $("mainSearch");		
		if (!container) return; // stop if there is no container element
		
		this.inpText = container.select("input")[0];
		this.btn = container.select("img")[0];
		
		// check if there is text preset in the text input
		if (this.inpText.value.length > 0) this.state(1);
		
		this.btn.observe("mouseover",function(){
			searchStates.state(0);
		});
		this.btn.observe("mouseout",function(){
			searchStates.state(2);
		});
		
		Event.observe(this.inpText,"keyup",function(){
			searchStates.state(2);
		});
	},
	state:function(i){
		if (i == 0){ // mouseover
			this.btn.src = "/images/buttons/search_over.gif";
		} else if (i == 1){ // keydown
			this.btn.src = "/images/buttons/search_active.gif";
		} else { // mouseout
			if (this.inpText.value.length > 0){
				this.btn.src = "/images/buttons/search_active.gif";
			} else {
				this.btn.src = "/images/buttons/search.gif";
			}
		}
	}
}
var Popup = {
  open: function(options)
  {
    this.options = {
      url: '#',
      width: 247,
      height: 223,
      name:"_blank",
      location:"no",
      menubar:"no",
      toolbar:"no",
      status:"yes",
      scrollbars:"no",
      resizable:"no",
      left:"",
      top:"",
      normal:false
    }
    Object.extend(this.options, options || {});

    if (this.options.normal){
        this.options.menubar = "yes";
        this.options.status = "yes";
        this.options.toolbar = "yes";
        this.options.location = "yes";
    }

    this.options.width = this.options.width < screen.availWidth?this.options.width:screen.availWidth;
    this.options.height=this.options.height < screen.availHeight?this.options.height:screen.availHeight;
    var openoptions = 'width='+this.options.width+',height='+this.options.height+',location='+this.options.location+',menubar='+this.options.menubar+',toolbar='+this.options.toolbar+',scrollbars='+this.options.scrollbars+',resizable='+this.options.resizable+',status='+this.options.status
    if (this.options.top!="")openoptions+=",top="+this.options.top;
    if (this.options.left!="")openoptions+=",left="+this.options.left;
    window.open(this.options.url, this.options.name,openoptions );
    return false;
  }
}

// BYOB total price update
function updateTotalPrice(){
	var chain = $('PriceChain');
	var charms = $('PriceCharms');
	var decimalSeperator = $('decimalSeperator').value;
	var thousandSeperator = $('thousandSeperator').value;
	var currencyInFront = $('currencyInFront').value;
	var currencyInBack = $('currencyInBack').value;
	
	if (chain && !charms)
	{
	    var totalPrice = parseFloat(chain.value);
	    
	    
		// formating of numbers to currency before being displayed
		var formattetPrice = totalPrice;
		$('priceTotal').innerHTML = currencyInFront + CommaFormatted(formattetPrice,decimalSeperator,thousandSeperator) + currencyInBack;
	}
	else if (charms && chain)
	{
		var totalPrice = parseFloat(charms.value) + parseFloat(chain.value);

		// formating of numbers to currency before being displayed
		var formattetPrice = totalPrice;
		$('priceTotal').innerHTML = currencyInFront + CommaFormatted(formattetPrice,decimalSeperator,thousandSeperator) + currencyInBack;
	}
	else
	{
	    $('priceTotal').innerHTML = '';
	}
	
}


function CommaFormatted(amount,decimalSeperator,thousandSeperator)
{
	var i = parseInt(amount);
	
	i = Math.abs(i);
	
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	
	if(n.length > 0) 
	{ a.unshift(n); }
	
	n = a.join(thousandSeperator);
	
	amount = n + decimalSeperator + '00';
	
	amount = amount;
	return amount;
}