
//document.cookie = 'js=hest er best;path=/';
$(function() {

	var initGrassPos;


	if($('.level-0').find('li.activeParent').length){
		$('.activeGrass').remove();
		$this = $('.level-0 li.activeParent a');

		var aWidth = ($this.outerWidth()/2.5);
		$siblings = $this.parents('ul').find('a');

		//var $this = $(this);
		var exit = false;
		$siblings.each(function(){
			$sib = $(this);
			if($this.attr('href')!=$sib.attr('href') && !exit){
				aWidth += $sib.outerWidth();
			}else
				exit = true;
		});

		//console.log($siblings.length);
		//var position = $(this).parents('ul').css('padding-left');
		//position = position.replace('px','');
		var position = parseInt(position) + aWidth;
		//console.log(position);

		//positionGrass(aWidth);
		$('#gress').css({'visibility': 'visible', 'backgroundPosition': aWidth+'px 0px'});
		initGrassPos = aWidth;

	}

	function positionGrass(position){
		$('#gress').stop();
		$('#gress').css({visibility:'visible'});
			/*$('#gress').animate({
				backgroundPosition: position+'px 0'
			},500,function(){
			});*/
			$('#gress').css('backgroundPosition', position+'px 0px');

	}


  

  if($.browser.msie && $.browser.version=="6.0"){
  	document.cookie = 'menu=on;path=/';
  }

  // slideshow

  var slide_buttons = $('.slide_button');
  slide_buttons.bind('click', function(ev) {
    var t = $(this);

    //var ul = t.parent('div').find('ul');
    var ul = t.nextAll('ul:first');
    if(ul.is(':visible')) {
      ul.slideUp("fast");
      t.removeClass('heading_minus').addClass('heading_plus');
    } else {
      ul.slideDown("fast");
      t.removeClass('heading_plus').addClass('heading_minus');
    }

    slide_buttons.not(t).each(function() {
        $(this)
            .removeClass('heading_minus').addClass('heading_plus')
            //.siblings('ul:first').slideUp("fast");
             .parent('div').find('ul').not(ul).slideUp("fast");
    });

		//ul.show();  // TEMP HACK BY HERMUND 14.04.2011

    return false;
  }).css('cursor', 'pointer');


  $('#main_menu>li>span>span>ul').hide();
    $('#nav>li').mouseover(function(){
    	// check that the menu is not currently animated
      if ($('#nav ul:animated').size() == 0) {
      	// create a reference to the active element (this)
        // so we don't have to keep creating a jQuery object
        $heading = $(this);
        // create a reference to visible sibling elements
        // so we don't have to keep creating a jQuery object
        $expandedSiblings = $heading.siblings().find('ul:visible');
        if ($expandedSiblings.size() > 0) {
        	$expandedSiblings.slideUp(200, function(){
          	$heading.find('ul').slideDown(400);
        	});
         } else {
           $heading.find('ul').slideDown(400);
         }
       }
    });



    var ajaxMenuManager = $.manageAjax.create('ajaxMenu',{
    	queue : false,
    	cacheResponse :true,
    	maxRequests:1,
    	abortOld:true,
    	preventDoubbleRequests: true
    });


  var remove = true;
  var prevLevel;
  var saveMenu = "";
  var interrupted = false;
  var hasReceivedData = false;
  var currentLoaded = null;
  var prevId;
  var menuOpen = false;
  var xhr;

 	var active;
 	var prevActive;
 	var timer;
 /*
Henter nivåer i menyen.
 */

$('#topMenu a').live('mouseover', function(event){


	if(timer){
		clearTimeout(timer);
	}

	//timer = setTimeout("loadMenuPart($(this))",1000);
	elem = $(this);

	timer = setTimeout(function(){
		if($.browser.msie && $.browser.version=="6.0"){
			return;
		}

		if(!menuOpen){
			if(elem.parents('li:first').hasClass('activeParent') && elem.parents('ul:first').hasClass('level-0')){
				$('.hidden').css('display','block');
				return;
			}
		}

		menuOpen = true;

		var level;

		var parentUl = elem.parents('ul').attr('class');

		if(hasReceivedData){
			interrupted = true;
		}

		remove = false;

		var values = href2array(elem.attr("href"));

		if(prevActive == null){
			prevActive = values['id'];
		}else{
			prevActive = active;
		}

		var active = values['id'];


		var re = new RegExp('[a-z]-([0-9])');
		var m = re.exec(parentUl);
		if(m!=null){
			level = m[1];
		}


		if(xhr != undefined){
			xhr.abort();
			xhr = null;
		}


		if(prevLevel==undefined){
			var temp = $('#topMenu ul:last').attr('class');
			m = re.exec(temp);
			prevLevel = m[1];
		}

		//artikkel = avbryt og fjern åpne nivåer under

		if(elem.attr('rel')!="it_13" && elem.attr('rel')!="it_14"){
			setTimeout(function(){
				if(prevActive==active){
					removeChildren(values['id'], parseInt(level));
				}
			},200);
			$('.alevel'+level).parent().removeClass('activeParent');
			$('.alevel'+level).remove();
			return;
		}

		$('.alevel'+level).parent().removeClass('activeParent');

		$this = elem;
		var params;


		params = "&menuId="+values['id'];


		if($.cookie("menuId")!=null){
			params +="&id="+$.cookie("menuId");
		}
		else
			params +="&id=0";

		var ajax_url    = 'ajax.asp';
		var ajax_params = 'ajax_action=1'+params;



		xhr = $.ajax({
			type: "POST",
			cache: false,
			url: ajax_url,
			async:true,
			data: ajax_params,
			error: function(){
					//Handle errors?
			},
			success: function(msg){
				hasReceivedData = true;
				if($('.loaded_'+values['id']).length){
					if(!$('.loaded_'+values['id']).hasClass("perm")){
						$('.loaded_'+values['id']).remove();
					}else{
						if($('.loaded_'+values['id']).length>1){
							return;
						}
					}
				}else{
					if(prevLevel==0 || prevLevel>level){
						removeChildren(values['id'], level);
					}
				}
				/*Navigerer på samme nivå. Forrige må fjernes*/
				if(prevLevel==level){
					removeChildren(prevId, level);
				}

				if(prevLevel>level){
					hidePermaLevels(level);
				}

				prevLevel = level;
				if(msg=='ajax_error'){
					$('.alevel'+level).remove();
					return;
				}
				$('not(.perm .alevel'+level+')').remove();

				if($this.parent().find('.activeArrow').length==0){
					$('.alevel'+level).each(function(){
						if($(this).hasClass('rem'))
							$(this).remove();
						if($(this).hasClass('.alevel0'))
							$(this).hide();
					});
					$this.parent().addClass('activeParent').append('<div class="activeArrow alevel'+level+' rem"><img src="/gfx/active'+level+'.png" alt="" /></div>');
				}

				$this.parents('ul:first').after(msg);
				prevId = values['id'];


				interrupted = false;
				hasReceivedData = false;

			}
		});

	},200);
});


	$('#topMenuWrapper').live('mouseover', function(event){
		remove = false;
	});


	$(':not(#topMenuWrapper)').live('mouseover', function(){
		remove = true;
	});

	$('#topMenuWrapper ul').live('mouseout', function(){
		setTimeout(function(){
			if(remove){
				$('#topMenuWrapper').find('ul[class*=loaded_]').each(function(){
					if($(this).hasClass('perm') || $(this).hasClass('hidden')){
						//saveMenu += $(this).html();
					}else{
						$(this).remove();
						menuOpen = false;
					}
				});
				$('ul.perm').each(function(){
					if(!$(this).hasClass('hidden'))
						$(this).show();
				});
				prevLevel = undefined;
				$('.rem').remove().parent();
			}
		},1000);
		remove = true;
	});

	function hidePermaLevels(level){
		for(var i=5;i>level;i--){
			if($('ul.level-'+i).length){
				if($('ul.level-'+i).hasClass('perm')){
					$('ul.level-'+i).hide();
				}
			}
		}
	}

	function removeChildren(catId, level){
		//console.log(catId);
		for(var i=5;i>level;i--){
			if($('ul.level-'+i).length>1){
				$('ul.level-'+i).each(function(){
					if(!($(this).hasClass('perm') || $(this).hasClass('hidden'))){
						$(this).remove();
					}
				});
			}
			else if($('ul.level-'+i).length==1){
				if(!($('ul.level-'+i).hasClass('perm') || $('ul.level-'+i).hasClass('hidden'))){
					$('.level-'+i).remove();
				}
			}
		}
	}
	var stillNavigating = false;
	$('#topMenu ul.level-0 li a').bind('mouseover', function(event){
		//event.stopPropagation();

		var aWidth = ($(this).outerWidth()/2.5);
		$siblings = $(this).parents('ul').find('a');

		$('#gress').stop();

		var $this = $(this);

		stillNavigating = true;
		var exit = false;
		$siblings.each(function(){
			if($(this).attr('href')!=$this.attr('href') && !exit){
				aWidth += $(this).outerWidth();
			}else
				exit = true;
		});

		//console.log($siblings.length);
		//var position = $(this).parents('ul').css('padding-left');
		//position = position.replace('px','');
		var position = parseInt(position) + aWidth;
		//console.log(position);

		if(event.type == 'mouseover'){
			positionGrass(aWidth);
		}

	});

	$('#topMenuWrapper ul,li,a').live('mouseover mouseout', function(event){
		event.stopPropagation();

		if(event.type == 'mouseover'){
			if($(this).get(0).tagName.toLowerCase()!='ul'){
				stillNavigating = true;
				return;
			}
			if($(this).hasClass('level-0') && !menuOpen){
				$('.hidden').css('display','block');
				//$('li.active').addClass('tempActive');
			}
		}
		else if(event.type == 'mouseout'){
			stillNavigating = false;
			setTimeout(function(){
				if(!stillNavigating && remove){
					$('.hidden').css('display','none');
					//$('li.active').removeClass('tempActive');
					//$('#gress').css({visibility:'hidden', backgroundPosition:'0 0'});
					if(initGrassPos!=undefined){
						positionGrass(initGrassPos);
					}
				}
			},500);

		}
		remove = false;
	});



	/*
	$('#topMenuWrapper').live('mouseout mouseover', function(event){

		if(event.type=='mouseout'){
			stillNavigating = false;
			setTimeout(function(){
				if(!stillNavigating && remove)
					$('#gress').css({visibility:'hidden', backgroundPosition:'0 0'});
			},500);
		}else
			stillNavigating = true;
	});
	*/

	$('#menuSwitch').click(function(){
		$menuSwitch = $("#menuSwitchCB");
		if($menuSwitch.hasClass("on")){
			$menuSwitch.attr('src','/gfx/menuSwitch.png')
			document.cookie = 'menu=off;path=/';
		}else{
			$menuSwitch.attr('src','/gfx/menuSwitch_on.png');
			document.cookie = 'menu=on;path=/';

		}
		$menuSwitch.toggleClass('on off');
		window.location.reload();
	});

});




function href2array(href) {
	var array = [];

	if(href && href.indexOf("?") != -1) {
		var querystring;

		querystring = href.split("?")[1];
		querystring = querystring.split("&");

		for (var i=0; i<querystring.length; i++) {
			var pair = querystring[i].split("=");
			array[pair[0]] = pair[1];
		}
	}

	return array;
} // href2array


$.fn.slideShow = function(slides_in_page) {
    var slide_me = $(this);
    var num_pages = Math.ceil(slide_me.find('td').length / slides_in_page);
    var page = 1;
    checkPages();

    $('.slide_overflow').css('width', slide_me.find('td:first').outerWidth(true) * slides_in_page+"px" );

    $('#nav_left, #nav_right').bind('click', function(ev) {
        var move_px = slide_me.find('td:first').outerWidth(true) * slides_in_page;
        if($(this).is('#nav_right')) {
          move_px = move_px * -1;
          page++;
        } else {
          page--;
        }


        slide_me.animate({ marginLeft: parseInt(slide_me.css('marginLeft').replace('px', '')) + move_px+"px" }, 500);
        checkPages();
        return false;


    });

    function checkPages() {
      if(page == 1) {
       $('#nav_left').css({ visibility: 'hidden' });
      } else {
        $('#nav_left').css({ visibility: 'visible' });
      }

      if(page == num_pages) {
       $('#nav_right').css({ visibility: 'hidden' });
      } else {
        $('#nav_right').css({ visibility: 'visible' });
      }
    }

  // end slideshow
};

$(window).load(function() {

  if($('#slide_me').length) {
    $('#slide_me').slideShow(4);
  }

  if($('#slide_me2').length) {
    $('#slide_me2').slideShow(5);
  }

  $('#main_menu').children('li').each(function(i, li) {
    var sub = $(this).children('.submeny');
    var width = $(this).find('a').outerWidth() + $(this).find('span').outerWidth();
    var height = $(this).height();

    var ie_x = 0;
    var ie_y = 0;

	  if(!$('#ie_browser').length) {
	     if($(this).is('#line5')) {
		      sub.css({ marginLeft: (width - 20 + ie_x) + "px", marginTop: (-16 + ie_y )+"px" });
	     } else if($(this).is('#line6')) {
		      sub.css({ marginLeft: (width - 50 + ie_x) + "px", marginTop: (-122 + ie_y)+"px" });
	     } else {
		      sub.css({ marginLeft: (width - 20 + ie_x) + "px", marginTop: (-height - 4 + ie_y)+"px" });
	     }
	   } else {
	     sub.css({ marginLeft: parseInt(sub.css('marginLeft').replace('px', '')) - 35 + "px" });
	   }
      sub.find('li > a').each(function(j, s) {
          $(this).closest('li').css({ marginTop: 15 * j+"px" });
      });

	  sub.css({ visibility: 'hidden' });

  });


$('#main_menu').children('li').children('a').bind('click show', function(ev) {

	var active = $(this).closest('.line').attr('id');
	var span = $(this).closest('li').children('span');
	var img = span.find('img');

	var active = span.find('img').attr('src').replace('passive', 'active');
	img.attr('src', active);

	var s = $(this).closest('li').find('.submeny');

	if (ev.type=="show"){
	 s.css({ visibility: 'visible' });
	}

  $('.submeny').not(s).each(function() {
		$(this).css({ visibility: 'hidden' });
		var passive = $(this).closest('li').children('span').find('img').attr('src').replace('active', 'passive');
		$(this).closest('li').children('span').find('img').attr('src', passive);
	});

  var temp = $('.submeny:visibility').clone();
	temp.css({ float:'left', display:'block', height: 'auto' }).removeClass('submeny').removeClass('line1');
	temp.children('li').css({ margin: 0 });
	$('body').append(temp);

	var height = temp.innerHeight();
	temp.remove();

  if($('#mwrapper').height() < height) {
    $('#mwrapper').css('height', (height + 35)+'px');
  }

  if(ev.type == 'show') {
	 return false;
	}

});

  /* menu on page load */
   if($('#r_active').length) {
      var r = $('#r_active').val();
      $('#m_'+r).trigger('show');

    }

  /* end menu on page load */


});


jQuery.extend(jQuery.expr[':'], {
  visibility: function(a) {
    return jQuery(a).css('visibility') === 'visible';
  }
});

/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});





jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;

			if (jQuery.isFunction(label)) {
				if (!times)
					times = fn;
				fn = label;
				label = interval;
			}

			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0)
				times = 0;

			times = times || 0;

			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

			if (!timers[label])
				timers[label] = {};

			fn.timerID = fn.timerID || this.guid++;

			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};

			handler.timerID = fn.timerID;

			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);

			this.global.push( element );

		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;

			if ( timers ) {

				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}

					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}

				for ( ret in timers ) break;
				if ( !ret )
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});
