var userAgent = navigator.userAgent.toLowerCase();
 
// Figure out what browser is being used
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
$(function()
{
	if($('div#boxContent.kampanje').size() > 0) {
		$('div#taglineContainer').animate({opacity:0});
		//$('div#mainContentBox').css({opacity:0, display: 'block'}).animate({opacity:1});
		$('div#contentArea').css({height:'auto'});
	}
    if($.browser.safari || $.browser.chrome)
	$('div#bg img').css({height:'50%'});

    window.currentHistory = getHash();

    if(getHash() != '')
        runUrl(null, getHash());
    if($('ul#mainMenu').size() > 0)
    {
        $('ul#mainMenu a.menuItem, div.bottomBox a').click(function()
        {
            if($(this).parent().attr('id'))
                return;
            else
                runUrl($(this).attr('rel'), getHash());
                
        });
	
	$('ul#mainMenu a.mouseover').mouseover(function() {
	    $('ul#mainMenu li.activeUnder').removeClass('activeUnder');
	    $('ul#mainMenu li ul li ul li a').removeClass('activeMenuItem');
	    if($(this).parent().attr('id'))
                return;
            else
                runUrl($(this).attr('rel'), getHash());
	});
        
        $('li#bobiler > a,li#campingvogner > a, li#brukteEnheter > a, li#butikk > a').click(function()
        {
		$('li#bobiler, li#campingvogner,li#brukteEnheter,li#butikk').css({overflow: 'hidden'});
            if($(this).parent().attr('id') == 'bobiler')
                $('li#campingvogner, li#brukteEnheter, li#butikk').animate({height:28});
            if($(this).parent().attr('id') == 'campingvogner')
                $('li#bobiler, li#brukteEnheter, li#butikk').animate({height:28});
            if($(this).parent().attr('id') == 'brukteEnheter')
                $('li#bobiler, li#campingvogner, li#butikk').animate({height:28});
	if($(this).parent().attr('id') == 'butikk')
		$('li#bobiler, li#campingvogner, li#brukteEnheter').animate({height: 28});


            var $parent = $(this).parent();
            if($parent.height() > 28)
            {
		$(this).parent().css({'overflow':'hidden'});
                $parent.stop().animate({ height: 28 });
                $parent.removeClass('active');
            }
            else
            {
		$(this).parent().css({'overflow':'visible'});
                var childLength = $parent.children('ul').children().size();
                $parent.addClass('active');
                var newHeight = ((childLength+1) * 29)-2;
                $parent.stop().animate({ height: newHeight });
            }

            return false;
        });
	
	$('ul#mainMenu li ul li ul li a').click(function()
	{
	    $('ul#mainMenu li ul li ul li a').removeClass('activeMenuItem');
	    $(this).addClass('activeMenuItem');
	    $('ul#mainMenu li.activeUnder').removeClass('activeUnder');
	    $(this).parent().parent().parent().addClass('activeUnder');
	});
    }
    
    
    if(typeof window.bakgrunnsbilder != 'undefined')
    {
        
        var index = 0;
        var bakgrunnsContainer = document.getElementById('backgroundImageContainer');
	var vHeight = $(window).height();
        var interval = setInterval(function()
        {
	    
            var image = new Image();
            image.src = window.bakgrunnsbilder[index];
	    if($.browser.safari || $.browser.chrome)
		image.style.height = '50%';
            image.onload = function() {
		
                bakgrunnsContainer.appendChild(image);
		$(window).height(vHeight+1);
		$(window).height(vHeight);
		    //$('div#bg table img').css({height: '50%'});
                //$('#backgroundImageContainer').find('img').eq(0).css({ display: 'block', opacity: 1, position:'absolute', width: width, height:height}).animate({ opacity:0}, function(){ $('#backgroundImageContainer').find('img').eq(0).remove(); });
                $('#backgroundImageContainer').find('img').eq(0).remove();
		
                if(index == window.bakgrunnsbilder.length-1)
                    clearInterval(interval);
                else
                    index++;
            }
        }, 3000);   
    }
    
    $("#kartBtn").attr('href', '#mapContainer');
    $("#apningstiderBtn").attr('href', '#apningstiderInfo');
    
    $("#kartBtn").fancybox({
            'titlePosition'		: 'inside',
            'transitionIn'		: 'none',
            'transitionOut'		: 'none'/*,
            'onComplete'                : function() { initMap();},
            'onClosed'                  : function() { $('#map_canvas').html('').attr('style', 'width:500px;height:350px;'); }*/
    });
    
    $("#apningstiderBtn").fancybox({
            'titlePosition'		: 'outside',
            'transitionIn'		: 'none',
            'transitionOut'		: 'none'
    });
    initMap();
    if ( $.browser.msie ) {
	$('a.lightBoxPage').click(function() {
		window.open($(this).attr('href'), $(this).attr('title'), "width=714,height=500,scrollbars=yes,location=no,menubar=no,status=no,toolbar=no,directories=no,resizable=yes");
		return false;
	});
    }else{
	$('a.lightBoxPage').fancybox({
		'width'			: 714,
		'height'		: '65%',
		'autoScale'     	: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'			: 'iframe',
		'titleShow'		: false,
		'onComplete'		: function() {
		    var iframe = document.getElementById('fancybox-frame');
		}
	    });
    }
    

});

function activeListeners()
{
    if($('a#spesifikasjon').size() > 0)
        $('a#spesifikasjon').toggle(function() {
            $('div#contentArea').hide();
            $('div#spesifikasjonContainer').show();
            $(this).html('Beskrivelse');
            return false;
        }, function(){
            $('div#contentArea').show();
            $('div#spesifikasjonContainer').hide();
            $(this).html('Spesifikasjoner');
            return false;
        });
		
	if($("a#closeUtvidetSpesifikasjoner").size() > 0) {
		$("a#closeUtvidetSpesifikasjoner").click(function() {
			$('div#contentArea').show();
            $('div#spesifikasjonContainer').hide();
            $('a#spesifikasjon').html('Spesifikasjoner');
			return false;
		});
	}	
	
	if($('a#prisPakker').size() > 0) {
        $('a#prisPakker').click(function() {
            $('div#contentArea').hide();
            $('div#prispakkerContainer').show();
			$('div#spesifikasjonContainer').hide();
            return false;
        });
		$("a#closePrisPakker").click(function(){
			$('div#contentArea').show();
            $('div#prispakkerContainer').hide();
			$('div#spesifikasjonContainer').hide();
			return false;
		});
	}
    
    var childCount = $('ul#childMenu li').size();
    var currentSlide = 0;
    var slideAmount = Math.ceil(childCount/4);
    var $childSlider = $('ul#childMenu');
    if(childCount > 4)
    {
        $('a#prevChild').click(function()
        {
            if(currentSlide == 0)
                currentSlide = slideAmount-1;
            else
                currentSlide = currentSlide-1;
            $childSlider.animate({ left: -(currentSlide*448) });
            return false;
        });
        $('a#nextChild').click(function()
        {
            if(currentSlide == slideAmount-1)
                currentSlide = 0;
            else
                currentSlide = currentSlide+1;
            $childSlider.animate({ left: -(currentSlide*448) });
            return false;
        });
    }
    else {
        $('a#nextChild').click(function(){ return false; });
        $('a#prevChild').click(function(){ return false; });
    }
    
    
    $('a[rel=caravan_gallery]').fancybox({
        'transitionIn'  : 'none',
        'transitionOut'  : 'none',
        'titlePosition' : 'over',
        'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
            return '<span id="fancybox-title-over">Bilde '+(currentIndex+1)+' av '+currentArray.length +' - Bilde kan fravike fra aktuell modell</span>';
        }
    });
    
    $('a[rel=caravan_ansatte]').fancybox({
        'transitionIn'  : 'none',
        'transitionOut'  : 'none',
        'titlePosition' : 'inside',
        'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
	    var arr = title.split(':');
	    
            return '<span id="fancybox-title-inside" style="text-align:left"><strong>Navn:</strong> '+arr[0]+'<br /><strong>Tittel:</strong> '+arr[1]+'<br /><strong>Telefon:</strong> '+arr[2]+'</span>';
        }
    });
    
    /* Bruce: start */
    $('a[rel=caravan_produktgalleribilder]').fancybox({
        'transitionIn'  : 'none',
        'transitionOut'  : 'none',
        'titlePosition' : 'inside',
        'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
	    var arr = title.split(':');
	    
            return '<span id="fancybox-title-inside" style="text-align:left">'+arr[0]+'</span>';
        }
    });
    /* Bruce: slutt */
    
    $('a#plantegningBtn').fancybox({
        'transitionIn'  : 'none',
        'transitionOut'  : 'none',
	'titleShow' : false,
        
        'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
            return '<span id="fancybox-title-over">'+ title + ' - Bilde kan fravike fra aktuell modell</span>';
        }
    });
    
    $('div#undermodellerSlider a').click(function()
    {

	    runUrl($(this).attr('rel'), getHash());
	    return false;
    });
    
    var $undermodeller = $('div#undermodellerSlider a');
    var $uSlider = $('div#undermodellerSlider');
    var currentUIndex = 0;
    var leftUWidth = 435;
    var endIndex = Math.floor($undermodeller.size()/3);
    
    if($undermodeller.size() > 0) {
	$('a#blackLeft').click(function() {
	    
	    if(currentUIndex == 0)
		currentUIndex = endIndex;
	    else
		currentUIndex--;
		
	    $uSlider.stop().animate({left: -(currentUIndex*leftUWidth)});
	    return false;
	});
	$('a#blackRight').click(function() {
	    
	    if(currentUIndex == endIndex)
		currentUIndex = 0;
	    else
		currentUIndex++;
	    
	    $uSlider.stop().animate({left: -(currentUIndex*leftUWidth)});
	    return false;
	});
    }
    
    var $leiebiler = $('div#utleieBilerWrapper a');
$leiebiler.click(function(){
	$leiebilTittel = $(this).find('span').html();
	$('a#foresporselBtn').remove();
	$('h3#title').remove();
	$image = $(this).find('img.bigImage');
	if($image.size() > 0)
	{
		if($('div#utleieImageContainer').size() == 0)
		{
			$('div#mainContent.utleie div#mainContentContext div.right').append('<div id="utleieImageContainer" style="position:absolute;top:0;left: 0;"></div>');
			$('div#utleieImageContainer').click(function(){
				$(this).hide();
				$('a#foresporselBtn').remove();
				$('h3#title').remove();
			});
		}
		$('div#utleieImageContainer').html('<img src="'+$image.eq(0).attr('src')+'" alt=""  />');
		$('div#utleieImageContainer, div#utleieImageContainer img').show();
		if($('h3#title').size() == 0)
			$('div#mainContent.utleie div#mainContentContext div.left').append('<h3 id="title">'+$leiebilTittel+'</h3>');
		if($('a#foresporselBtn').size() == 0)
			$('div#mainContent.utleie div#mainContentContext div.left').append('<a href="mailto:vestcaravanutleie@bergen-caravan.no?subject=Jeg vil leie en '+$leiebilTittel+'" title="Send forespørsel" id="foresporselBtn">Send forespørsel</a>');
	}
});
    var $lSlider = $('div#utleieBilerSlider');
    var currentLIndex = 0;
    var leftLWidth = 498;
    var endLIndex = Math.floor($leiebiler.size()/3);
    if($leiebiler.size() > 0)
    {
	$('a#forrigeUtleieBil').click(function()
	{
	    if(currentLIndex == 0)
		currentLIndex = endLIndex;
	    else
		currentLIndex--;
		
	    $lSlider.stop().animate({left: -(currentLIndex*leftLWidth)});
	    return false;
	});
	$('a#nesteUtleieBil').click(function()
	{
	    if(currentLIndex == endLIndex)
		currentLIndex = 0;
	    else
		currentLIndex++;
	    
	    $lSlider.stop().animate({left: -(currentLIndex*leftLWidth)});
	    return false;
	});
    }
    
    var $ansatte = $('div#ansatteWrapper a');
    var $aSlider = $('div#ansatteSlider');
    var currentAIndex = 0;
    var topAHeight = 207;
    var endAIndex = Math.floor($ansatte.size()/6);
    
    if($ansatte.size() > 6)
    {
	$('a#ansatteUpBtn').click(function() {
	    if(currentAIndex == 0)
		currentAIndex = endAIndex;
	    else
		currentAIndex--;
		
	    $aSlider.stop().animate({top: -(currentAIndex*topAHeight)});
	    return false;
	});
	$('a#ansatteDownBtn').click(function() {
	    
	    if(currentAIndex == endAIndex)
		currentAIndex = 0;
	    else
		currentAIndex++;
		
	    $aSlider.stop().animate({top: -(currentAIndex*topAHeight)});
	    return false;
	});
    }
    
    /* Bruce: start */
    var $produktgalleribilder = $('div#produktgalleribilderWrapper a');
    var $pgbSlider = $('div#produktgalleribilderSlider');
    var currentPGBIndex = 0;
    var topPGBHeight = 207;
    var endPGBIndex = Math.floor($produktgalleribilder.size()/6);
    
    if($produktgalleribilder.size() > 6)
    {
	$('a#produktgalleribilderUpBtn').click(function() {
	    if(currentPGBIndex == 0)
		currentPGBIndex = endPGBIndex
;
	    else
		currentPGBIndex--;
		
	    $pgbSlider.stop().animate({top: -(currentPGBIndex*topPGBHeight)});
	    return false;
	});
	$('a#produktgalleribilderDownBtn').click(function() {
	    
	    if(currentPGBIndex == endPGBIndex
)
		currentPGBIndex = 0;
	    else
		currentPGBIndex++;
		
	    $pgbSlider.stop().animate({top: -(currentPGBIndex*topPGBHeight)});
	    return false;
	});
    }
    /* Bruce: slutt */
    
    $('div#utleieBilerWrapper a').click(function() {
	$('div#utleieBilerWrapper a').removeClass('active');
	$(this).addClass('active');
	var merke = $(this).find('span').html();
	var emailAdr = $('a#UtleieBtn').html();
	$('a#UtleieBtn').replaceWith('<a href="mailto:'+emailAdr+'?subject=Jeg vil leie en '+merke+'" title="'+emailAdr+'" id="UtleieBtn">'+emailAdr+'</a>');
	//$('a#UtleieBtn').attr('href', 'mailto:'+emailAdr+'?subject=Jeg vil leie en '+merke);
	return false;
    });
    
    $('a#UtleieBtn').click(function() {
	if($(this).attr('href') == '#') {
	    alert('Du må velge et merke!');
	    return false;
	}
    });
}

function getHash()
{
    return window.location.hash.replace('#','');
}

function initMap()
{
    var latlng = new google.maps.LatLng(60.51029493159766, 5.3465330600738525);
    var myOptions = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    var marker = new google.maps.Marker({
      position: latlng, 
      map: map, 
      title:"Bergen Caravan - Hylkjeflaten 1"
    });
}

function runUrl(pageId, hash)
{
    if(window.siteRequest != undefined)
	window.siteRequest.abort();
    if($('div#mainContentBox:hidden').size() > 0)
        $('div#mainContentBox').fadeIn(250, function()
        {
            $('img#ajaxloader').show();
	    $('div#jsContentWrapper').hide();
            window.siteRequest = $.get('/bergencaravan/main.php', { ajax: true, pageId : pageId, href : hash }, function(data)
            {
                if(data != null)
                {
                    
                    
		    if(data.classname){
			$('div#mainContentBox').attr('class','');
			$('div#mainContentBox').addClass(data.classname)
		    }
		    
		    if(data.classname == 'Utleiebiler'){
			$('div#mainContentBox').animate({left:245});
			$('div#mainContentBoxContentArea').animate({width:648}, function() {
			    $('img#ajaxloader').show();
			    $('div#jsContentWrapper').hide();
			    if(data.template != null || data.template != '')
				$('div#boxContent').html(data.template);
		
			    if(data.title != null || data.title != '')
				$('h2#contentTitle').html(data.title);
				
			    if(data.content != null || data.content != '')
				$('div#contentArea').html(data.content);
			    $('a#UtleieBtn').attr('href', '#');
			    activeListeners();
			});
		    } else {
			$('div#mainContentBox').animate({left:347});
			$('div#mainContentBoxContentArea').animate({width:548}, function() {
			    $('img#ajaxloader').hide();
			    $('div#jsContentWrapper').show();
			    if(data.template != null || data.template != '')
				$('div#boxContent').html(data.template);
		
			    if(data.title != null || data.title != '')
				$('h2#contentTitle').html(data.title);
				
			    if(data.content != null || data.content != '')
				$('div#contentArea').html(data.content);
				$('a#UtleieBtn').attr('href', '#');
			    activeListeners();
			});
			
		    }
                    
                    
                    /*if(typeof data.boxImage != 'undefined' && data.boxImage != '') {
                        $('img#boxImagePlaceholder').attr('src', data.boxImage);
                        if($('img#boxImagePlaceholder').attr('src') != '')
                            $('div#boxImage').show();
                    }
                    else
                        $('div#boxImage').hide();*/
                }
                
                if($('#taglineContainer').is(':visible'))
                    $('#taglineContainer').fadeOut();
                
                if($('a.otherNavigation').size() > 0)
                $('a.otherNavigation').click(function()
                {
                    runUrl($(this).attr('rel'), getHash());
                    return false;
                });
                
                
                
            }, "json");
        });
    else {
        $('img#ajaxloader').show();
        $('div#jsContentWrapper').hide();
        window.siteRequest = $.get('/bergencaravan/main.php', { ajax: true, pageId : pageId, href : hash }, function(data)
        {
            if(data != null)
            {
                if(data.classname){
			$('div#mainContentBox').attr('class','');
			$('div#mainContentBox').addClass(data.classname)
		    }
		    
		    if(data.classname == 'Utleiebiler'){
			$('div#mainContentBox').animate({left:245});
			$('div#mainContentBoxContentArea').animate({width:648}, function() {
			    $('img#ajaxloader').hide();
			    $('div#jsContentWrapper').show();
			    if(data.template != null || data.template != '')
				$('div#boxContent').html(data.template);
		
			    if(data.title != null || data.title != '')
				$('h2#contentTitle').html(data.title);
				
			    if(data.content != null || data.content != '')
				$('div#contentArea').html(data.content);
				$('a#UtleieBtn').attr('href', '#');
			    activeListeners();
			});
		    } else {
			$('div#mainContentBox').animate({left:347});
			$('div#mainContentBoxContentArea').animate({width:548}, function() {
			    $('img#ajaxloader').hide();
			    $('div#jsContentWrapper').show();
			    if(data.template != null || data.template != '')
				$('div#boxContent').html(data.template);
		
			    if(data.title != null || data.title != '')
				$('h2#contentTitle').html(data.title);
				
			    if(data.content != null || data.content != '')
				$('div#contentArea').html(data.content);
				$('a#UtleieBtn').attr('href', '#');
			    activeListeners();
			});
			
		    }
		    
            }
            if($('#taglineContainer').is(':visible'))
                $('#taglineContainer').fadeOut();
            
            if($('a.otherNavigation').size() > 0)
                $('a.otherNavigation').click(function()
                {
                    runUrl($(this).attr('rel'), getHash());
                    return false;
                });
                
        }, "json");
    }    
}

(function(){
	var db=document.body;
	var img=$('#backgroundImageContainer img').first();
	

	var dbsize={}; //needed to store body size
	var imgsrc=img.src; //needed to store images src
	var keyStop=function(e){
		var e=window.event||e||{};
		var tag=e.target.tagName.toLowerCase();
		if(tag!='textarea'&&!(tag=='input'&&(e.target.type=='text'||e.target.type=='password'))){ //are the user not writing?
			if(e.keyCode==32||e.keyCode==39||e.keyCode==40){ //Did he press any of the "scrolling-keys"? (down, right, and space key)
				if(e.preventDefault)e.preventDefault();
				else e.returnValue=false;
			}
		}
	}

	if(this.addEventListener)window.addEventListener('keydown',keyStop,false);
	else window.attachEvent('onkeydown',keyStop);

	$(window).resize(function() {
		window.scrollTo(0,0);
		if(img.complete){ //check if image has loaded
			if(db.clientWidth!=dbsize.w||db.clientHeight!=dbsize.h||img.src!=imgsrc){ //check if size or img size has changed
				imgsrc=img.src; //store current src
				dbsize.w=db.clientWidth; //store current body width
				dbsize.h=db.clientHeight; //store current body height

				var newwidth=Math.round(dbsize.h*(img.offsetWidth/img.offsetHeight)); //calculate new width based on height

				img.style.width=(dbsize.w>newwidth?dbsize.w:newwidth)+'px'; //use the largest value of body-width and newwidht
				//and this is the real trick: if there's no specified height, the height is automaticly calculated relative to the with
			}
		}
	});
})();
