/*=============================================================
  Spinning Jewelry
  Overall javascript
  Author:  Steven Sønderskov - Århuskontoret Elektrisk
===============================================================*/

//------------------------------------------------------------------------------------------------------ ISOTOPE
//Meet Juliette section
function sortMeetJulietteGrid(){
      $('#overviewContainer').isotope({
      itemSelector : '.item',
      layoutMode : 'fitColumns',
      masonry : {
      columnWidth : 198
      }    
    });	
	
    showOverviewArrows();    
}

//-------------------------------------------------------------------------------------------------------- EXTEND
$.extend({
  getUrlVars: function (){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


$.extend({
  getUrlHashVars: function (){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
	  hash = hashes[i].split('='); 
	  
      vars.push(hash);
	
     // vars[hash[0]] = hash[1];
    }
	
    return vars;
  },
  getUrlHashVar: function(name){
    return $.getUrlHashVars()[name];
  }
});



$.extend ({
  URLEncode: function (s) {
  	s = encodeURIComponent (s);
  	s = s.replace (/\~/g, '%7E').replace (/\!/g, '%21').replace (/\(/g, '%28').replace (/\)/g, '%29').replace (/\'/g, '%27');
  	s = s.replace (/%20/g, '+');
  	return s;
  },
  URLDecode: function (s) {
  s = s.replace (/\+/g, '%20');
  s = decodeURIComponent (s);
  return s;
  }
});


function ImgErrorProductImage(source){
    source.src = "/images/ImgErrorProductImage.jpg";
    source.onerror = "";	
    return true;
}
function ImgErrorproduct(source){
    source.src = "/images/ImgErrorproduct.png";
    source.onerror = "";	
    return true;
}
function ImgErrorrelatedProducts(source){
    source.src = "/images/ImgErrorrelatedProducts.png";
    source.onerror = "";	
    return true;
}

function addTowishErrorImg(source){
    source.src = "/ImageGen.ashx?image=/images/ImgErrorrelatedProducts.png&width=90&height=90";
	
    source.onerror = "";	
    return true;
}


//TIMER METHOD
;(function($) {
	$.timer = function(func, time, autostart) {     
	    this.set = function(func, time, autostart) {
	            this.init = true;
	            if(typeof func == 'object') {
	                    var paramList = ['autostart', 'time', 'action'];
	                    for(var arg in paramList) {
	                            if(func[paramList[arg]] != undefined) {
	                                    eval(paramList[arg] + " = func[paramList[arg]]");
	                            }
	                    };
	                    func = func.action;
	            }
	            if(typeof func == 'function') {
	                    this.action = func;
	            }
	            if(!isNaN(time)) {
	                    this.intervalTime = time;
	            }
	            if(autostart && !this.active) {
	                    this.active = true;
	                    this.setTimer();
	            }
	            return this;
	    };
	    this.once = function(time) {
	            if(!isNaN(time)) {
	                    this.setOnce(time);
	            } else {
	                    this.setOnce();
	            }
	            return this;
	    };
	    this.play = function () {
	            if(!this.active) {
	                    this.active = true;
	                    this.setTimer();
	            }
	            return this;
	    };
	    this.pause = function () {
	            this.active = false;
	            this.clearTimer();
	            return this;
	    };
	    this.stop = this.pause;
	    this.toggle = function () {
	            if(this.active) {
	                    this.pause();
	            } else {
	                    this.play();
	            }
	            return this;
	    };
	    this.reset = function () {
	            this.pause().play();
	            return this;
	    };
	    this.clearTimer = function () {
	            window.clearTimeout(this.timeoutObject);
	    };
	    this.setTimer = function(time) {
	            if(typeof this.action != 'function') {
	                    return;
	            }
	            if(isNaN(time)) {
	                    time = this.intervalTime;
	            }
	            var timer = this;
	            this.clearTimer();
	            this.timeoutObject = window.setTimeout(function () {timer.go();}, time);
	    };
	    this.setOnce = function(time) {
	            if(isNaN(time)) {
	                    time = 0;
	            }
	            var timer = this;
	            window.setTimeout(function () {timer.action();}, time);
	    };
	    this.go = function () {
	            if(this.active) {
	                    this.action();
	                    this.setTimer();
	            }
	    };
	    
	    if(this.init) {
	            return new $.timer(func, time, autostart);
	    } else {
	            this.set(func, time, autostart);
	            return this;
	    }
	};
})(jQuery);









//---------------------------------------------------------------------------------------------------------------- SHARE FUNCTIONALITET

function shareOnFacebook(id)
{
		
	$('.facebookImage').attr('href','www.spinningjewelry.com/product_images/large/'+id+'.jpg')
	
	var fbUrl = 'http://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fwww.spinningjewelry.com/' + curCountryCode + "/" + currentPageName + '.aspx/' + '%3Fproduct='+id+'%23product='+id;
	window.location = fbUrl;
	//,'Share','menubar=yes,toolbar=yes,location=yes,directories=yes,titlebar=yes,status=yes,scrollbars=yes,resizable=yes';
	
}



function shareTweet(id)
{
	var twUrl = 'http://twitter.com/share?url=http%3A%2F%2Fwww.spinningjewelry.com/' + curCountryCode + "/" + currentPageName + '.aspx/%3Fproduct='+id+'%23product='+id + '&amp;via=your_screen_name';
	
	window.location = twUrl;
}

//---------------------------------------------------------------------------------------------------------------- FORSIDE
var orgFrontSubmenuStart = 0;
function placeFrontSubmenu()
{
  orgFrontSubmenuStart = 520; //$('.mainImg').height();
  var newHeight = $('#content').height();
  $('#content').css('height',newHeight+55);
  
  $('#frontpageSubMenu').css('top',orgFrontSubmenuStart);
}

var footerPlacement = 0;
function placeFooter()
{
  footerPlacement = $('#content').height() + $('#topNav').height();
  $('#footer').css('top',footerPlacement);
}

function calculateSlider()
{
	      
    //BUGFIX FOR THUMBNAIL SCROLL
    $.fx.prototype.cur = function (){
      if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
        return this.elem[ this.prop ];
      }
        var r = parseFloat( jQuery.css( this.elem, this.prop ) );
        return typeof r == 'undefined' ? 0 : r;
    };
  $("#tS2").thumbnailScroller({ 
		scrollerType:"clickButtons", 
		scrollerOrientation:"horizontal", 
		scrollSpeed:2, 
		scrollEasing:"easeOutCirc", 
		scrollEasingAmount:600, 
		acceleration:4, 
		scrollSpeed:800, 
		noScrollCenterSpace:10, 
		autoScrolling:0, 
		autoScrollingSpeed:2000, 
		autoScrollingEasing:"easeInOutQuad", 
		autoScrollingDelay:500 
	});

}



var animating = false;
var runSlide = $.timer();
//SLIDE SUBMENU UP & DOWN ON PAGE LOAD
 	

function showSubMenu()
{
	
	
	
	var $submenuHitArea =  $('#submenuHitArea');
	var $frontpageSubMenu =  $('#frontpageSubMenu');
	var $submenuContent =  $('#submenuContent');
	
	 animating = true;
	 $submenuHitArea.fadeOut(10);
	 $frontpageSubMenu.animate({      
    	top: orgFrontSubmenuStart-130 ,
	  	opacity:0,    
      }, 0, function () { 
	  		
		
		$frontpageSubMenu.animate({  		
			opacity:1    
		}, 400, function () { 
			
				$submenuContent.bind('mouseleave', function () {
					$frontpageSubMenu.animate({      
						top: orgFrontSubmenuStart    
					}, 400, function () {
						// Animation complete.
						$submenuHitArea.fadeIn(400, function () {
							// Animation complete.
							
						});        
					});
					$submenuContent.animate({
						top: 50
					},400,function (){
					$submenuHitArea.fadeIn(400, function () {
						// Animation complete.
						$submenuContent.css('top','0px')							
							$submenuContent.unbind('mouseleave');
							animating = false;
						});  
					})
				});
		})			
	  })
	  

	
	  
		//RUN TIMER
		runSlide.set({
			action : function () {				
				hideSubMenu();			
			},
			time : 12000
		}).play();

}

function hideSubMenu()
{
	
	if(animating){
		 $('#frontpageSubMenu').animate({      
          top: orgFrontSubmenuStart    
          }, 400, function () {
          // Animation complete.
         
		  });
		  
		  
		   $('#submenuContent').animate({
			  	top: 50
			  },400,function (){
				$('#submenuHitArea').fadeIn(400, function () {
			    // Animation complete.
					 $('#submenuContent').css('top','0px')
				animating = false;
				
			  });  
			  })
		  
	}
	runSlide.stop();
}





//------------------------------------------------------------------------------------------------------- MEET JULIETTE
function getAboutJuliette()
{
	_gaq.push(['_trackPageview', curCountryCode+'/Meet Juliette']);
	$('#aboutJuliette').animate({
			top:0
		},400,
			function (){
					$('.lukAboutJuliette').bind('click', function (){
						closeAboutJuliette();
					})
			}
		)

        $('#julietteTopContent').removeClass('showingProduct');
        $('#julietteTopContent').animate({
            top:-520,
        },400)
}

function closeAboutJuliette()
{
	$('#aboutJuliette').animate({
			top:590
		},400,
			function (){
					$('.lukAboutJuliette').unbind('click', function (){
						closeAboutJuliette();
					})
			}
		)
}

function getOverview()
{
	_gaq.push(['_trackPageview', curCountryCode+'/View Gallery']);
	
	$('#overviewWrap').animate({
			top:0
		},400)
		
	$('#menuMidtSectionShiftImage').fadeOut(100,function (){
		$('#menuMidtSectionShiftMonth').fadeIn(100)
	});

    $('#julietteTopContent').removeClass('showingProduct');
        $('#julietteTopContent').animate({
            top:-520,
        },400)
	
}



var ovAnimation = false;
function slideOverview(dir)
{
	var pDir = parseInt(dir);
	
	if(!ovAnimation){
		$('.overviewRight ').removeClass('displayNone')
		$('.overviewLeft ').removeClass('displayNone')
		//Right pressed		
		if(!($('#overviewContainer').position().left + $('#overviewContainer').width() -990 <= 0) && pDir == 1){			
			ovAnimation = true;
			
				$('#overviewContainer').animate({
					left: $('#overviewContainer').position().left -396
				},300,function (){ovAnimation = false; calcMonthSlide();})			
			
		}
		
		
		//left pressed
		if(pDir == -1 && $('#overviewContainer').position().left != 0){
			ovAnimation = true;
			$('#overviewContainer').animate({
				left: $('#overviewContainer').position().left +396
			},300,function (){ovAnimation = false; calcMonthSlide();})	
		}	
		
	}
}
var currentPageId = 0;
var runBox = $.timer();
function getJulietteImage(nodeId)
{
	_gaq.push(['_trackPageview', curCountryCode+'/Image of Juliette/rel='+nodeId]);
	
	window.location.hash = nodeId;
	
	runBox.stop();
	$.ajax({		
		
        url: "/" + curCountryCode + "/" + currentPageName + '.aspx?ref='+nodeId+'&alttemplate=AJAX_julietteImage&curPage='+currentPageId,
        cache:false,
        success: function(data) {      
            
          $('#imageOfTheDay').html(data);
          $('#overviewWrap').animate({
			top:590
			},600)			
			currentRel = nodeId;
			gettingData = false;
			getNextOrPrevJulietteImage();
			
		}		
	})	
}

function shiftImageByPrevNext(nodeId)
{
	_gaq.push(['_trackPageview', curCountryCode+'/Image of Juliette/rel='+nodeId]);
	
	runBox.stop();
	$('#imageOfTheDay').fadeOut(300, function (){
		$.ajax({		
			
			url: "/" + curCountryCode + "/" + currentPageName + '.aspx?ref='+nodeId+'&alttemplate=AJAX_julietteImage&curPage='+currentPageId,
            cache:false,
			success: function(data) {  
               // alert(data);    
				$('#imageOfTheDay').fadeIn(300);               
				$('#imageOfTheDay').html(data);	
				currentRel = nodeId;
				gettingData = false;
				window.location.hash = nodeId;
			}		
		})
	})
    
    if($('#julietteTopContent').hasClass('showingProduct')){
    $('#julietteTopContent').removeClass('showingProduct');
        $('#julietteTopContent').animate({
            top:-520,
        },400)
    }
}

var julRelArray = new Array();
var relIndicator = 0;
var currentRel = 0;
var gettingData = false;
function getNextOrPrevJulietteImage(dir)
{
	if(!gettingData){
		gettingData = true;
		if(dir != undefined){
			var pDir = parseInt(dir);
			relIndicator += pDir;	
			
			$('.julGoLeft, .julGoRight').removeClass('displayNone');
		
			if(relIndicator <= 0){
				relIndicator = 0;
				$('.julGoLeft').addClass('displayNone');
			}
			
			if(relIndicator >= julRelArray.length-1){
				relIndicator = julRelArray.length-1;
				$('.julGoRight').addClass('displayNone');
			} 
			
			if(currentRel != julRelArray[relIndicator]){	
				shiftImageByPrevNext(julRelArray[relIndicator]);
				slideDatoTo(relIndicator);
			}
			
			
		}
		
		//HVIS DER HENTES BILLEDE IND FRA OVERVIEW SEKTIONEN
		if(dir == undefined){
			for(var i = 0; i< julRelArray.length; i++){
				
				if(julRelArray[i] == currentRel){
					
					$('.julGoLeft, .julGoRight').removeClass('displayNone');
					
					if(i == 0){
						$('.julGoLeft').addClass('displayNone');
					}
					
					if(i == julRelArray.length -1){
						$('.julGoRight').addClass('displayNone');
					}				
					relIndicator = i;
					
					gettingData = false;
					$('#menuMidtSectionShiftMonth').fadeOut(100, function (){
						$('#menuMidtSectionShiftImage').fadeIn(100,function (){
							slideDatoTo(relIndicator);
					});
					})
					
				}
				
			}
		}
	}
}

function calculateSlideWidth()
{
	var calcWidth = 0;
	
	$('#datoerContainer ul li').each(function(index) {
    	calcWidth += $(this).width();
		$('#datoerContainer').css('width',calcWidth+'px');
  	});
	
	slideDatoTo(relIndicator);
}

function calculateMonthWidth()
{
	var calcWidth = 0;
	
	$('#monthContainer ul li').each(function(index) {
    	calcWidth += $(this).width();
		$('#monthContainer').css('width',calcWidth+'px');
		
  	});
	
	slideMonthTo(0);
}


function slideDatoTo(pos, speed)
{
	if(speed == undefined){
		speed = 300;
	}
	
	$('#datoerContainer').animate({
		left:(215*pos)*(-1)+76,
	},speed)
	
	$('#datoerContainer ul li').each(function(index) {
		if(index == relIndicator){
			var obj = $(this).find('.dayDateLi')
			var objMonth = $(this).find('.monthNameLi')			
			
				$(obj).css('font-family','neueUltraLight')
				$(obj).css('font-size','48px')
				$(obj).css('margin-top','10px')
				$(obj).css('margin-left','15px')
				$(obj).css('float','left')
				$(objMonth).fadeIn(50);
		
		}
				
		if(index != relIndicator){
			var obj = $(this).find('.dayDateLi')			
			
				$(obj).css('font-family','neueBold')
				$(obj).css('float','right')
				$(obj).css('margin-top','27px')				
				$(obj).css('margin-right','35px')
				$(obj).css('font-size','13px')
		}
		if(index != relIndicator && index > relIndicator){
			var obj = $(this).find('.dayDateLi')	
			var objMonth = $(this).find('.monthNameLi')	
			$(objMonth).fadeOut(50, function (){
				$(obj).css('margin-left','30px')
				$(obj).css('float','left')
			});			
		}
	})
	
}


function slideMonthTo(pos)
{
	$('#monthContainer').animate({
		left:(200*pos)*(-1)+76,
	},300)
	
	$('#monthContainer ul li').each(function(index){
		if(index == monthIndicator){
			$(this).find('span:first').removeClass('displayNone');
		}
		else{
			$(this).find('span:first').addClass('displayNone');
		}
	})
}

var monthsArray = new Array(); //XSLT DEFINED
var monthIndicator = 0;
var currentMonth = 0; //XSLT DEFINED
function getMonthX(target)
{
	
	var pDir = parseInt(target);	
	monthIndicator += pDir;
	
	
	if(monthIndicator < 0){
		monthIndicator = 0;
	}
		
	if(monthIndicator >= monthsArray.length-1){
		monthIndicator = monthsArray.length-1;
	}
	
	
	//HVIS DER SKAL ANIMERES
	 slideMonthTo(monthIndicator)
	if(currentMonth != monthsArray[monthIndicator]){
		
		$('.julGoLeftMonth').removeClass('displayNone');
		$('.julGoRightMonth').removeClass('displayNone');		
		$('.overviewLeft').removeClass('displayNone');
		$('.overviewRight').removeClass('displayNone');
		
		$('#overviewContainer ul li').each(function(index) {
			
			if($(this).attr('rel') == monthsArray[monthIndicator]){
				
				var tx = (Math.floor(index/4));
				
				$('#overviewContainer').animate({
					
					left: (tx * 198)*(-1),
					
				}, 1000);
				
				//VI HAR FUNDET EN MÅNED
				currentMonth = monthsArray[monthIndicator];
				
				
			}
			
			
		})
	}
	
	if(monthIndicator == 0){
		$('.julGoLeftMonth').addClass('displayNone');
		$('.overviewLeft').addClass('displayNone');		
	}
	
	if(monthIndicator == monthsArray.length-1){
		$('.julGoRightMonth').addClass('displayNone');
		//$('.overviewRight').addClass('displayNone');
	}
}

function calcMonthSlide()
{	
	if($('#overviewContainer').position().left == 0){
		$('.overviewLeft').addClass('displayNone');
		$('.overviewRight').removeClass('displayNone')
	}
	
	if($('#overviewContainer').position().left + $('#overviewContainer').width() -990 <= 0){
		$('.overviewLeft').removeClass('displayNone');
		$('.overviewRight').addClass('displayNone')
	}
}

function showOverviewArrows()
{
	
	if($('#overviewContainer').width() < 980){		
		$('.overviewRight, .overviewLeft').addClass('displayNone')			
	}
	
	$('.julGoLeftMonth').addClass('displayNone')
	if(monthsArray.length == 1){
		$('.julGoRightMonth').addClass('displayNone')
	}
	
}


function resetJulietteProductList(){
	$('#leftPB ul li').each(function(index){
		if(index < 3){
			$(this).addClass('noTopMargin');
		}
	})
}

//----------------------------------------------------------------------------------------------------- HISTORY OF COMPANY
var historyArray = new Array()
function getHistoryYear(nodeId, dir)
{
   
   
    
   $.ajax({		
		
        url: '/global-settings/ajax.aspx?ref='+nodeId+'&alttemplate=AJAX_About_Us_History_Image',
        cache:false,
        success: function(data) {  
		   
		
			animateContent('#imgContainer',dir, data);		
          
		}		
	})
    
	//Set colour on year
    $('#historyField ul').find('li').each(function(index){
        if($(this).find('a').attr('rel') == nodeId){
            $(this).find('a').addClass('blueYear');
            currentHistoryIndicator = index;
        }
        else{
            $(this).find('a').removeClass('blueYear');
        }
    })	
}

function animateContent(obj,dir, data)
{
	if(dir == 1 || dir == undefined){
		$(obj).animate({
                left:-100,
				opacity:0
            	},400, function(){
					$(obj).css('left',100);
							
					$(obj).html(data);
					$(obj).animate({
						left:0,
						opacity:1
					}, 400)
		})
			}
	else{
		$(obj).animate({
                left:100,
				opacity:0
            	},400, function(){
					$(obj).css('left',-100);
							
					$(obj).html(data);
					$(obj).animate({
						left:0,
						opacity:1
					}, 400)
		})
	}
	
}

var currentHistoryIndicator = 0;
function getNextOrPrevHistoryYear(dir)
{
    var dDir = parseInt(dir);
    currentHistoryIndicator += dDir;

    if(currentHistoryIndicator < 0){
        currentHistoryIndicator = historyArray.length -1;
    }
    if(currentHistoryIndicator > historyArray.length -1){
        currentHistoryIndicator = 0;
    }
   getHistoryYear(historyArray[currentHistoryIndicator], dDir) 
}


function closeHistoryOverview()
{
    
  
		
		if($("#imageRotation").hasClass('displayNone')){						
			 imgRotation.startTimer();
            $('.noBorder').addClass('removeBorderJS')		
			$('.noBorder').removeClass('noBorder')
			$('#historyField').animate({
                top:-400
            },400, function(){
                $('#historyField').addClass('displayNone');
                $("#imageRotation").css('top','-400px')
                $("#imageRotation").removeClass('displayNone');
                
                $("#imageRotation").animate({
                    top:0,                    
                }, 450)
            });

            $('#topContent').animate({
                height:370
            },400);
			
		}
        else{
			imgRotation.stopTimer();
            $('.removeBorderJS').addClass('noBorder')		
			$('.noBorder').removeClass('removeBorderJS')
            $('#imageRotation').animate({
                    top:-400
                },400, function(){
                    $('#imageRotation').addClass('displayNone');
                    $("#historyField").css('top','-400px');                   
                    $("#historyField").removeClass('displayNone');
                    $("#historyField").animate({
                        top:0,                    
                    }, 450)
                });

                $('#topContent').animate({
                    height:400
                },400);
        }		

}

//------------------------------------------------------------------------------------------------------- GLOBAL FUNCTIONS

//Fold next element in or out
var closeBtnTxt, openBtnTxt;
var productspage = false;
function foldoutNext(obj)
{	
	if(!obj.next('div,li').hasClass('hideThisNext')){
        if(productspage){
			$('.hideThisNext').slideUp(function(){$(this).removeClass('hideThisNext')})
		}
		
        obj.next('div,li').slideDown(function (){
			$(this).addClass('hideThisNext');
			if(obj.hasClass('plusSign')){
				$(obj).removeClass('plusSign');
				$(obj).addClass('minusSign');
			}           					
		});
        if($(obj).prev('div,li').hasClass('removeBorderJS')){
            $(obj).prev('div,li').addClass('noBorder');
            $(obj).prev('div,li').removeClass('removeBorderJS');
        }
        if($(obj).parent().find('.removeBorderJS')){
           $(obj).parent().find('.removeBorderJS').addClass('noBorder');
           $(obj).parent().find('.removeBorderJS').removeClass('removeBorderJS'); 
        }

        $(obj).text(closeBtnTxt)	
	}
	else{		
		obj.next('div,li').slideUp(function (){
            $(this).removeClass('hideThisNext');
                if(obj.hasClass('minusSign')){
                    $(obj).removeClass('minusSign');
                    $(obj).addClass('plusSign');
                }
                if($(obj).prev('div,li').hasClass('noBorder')){
                    $(obj).prev('div,li').addClass('removeBorderJS');
                    $(obj).prev('div,li').removeClass('noBorder');
                }
                 if($(obj).parent().find('.noBorder')){
                   $(obj).parent().find('.noBorder').addClass('removeBorderJS');
                   $(obj).parent().find('.noBorder').removeClass('noBorder'); 
                }         			
		});

         $(obj).text(openBtnTxt)
	}
}


//SET FOOTER POSITIONING 
/*
	Footer position skal være absolute på forsiden, pga andet indhold. På resterende sider skal den sættes til at være relativ for at følge #content height.
	På forsiden beregnes dens absolutte positionering ud fra højde på billedet i #content.
*/
function resetFooter()
{
	 $('#footer').css('position','relative');
}

var popupDiv;
var overlayMessage = '';
//showOverlay forventer et ID på den div der skal vises inde i overlayet
function showOverlay(showDiv, message)
{
    //SHOW STUFF
	if(popupDiv == null){		
		var obj = $('#'+showDiv);
        $('#overlaysPlacer').width($(obj).width());//CSS FIX FOR AT ALIGNE I MIDTEN
		$('#overlaysPlacer').height($(document).height());
		$('.overlaybg').height($(document).height()+250);
		popupDiv = obj;
		$(obj).removeClass('displayNone')
		$('#overlay').fadeIn('slow', function (){
			$('.overlaybg, .closePopUp').bind('click', function (){
				showOverlay(obj)	
			})
		})
		
		if(message != undefined){
			overlayMessage = message;			
			$(obj).find('.overlayMessage').text(overlayMessage);
		}
		else{
			$(obj).find('.overlayMessage').text('');
		}
		
	}	
	//HIDE STUFF
	else{
		$('.overlaybg, .closePopUp').unbind('click');
		$('#overlay').fadeOut('fast', function (){
			$(popupDiv).addClass('displayNone');			
			popupDiv = null;			
		});
		
	}
}


//IMAGE ROTATION
var imgRotationArray = [];
var nextRotateImg = 1;
var randomSelectedImages = [];


//IMAGE ROTATION
var imgRotation = (function(){
	var self, randomSelectedImages, mainImage, nextRotateImg, imgRotateTimer;
	self = {};
	nextRotateImg = 1;
	randomSelectedImages = [];
    
    //SET TIMER FOR SHIFTING IMAGES
	imgRotateTimer = $.timer();    
	imgRotateTimer.set({
		action : function () {				
			imageRotationShift();			
		},
		time : 8000
	});

	function imageRotationShift(){
		var fadeTime, ranImageArr, loadThisImg, hasDisplayNone, imageTwo, imageOne;

		fadeTime = 500;
		ranImageArr = randomSelectedImages;
		loadThisImg = ranImageArr[nextRotateImg];
		imageOne = mainImage.find('.imageOne');
		imageTwo = mainImage.find('.imageTwo');
		hasDisplayNone = imageTwo.hasClass('displayNone');
        //imageTwo

		if(hasDisplayNone){
		imageTwo.attr('src', loadThisImg).load(function (){
				mainImage.append( $(this) );			
				imageTwo.fadeIn(fadeTime, function (){
					$(this).removeClass('displayNone');
					imageOne.fadeOut(fadeTime, function (){
						$(this).addClass('displayNone');
					});
				});
			});	            
		} else {
			imageOne.attr('src', loadThisImg).load(function (){
				mainImage.append( $(this) );
				imageOne.fadeIn(fadeTime, function (){
					$(this).removeClass('displayNone');
					imageTwo.fadeOut(fadeTime, function (){
						$(this).addClass('displayNone');
					});
				});
			});	            
		}
		
	
		nextRotateImg++;

		if(nextRotateImg > ranImageArr.length-1){
			nextRotateImg = 0;
		}
	}

	self.startRotation = function(){
		var antalImgs, ieVersion, i, randNr, idx;
		
		//BUILD RANDOM ARRAY
		randomSelectedImages = [];	
		antalImgs = 10;
		ieVersion = 9;

		if(imgRotationArray.length < 10){
			antalImgs = imgRotationArray.length;
		}		
	
		//IE8 fix. Hvis IE 8 eller mindre så drop at sætte randomSelectedImages, men sæt den til alle billeder.        
		if($.browser.msie){
			ieVersion = parseInt($.browser.version, 10);
			
		}

		if(ieVersion >= 9){
			for(i = 0; i < antalImgs; i += 1){
		
				randNr = Math.ceil(Math.random() * imgRotationArray.length - 1);
				randomSelectedImages.push(imgRotationArray[randNr]);		
				idx = imgRotationArray.indexOf(imgRotationArray[randNr]); // Find index
				if( idx !== -1){
					imgRotationArray.splice(idx, 1); // Remove it if really found!
				}
			}
			
		}else{
			randomSelectedImages = imgRotationArray;
			
		}
	
		//SET FIRST IMAGE        
		mainImage = $("#imageRotation").find(".mainImage");
		mainImage.find('.imageOne').attr('src', randomSelectedImages[0]).load(function (){            
			mainImage.append( $(this) );
		});			
			
        // Start timer
        imgRotateTimer.play();
	};    	

    self.stopTimer = function(){
        imgRotateTimer.stop();        
    };

    self.startTimer = function(){
        imgRotateTimer.play();        
    };

	return self;
}());

//SHOW SEARCH FIELD
function getSearchField()
{
	
	$('.getSearchBtn').mouseover(
		function () 
		{			
			$('.getSearchBtn').unbind('click'); //HVIS DER ER CLICK EVENT. FOR IKKE AT FÅ SAMME CLICK EVENT FLERE GANGE
			$('.getSearch').stop();
			$('.getSearch').animate({      
				right: $('.getSearch').width()-10   
			}, 400, 
				function (){
					
					//SET LISTENER FOR CLICK ON SEARCH_BTN
					$('.getSearchBtn').bind('click',function (){submitSearchField();})
					//SET FOCUS ON TXT FIELD & LISTEN FOR MOUSE LEAVE ON TOP MENU
					$('.getSearch input').focus();
					$('#topNav').bind('mouseleave',function (){
						//$('.getSearch input').val('');
						$('.getSearch').animate({      
							right: $('.getSearch').width()*(-1)   
						}, 400 ,function (){
								$('#topNav').unbind('mouseleave');
								$('.getSearchBtn').unbind('click');
							})
					})
					
					$('.getSearch input').click(function(){$('.getSearch input').val('');})
					//$('.getSearch input').keypress(function(){$('.getSearch input').val('');})
					
					
				})
		}
	);	
}

function submitGetSearch()
{
	$('#searchForm').trigger('submit');
}

//SET COOKIE FOR LANGUAGE SETTINGS
function getLanguageUrl(nodeName)
{
    if(nodeName != 'COM'){
		var coo = $.cookie('cookieCountry', nodeName);    	 
	}
	else{
		var coo = $.cookie('cookieCountry', '');
		
	}
	window.location = '/' + nodeName;
   
}

var formUrl = "";
var formUrlCurPage ='';
function collectURLDataForForm()
{
	//var hashCollection = new Array()
		var hashCollection = new Array();
		hashCollection = $.getUrlHashVars('collection')
		
	
		
		
		if(hashCollection[0] != undefined){
			formUrl += hashCollection[0][0]+'='+hashCollection[0][1];
		}
		
		if(hashCollection[1] != undefined){
			formUrl += '&'+hashCollection[1][0]+'='+hashCollection[1][1];
		}
		
		if(hashCollection[2] != undefined){
			formUrl += '&'+hashCollection[2][0]+'='+hashCollection[2][1];
		}
		
		if(hashCollection[3] != undefined){
			formUrl += '&'+hashCollection[3][0]+'='+hashCollection[3][1];
		}
		
		if(formUrl.indexOf("http") != -1){
			formUrl = '';
		}
		
		
		return true;
		
	
}



//-------------------------------------------------------------------------------------------------------- RETAILERS

function foldOutSubmenu(target){
	
	var tt = $(target).next();
	
	if(tt.hasClass('displayNone')){
		tt.slideDown('fast',function(){
			$(target).removeClass('arrowSignDown');			
			$(target).addClass('arrowSignUp');
			$(this).removeClass('displayNone');
		});
	}
	else{
		tt.slideUp('fast',function(){
			
			$(target).removeClass('arrowSignUp');
			$(target).addClass('arrowSignDown');
			$(this).addClass('displayNone');
		});
	}
}

//-------------------------------------------------------------------------------------------------------- ADD LISTERS ETC


  
$(document).ready(function () {

    /*if (window.Touch){isiPad = true;}*/	
	
	
	var openOverlay = $.getUrlVar('openOverlay');
	
	
	if(openOverlay != null || openOverlay != undefined){
		showOverlay(openOverlay)
	}
	
	//FORSIDE
	if(document.getElementById('submenuHitArea') != null){
		
		
		var $submenuHitArea =  $('#submenuHitArea');
		var $frontpageSubMenu =  $('#frontpageSubMenu');
		var $submenuContent =  $('#submenuContent');
	
		
	  $submenuHitArea.hover(function () {    
		
		if(!animating){
		  animating = true;
		  $submenuHitArea.fadeOut(0)
		  $frontpageSubMenu.animate({      
			top: orgFrontSubmenuStart-130      
		  }, 600, function () {
			// Animation complete.  
			
				$submenuContent.bind('mouseleave', function () {
			  
				  $frontpageSubMenu.animate({      
					top: orgFrontSubmenuStart    
				  }, 400);  
				  
				  $submenuContent.animate({
					top: 50
				  },400,function (){
					$submenuHitArea.fadeIn(400, function () {					
					// Animation complete.
						$submenuContent.unbind('mouseleave');
						$submenuContent.css('top','0px')						
						animating = false;					
				  });  
				  })
				});
			
		  });        
		  
		}
	  });//HOVER END
	
		//Chrome fix
		$('#footer').css('top','-600px');		
		
	}// IF END
	
	
	
	
	
	//LISTEN FOR FOLD OUT NEXT, ELEMENTS	
    if($('.foldoutNext').length){
		$('.foldoutNext').click(function (){foldoutNext($(this))});
	}
	
	if($('.closeWishList').length){
		$('.closeWishList, .closeFormContainer').click(function (){closeWishList($(this))});
	}			
	
	// JULIETTE
	if($('.getAboutJuliette').length){		
		$('.getAboutJuliette').click(function (){getAboutJuliette();})
	}    	
	
	if(document.getElementById('overviewContainer') != null){		
		calculateSlideWidth();
		calculateMonthWidth();
		sortMeetJulietteGrid();
		$('.getJulietteOverview').click(function (){getOverview();})
		$('.itemLink').click(function (){			
			getJulietteImage($(this).attr('rel'));
		})
		
		$('.overviewLeft, .overviewRight').click(function (){slideOverview($(this).attr('rel'))})
		
		//Hover på overview billeder
		$(".itemLink").hover(
			function () {
				$(this).find('span:first').fadeIn('fast')
			},
			function () {
				$(this).find('span:first').fadeOut('fast')
			}
		);
		
		//Gå frem og tilbage i billeder
		$('.julShiftImg').click(function (){
			getNextOrPrevJulietteImage($(this).attr('rel'));
		})	
		//Gå frem og tilbage i mdr
		$('.monthShiftImg').click(function (){
			getMonthX($(this).attr('rel'));
		})	
	}
	
    //----------------------------HISTORY - ABOUT US
    if($('.historyYearLink').length){		
		$('.historyYearLink').click(function (){getHistoryYear($(this).attr('rel'));});
        $('#historyField .prevProduct, #historyField .nextProduct').click(function(){getNextOrPrevHistoryYear($(this).attr('rel'))})
        $('#closeXHis, .getHistory').click(function(){closeHistoryOverview()})
        $('.removeBorderJS').addClass('noBorder');
        $('.removeBorderJS').removeClass('removeBorderJS');
    }
	//----------------------------GLOBALS
	
	//SHOW OVERLAYS
	
    /*if($('.showWishlist').length){		
		$('.showWishlist').click(function (){showOverlay('addToWishListOL');});
	}*/
	if($('.showChangeCountry').length){		
		$('.showChangeCountry').click(function (){showOverlay('changeCountry');});
	}
	if($('.showSignIn').length){		
		$('.showSignIn').click(function (){showOverlay('signIn');});
	}
	if($('.sendWish').length){		
		$('.sendWish').click(function (){
			showOverlay('shareWishlist');
			//SMID VALUE IND PÅ HIDDEN FIELD, SÅ DEN KAN HENTES UD VIA XSLT
			$('#shareListID').val($(this).attr('rel'))
			
		});
	}
	if($('.createWishList').length){		
		$('.createWishList').click(function (){showOverlay('createWishlist');});
	}
    if($('.terms').length){		
		$('.terms').click(function (){showOverlay('termsOverlay');});
	}
       
	
	
	//SHOW SEARCHFIELD
	getSearchField();
	
		
	
	
});//DOC READY END

$(window).load(function () {
	
	//FORSIDE
	$('#footer').removeClass('displayNone');
	if(document.getElementById('submenuHitArea') != null){
		calculateSlider();
		placeFrontSubmenu();
		showSubMenu();
		placeFooter();		
	}
	
	
	$('#frontQuote').fadeIn(800,function(){$(this).removeClass('displayNone')});
	
	
	
	// IF NOT FRONTPAGE
	if(document.getElementById('submenuHitArea') == null){
		resetFooter();
	}
	
	//GLOBAL

	
});

//DEBUGGING
//------------------------------------------------------------------------------------------------------------------TRACE
function trace(param){
  window.console.log(param);
}


