// Author: Steven Holmberg Sønderskov - Aarhuskontoret Elektrisk



//----------------------------------------------------------------------- GET URL VARS EXTENSION

$.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];
  }
});


//----------------------------------------------------------------------- SUBMENU HANDLER

//Variabler for submenuHandler
var frontCatCount = 1;
var capCount = 0;
var submenuHandler = (function ($, window, document) {	
	var self = this;
	
	this.toggleCategory = function (obj) {
		
		$('#subNav li.getSub').each(function(index){
			
			if($(this).get(0) == $(obj).get(0)){
				$(this).next('li').find('ol').slideDown(200, function(){
					$(this).removeClass('displayNone')
				})
			}
			else{
				$(this).next('li').find('ol').slideUp(200, function(){
					$(this).addClass('displayNone')
				})
			}
		})		
	};
	
	this.closeAllLists = function(){
		
		$('#subNav li.getSub').each(function(index){			
			
			$(this).next('li').find('ol').slideUp(200, function(){
				$(this).addClass('displayNone')
			})
			
		})	
	};
	
	this.getFilmRibbon = function(id){
		
		
		var wurl = '';			
		wurl = '/forside.aspx?altTemplate=ajax_getMovie&nodeId='+id;			
			
			//skift top billeder
			$.ajax({    
				url:wurl,		
				cache: false,                      
				success: function(data) {
					window.console.log('yes')
					
					$('#productContainerPrepender').html('');
					$(data).prependTo('#productContainerPrepender');
				}    
			})
		
		
	}
	
	this.requestProducts = function(rel, forside, altTemplate, keepCount, overWriteCount,typeSorting, sortByThisType){
		
		
		if(!keepCount){
			frontCatCount = 1;
		}
		
		if(overWriteCount != undefined ){
			frontCatCount = parseInt(overWriteCount);
		}			
		
		if(!altTemplate){
		
			var wurl = '';
			if(forside == true){
				wurl = '/forside.aspx?altTemplate=AJAX_getForsideStart&nodeId='+rel;
			}
			else{
				wurl = '/forside.aspx?altTemplate=AJAX_forsidetilbud&nodeId='+rel;
			}
			
			
			//skift top billeder
			$.ajax({    
				url:wurl,		
				cache: false,                      
				success: function(data) {
					
					$('#productContainerPrepender').html('');
					$(data).prependTo('#productContainerPrepender');
				}    
			})
		}
		
		$('#subNav ul li ol li a').each(function(){
			if($(this).hasClass('activeSubmenu')){
				$(this).removeClass('activeSubmenu');
			}
			
			if($(this).attr('rel') == rel){
				$(this).addClass('activeSubmenu');
			}
		})	
		
		//Skift produkter i slider ud
		if(forside != true){
			var nWurl;
			if(altTemplate){
				if(!typeSorting){
					if(sortByThisType != undefined){
						nWurl = '/forside.aspx?altTemplate=AJAX_build_tilbud_gridvisning&counter='+frontCatCount+'&nodeId='+rel+'&sortByThisType='+sortByThisType;
					}
					else{
						nWurl = '/forside.aspx?altTemplate=AJAX_build_tilbud_gridvisning&counter='+frontCatCount+'&nodeId='+rel;
					}
				}
				else{
					nWurl = '/forside.aspx?altTemplate=AJAX_build_tilbud_gridvisning&counter='+frontCatCount+'&nodeId='+rel+'&showSorting=true';
				}
			}
			else{
				nWurl ='/forside.aspx?altTemplate=AJAX_getTilbud&nodeId='+rel;
			}
			
			$.ajax({    
			url:nWurl,		
			cache: false,                      
			success: function(data) {
					
					if(!altTemplate){
						$('#tilbudsSlider').removeClass('displayNone')	
						$('#tS2').html('');
						$(data).prependTo('#tS2');
						
						
						//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;
						};
						
						markedPagination = 0;
						
						$("#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,
							scrollAmount:720 //VÆRDI TILFØJET I SCRIPTET AF STEVEN H. SØNDERSKOV -AARHUSKONTORET. :: Styrer hvor mange px der scrolles horisontalt
						});
						
						$('.getProduct').mouseenter(function(){tilbudsSlideHandler.showProduct(this)})
						$('#tS2').addClass('IE7Fix');
						$('#tS2').removeClass('IE7Fix');
					}
					else{
						$('#tilbudsSlider').addClass('displayNone');						
						$('#productContainerPrepender').html('');
						$('#productContainerPrepender').html(data)
						//$(data).prependTo('#productContainerPrepender');
						$('.getProduct').mouseenter(function(){tilbudsSlideHandler.showProduct(this, true)})
					}
			}    
			}) 			
			
		}	
		 		
	}
	
	
	this.getPrevOrNextAltGrid = function(nodeId, dir, sortBy){
		
		var dDir = parseInt(dir);
		frontCatCount += dDir;
		
		if(frontCatCount< 1){
			frontCatCount = capCount;			
		}
		if(frontCatCount> capCount){
			frontCatCount = 1;	
		}	
					
		self.requestProducts(nodeId, false, true, true, undefined, false, sortBy )
		
	};
	

    return this;
} (jQuery, window, document));





//----------------------------------------------------------------------- CATALOGUE HANDLERS
var catalogLoaded = false;
function toggleCatalogue()
{
	var $catalogue = $('#catalogue');
	if($catalogue.hasClass('displayNone')){
		
		//_gaq.push(['_trackPageview','Vis produkt katalog']);
		
		if(!catalogLoaded){
			
			$.ajax({    
			url:'/forside.aspx?altTemplate=AJAX_build_tilbudsavis',		
			cache: true,                      
			success: function(data) {
					catalogLoaded = true;
					$('#catalogContainer').html('');
					$(data).prependTo('#catalogContainer');
							
					$catalogue.slideDown(400, function(){
						$catalogue.removeClass('displayNone');
						 $('#slides').slides({
							preload: false,
							preloadImage: '/images/loading.gif',
							play: 0,
							pagination: true,
							generatePagination: true		
						});
					})				
					if ($(document).scrollTop() != 850) {
						$('html, body').animate({ scrollTop: 850 }, 'fast');
					}	
							
							
				}    
			}) 
			
		}//if
		else{
			$catalogue.slideDown(400, function(){
				$catalogue.removeClass('displayNone')
			})		
			if ($(document).scrollTop() != 850) {
				$('html, body').animate({ scrollTop: 850 }, 'fast');
			}
		}
		
		
	}
	else{
	//	_gaq.push(['_trackPageview','Vis produkt katalog']);
		$catalogue.slideUp(400, function(){
			$catalogue.addClass('displayNone')
		})
	}
}


//




var animating = false;
var dofadeIn = false;
var ajaxNode = '';
var tilbudsSlideHandler = (function ($, window, document) {	
	
	this.showProduct = function (obj, altGrid){
		
		
		//ANALYTICS
		_gaq.push(['_trackPageview','Produkt/'+$(obj).find('.productTxtHolder h1').text()]);
		
		var $productHover;
		
		if(altGrid == true){			
			$productHover = $('#productHoverAlt');
			
		}
		else{
			$productHover = $('#productHover');
			
		}
		
		
		
		if(!animating){
			animating = true;
			dofadeIn = true;
			var wurl;
			
			if(ajaxNode != $(obj).attr('rel')){
				ajaxNode = $(obj).attr('rel');
				wurl = '/forside.aspx?altTemplate=AJAX_buildHoverTilbud&nodeId='+$(obj).attr('rel');
				
				
				$.ajax({    
					url:wurl,		
					cache: true,                      
					success: function(data) {
						
						
							
							if(altGrid){
								$('#productHoverAlt').html('');
								$(data).prependTo('#productHoverAlt');
							}
							else{
								$('#productHover').html('');
								$(data).prependTo('#productHover');														
							}
							
							
							if(dofadeIn){
								
								if(altGrid){
									var $obj = $(obj);
									
									/*$productHover.fadeIn('fast',function(){
										$productHover.removeClass('displayNone');
										animating = false;
									})*/
									$productHover.css('left' , ($(obj).position().left + $('#altListHolder').position().left) - 15) ;
									
									var arrowOnTop = true;
									// top positions
									if($obj.position().top < 200){
										$productHover.css('top' , 130) ;																		
									}
									
									if($obj.position().top > 200){
										$productHover.css('top' , -115) ;
										arrowOnTop = false;	
									}						
									
									
									if($obj.position().top > 400){
										$productHover.css('top' , 90);
										arrowOnTop = false;	
									}
									
									// left positions								
									
									//Product to right
									if($productHover.position().left > 400){
										$productHover.css('left' , ($(obj).position().left + $('#altListHolder').position().left) - 300);
										if(!arrowOnTop){
											$productHover.css('background-image','url(/images/grid_hover_3.png)')										
										}
										else{
											$productHover.css('background-image','url(/images/grid_hover_3_t.png)')	
										}									
									}
									
									if($productHover.position().left > 299){
										$productHover.css('left' , 280) ;
										if(!arrowOnTop){
											$productHover.css('background-image','url(/images/grid_hover_1.png)')
										}
										else{
											$productHover.css('background-image','url(/images/grid_hover_1_t.png)')	
										}
										
										
									}
									
									if($productHover.position().left < 260){
										
										if(!arrowOnTop){
											$productHover.css('background-image','url(/images/grid_hover_2.png)')
										}
										else{
											$productHover.css('background-image','url(/images/grid_hover_2_t.png)')
										}
										
										
									}
									
									$productHover.css('display', 'block')
									//$productHover.removeClass('displayNone');
									animating = false;
									
									
								}
								else{
									
									$productHover.css('left' , ($(obj).position().left + $('.jTscroller').position().left) + 150) ;
									
								
									if($productHover.position().left > 400){
										$productHover.css('left' , ($(obj).position().left + $('.jTscroller').position().left) - 45);
										$productHover.css('background-image','url()');
										$productHover.css('background-image','url(/images/popup_bg_mirror.png)')
										
									}
									
									else{
										$productHover.css('background-image','url()');
										$productHover.css('background-image','url(/images/popup_bg.png)')
										
									}
									
									if($productHover.position().left < 0){
										$productHover.css('left' , ($(obj).position().left + $('.jTscroller').position().left) + 650);
										$productHover.css('background-image','url()');
										$productHover.css('background-image','url(/images/popup_bg_first.png)')
										
									}
									$productHover.css('display', 'block')
									//$productHover.show();
									$productHover.removeClass('displayNone');
									/*$productHover.fadeIn('fast',function(){
										$productHover.removeClass('displayNone');
										animating = false;
									})*/
									
								}
							}
												
					}    
				}) 
			}
			else{
				$productHover.css('display', 'block');				
				$productHover.show();
				$productHover.removeClass('displayNone');
				animating = false;
				/*$productHover.fadeIn('fast',function(){
					$productHover.removeClass('displayNone');
					animating = false;
				})*/

			}
		}
		
		$(obj).bind('mouseleave', function(){
			dofadeIn = false;
			animating = false;	
			$productHover.css('display', 'none')
			$(obj).unbind('mouseleave');	
			/*$productHover.fadeOut(0, function(){					
				$(obj).unbind('mouseleave');	
			});*/
		})
	};
	
	
	
	
	

    return this;
} (jQuery, window, document));




//----------------------------------------------------------------------- JOBS

function toggleJobformular()
{
	var $catalogue = $('#ansoegningsskema');
	if($catalogue.hasClass('displayNone')){
		$catalogue.slideDown(400, function(){
			$catalogue.removeClass('displayNone')
		})
		
		if ($(document).scrollTop() != 500) {
            $('html, body').animate({ scrollTop: 500 }, 'fast');
        }
	}
	else{
		$catalogue.slideUp(400, function(){
			$catalogue.addClass('displayNone')
		})
	}
}




//----------------------------------------------------------------------- KONTAKT FORM 


var kontaktFormHandler = (function ($, window, document) {	
	
	this.resetKontaktform = function (){		
		$('#Navn, #Adresse,#Email,#Postnr,#By,#comments').val('');		
	};
	
	this.validateForm = function (){	
		
		var sending = true;
		var $errorMessage = $('#errorMessage');	
		
		$errorMessage.addClass('displayNone');
		$errorMessage.text('');
		
		if($('#Navn').val() == ''){
			$errorMessage.text('Udfyld Navn')
			$errorMessage.removeClass('displayNone');
			sending = false;
		}
		
		if($('#Adresse').val() == ''){
			$errorMessage.text('Udfyld Adresse')
			$errorMessage.removeClass('displayNone');
			sending = false;
		}
		
		if($('#Email').val() == '' || $('#Email').val().indexOf('@') == -1 || $('#Email').val().indexOf('.') == -1 ){
			$errorMessage.text('Udfyld Email')
			$errorMessage.removeClass('displayNone');
			sending = false;
		}
		
		if($('#Postnr').val() == ''){
			$errorMessage.text('Udfyld Postnr.')
			$errorMessage.removeClass('displayNone');
			sending = false;
		}
		
		if($('#By').val() == ''){
			$errorMessage.text('Udfyld By')
			$errorMessage.removeClass('displayNone');
			sending = false;
		}
		
		
		if(sending){					
			$errorMessage.text('');
			return true
		}
		if(!sending){			
			return false
		}
		
		
	};
	
	this.confirmMailsent = function (){		
		$('#errorMessage').text('Formular sendt');	
		$('#errorMessage').removeClass('displayNone');		
	};
	

    return this;
} (jQuery, window, document));






//----------------------------------------------------------------------- SUBMIT SEARCH

function submitSearch(){
	$('#searchFieldForm').submit();
}

//----------------------------------------------------------------------- GET FULLSCREEN

function getFullscreen(){
	
	
	
	window.open('/forside.aspx?alttemplate=TilbudsavisFullscreen','','scrollbars=yes,menubar=no,height=1300,width=1500,resizable=yes,toolbar=no,location=no,status=no');
}

//----------------------------------------------------------------------- TOLDREGLER SLIDE HANDLER

var toldSlideHandler = (function ($, window, document) {	
	
	this.slideContent = function (relId) {
		
		var pDir = parseInt(relId);
		
		$('#toldSkema').animate({
			
			left:0 - (pDir*650)
			
		}, 400)
		
		
		$('#toldreglerTop ul li a').each(function(){
			
			if($(this).attr('rel') == relId ){
				$(this).addClass('active');
			}
			else{
				$(this).removeClass('active');
			}
			
		})
	};
	
	
	

    return this;
} (jQuery, window, document));




//----------------------------------------------------------------------- ANALYTICS TIL PRODUKT KATALOG
var currentCataloguePage = 1;
var topcountForCatalogue = 1;

function trackCataloguePages(dir){
					
	currentCataloguePage += dir;
	
	if(currentCataloguePage > topcountForCatalogue){
		currentCataloguePage = 1;
	}
	
	if(currentCataloguePage < 1){
		currentCataloguePage = topcountForCatalogue;
	}
	
	
	_gaq.push(['_trackPageview','Tilbuds-katalog-visning/side-'+currentCataloguePage]);		
}


				 





//----------------------------------------------------------------------- DEBUGGING

function trace(data)
{
	window.console.log(data)
}



//----------------------------------------------------------------------- ON READY HANDLER
$(document).ready(function () {
	
	
	$('#getTilbudsAvis').click(function(){toggleCatalogue();})
	
	$('.getSub a').click(function(){submenuHandler.toggleCategory($(this).parent());})
	$('.closeSubs').click(function(){submenuHandler.closeAllLists();})
	 
	$('.getProduct').mouseenter(function(){tilbudsSlideHandler.showProduct(this)})
	$('.getProduct').click(function(){tilbudsSlideHandler.showProduct(this)})
	
	//Catalogue slider
	$('#slides').slides({
		preload: true,
		preloadImage: '/images/loading.gif',
		play: 0,
		pagination: true,
		generatePagination: true		
	});
	
	
	//Lyt efter kontakt submit success
	
	var mailSent = $.getUrlVar('mailSent');
	
	if(mailSent == 'true'){
		kontaktFormHandler.confirmMailsent();
	}
	
	
	
	// CLEAR BUSLOGIN ON FOCUS
	$('#busLogin input, #nyhedsbrevTilmelding input').focus(function(){
		$(this).val('');	
	})
	
	
	
	$('#tS2').bind('mouseleave', function(){				
		$('#productHover').fadeOut(0);
	})
	
	$('#searchThis').focus(function(){
		$(this).val('');
		$('#searchThis').css('color','#fff');
		$('#searchThis').css('font-style','normal');
		
	})
	
	//FACEBOOK IFRAME FIX
	//$('.fb-like span .fb_ltr').css('width',185);
	
	
	
});


$(window).load(function () {
	
	//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,
		scrollAmount:720 //VÆRDI TILFØJET I SCRIPTET AF STEVEN H. SØNDERSKOV -AARHUSKONTORET. :: Styrer hvor mange px der scrolles horisontalt
	});
	
	$('#tS2').addClass('IE7Fix');
	$('#tS2').removeClass('IE7Fix');
	
	
	
	
});
