/* Setup jQuery
---------------------------------------------------------------- */
var $j = jQuery.noConflict();

/* 23-1-2008
/* Toogle text in search field functions
---------------------------------------------------------------- */
function focusField(f,txt){
	// Declare variable
	var field = document.getElementById(f.id);
	// Clean field, markup if text is not the same as original
	if(field.value==txt){
		field.value = '';
	}else{
		field.select();
	}
}

function blurField(f,txt){
	// Declare variable
	var field = document.getElementById(f.id);
	// Restore field if not text is original
	if(field.value==''){
		field.value = txt;
	}
}

/* Link function
---------------------------------------------------------------- */
function goToUrl(popup,url){
	// If popup is true, then open in popup, else open normal
	if(url){
		if(popup){
			window.open(url);
		}else{
			location.href = url;
		}
	}
}
function PopUp(mypage, myname, w, h, scroll){
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable';
	win = window.open(mypage, myname, winprops);

	if(parseInt(navigator.appVersion) >= 4){
		win.window.focus();
	}
}
/* Bad bad code
window.onload= initPrint;

function initPrint(){
	if (document.getElementById('printlink')){
		document.getElementById('printlink').onclick = goPrint;
		return false;
	}	
}
*/
/*
function goPrint(){
	window.print();
}
*/

function shiftIndex(current,min,max,direction){
	newIndex=(direction==-1)?(current--==min)?current=max:current--:(current++==max)?current=min:current++;
	return newIndex;
}
function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function slideShow(imagePaths){
	var imagePaths = $j('#imagePaths').val();
	var imageAlts = $j('#imageAlts').val();
	var imageTitles = ($j('#imageTitles').length>0) ? $j('#imageTitles').val() : imageAlts;
	var imageLinks = $j('#imageLinks').val();
	if(imagePaths=='')return;
	imagePaths = imagePaths.split('|');
	imageAlts = imageAlts.split('|');
	imageTitles = (imageTitles!='') ? imageTitles.split('|') : '';
	imageLinks = imageLinks.split('|');
	var argsleft = $j('#left-arr').attr('rel').split('|');
	var indexleft = parseInt(argsleft[0]);
	
	var argsright = $j('#rgt-arr').attr('rel').split('|');
	var indexright = parseInt(argsright[0]);
	
	var totalimages = parseInt(argsright[1]);
	
	if(imageLinks[indexright-1]!='')
	{
		$j('#imageLink').attr('href',imageLinks[indexright-1]);
		$j('#slideshowtitle').attr('href',imageLinks[indexright-1]);
	}else{
		$j('#imageLink').removeAttr('href');
		$j('#slideshowtitle').removeAttr('href');
	}
	
	if($j('#ImageCarousel').css('display')!='none'){
		$j('#slide2').attr('src',imagePaths[indexright-1]).attr('alt',imageAlts[indexright-1]);
		$j('#slideshowtitle').text(imageTitles[indexright-1]);
		//$j('#imageCarouselWrapper').attr('style','background:#fff url("' + imagePaths[indexright-1] + '") no-repeat;width:519px;height:327px;');
		$j('#ImageCarousel').fadeOut();	
	}else{
		$j('#ImageCarousel').attr('src',imagePaths[indexright-1]).attr('alt',imageAlts[indexright-1]).fadeIn();
		$j('#slideshowtitle').text(imageTitles[indexright-1]);
	}
	$j('#left-arr').attr('rel',shiftIndex(indexleft,1,totalimages,1) + '|' + totalimages).attr('href','?slide='+shiftIndex(indexleft,1,totalimages,1));
	$j('#rgt-arr').attr('rel',shiftIndex(indexright,1,totalimages,1) + '|' + totalimages).attr('href','?slide='+shiftIndex(indexright,1,totalimages,1));
}


/* jQuery functions
---------------------------------------------------------------- */
/* Print
---------------------------------------------------------------- */
$j(function(){
	$j('#printlink').click(function (){
		window.print();
		return false;
	});
});
/* Image carousel
---------------------------------------------------------------- */

$j(function(){
	if($j('#imagePaths').length > 0){
		if($j('#slideshow').length > 0){$j('#slideshow').fadeIn();}
		var slideInterval = setInterval("slideShow();",5000);
		var imagePaths = $j('#imagePaths').val();
		var imageAlts = $j('#imageAlts').val();
		var imageTitles = ($j('#imageTitles').length>0) ? $j('#imageTitles').val() : imageAlts;
		var imageLinks = $j('#imageLinks').val();
		if(imagePaths=='')return;
		imagePaths = imagePaths.split('|');
		imageAlts = imageAlts.split('|');
		imageTitles = (imageTitles!='') ? imageTitles.split('|') : '';
		imageLinks = imageLinks.split('|');
		$j('#left-arr').click(function (){
			clearInterval(slideInterval);
			if(imagePaths=='')return;
			var argsleft = $j('#left-arr').attr('rel').split('|');
			var indexleft = parseInt(argsleft[0]);
			
			var argsright = $j('#rgt-arr').attr('rel').split('|');
			var indexright = parseInt(argsright[0]);
			
			var totalimages = parseInt(argsleft[1]);
			
			if(imageLinks[indexleft-1]!='')
			{
				$j('#imageLink').attr('href',imageLinks[indexleft-1])
			}else{
				$j('#imageLink').removeAttr('href')
			}
			if($j('#ImageCarousel').css('display')!='none'){
				$j('#slide2').attr('src',imagePaths[indexleft-1]).attr('alt',imageAlts[indexleft-1]);
				//$j('#imageCarouselWrapper').attr('style','background:#fff url("' + imagePaths[indexleft-1] + '");width:519px;height:327px;');
				$j('#ImageCarousel').fadeOut();	
			}else{
				$j('#ImageCarousel').attr('src',imagePaths[indexleft-1]).attr('alt',imageAlts[indexleft-1]).fadeIn();
			}
			$j('#left-arr').attr('rel',shiftIndex(indexleft,1,totalimages,-1) + '|' + totalimages).attr('href','?slide='+shiftIndex(indexleft,1,totalimages,-1));
			$j('#rgt-arr').attr('rel',shiftIndex(indexright,1,totalimages,-1) + '|' + totalimages).attr('href','?slide='+shiftIndex(indexright,1,totalimages,-1));
			return false;
		});
		$j('#rgt-arr').click(function (){
			clearInterval(slideInterval);
			if(imagePaths=='')return;
			var argsleft = $j('#left-arr').attr('rel').split('|');
			var indexleft = parseInt(argsleft[0]);
			
			var argsright = $j('#rgt-arr').attr('rel').split('|');
			var indexright = parseInt(argsright[0]);
			
			var totalimages = parseInt(argsright[1]);
			if(imageLinks[indexright-1]!='')
			{
				$j('#imageLink').attr('href',imageLinks[indexright-1])
			}else{
				$j('#imageLink').removeAttr('href')
			}
			if($j('#ImageCarousel').css('display')!='none'){
				$j('#slide2').attr('src',imagePaths[indexright-1]).attr('alt',imageAlts[indexright-1]);
				//$j('#imageCarouselWrapper').attr('style','background:#fff url("' + imagePaths[indexright-1] + '") no-repeat;width:519px;height:327px;');
				$j('#ImageCarousel').fadeOut();	
			}else{
				$j('#ImageCarousel').attr('src',imagePaths[indexright-1]).attr('alt',imageAlts[indexright-1]).fadeIn();		
			}
			$j('#left-arr').attr('rel',shiftIndex(indexleft,1,totalimages,1) + '|' + totalimages).attr('href','?slide='+shiftIndex(indexleft,1,totalimages,1));
			$j('#rgt-arr').attr('rel',shiftIndex(indexright,1,totalimages,1) + '|' + totalimages).attr('href','?slide='+shiftIndex(indexright,1,totalimages,1));
			return false;
		});
	}
});

/* Auto clear textbox on focus
---------------------------------------------------------------- */
$j(function(){
	$j('.AutoClear')
		.focus(function (){if($j(this).val()==$j(this).attr('title')){$j(this).val('');}})
		.blur(function (){if($j(this).val()==''){$j(this).val($j(this).attr('title'));}});
});
/* Pop image
---------------------------------------------------------------- */
$j(function(){
	$j('.popImage').click(function (){
		/*
		var winl = (screen.width - 200) / 2;var wint = (screen.height - 200) / 2;
		newWin=window.open("","ResizeBillede","width=300,height=200,status=no,top="+wint+",left="+winl);
		doc='';
		doc+='<html><head>';
		doc+='<title>Slots- og Ejendomsstyrelsen Billedbank<\/title>';
		doc+='<style type="text/css">html,body,img{margin:0;padding:0;border:0;}<\/style>';
		doc+='<script type="text/javascript">function resPic(){img=document.images[0];h=img.scrollHeight;w=img.scrollWidth;var winl=(screen.width-w)/2;var wint=(screen.height-h)/2;window.resizeTo(w+6,h+32);window.moveTo(winl,wint);}<\/script>';
		doc+='<\/head><body onload="resPic();">';
		doc+='<img src="' + $j(this).attr('href') + '"<\/img>';
		doc+='<\/body><\/html>';
		newWin.document.write(doc);
		*/
		 var winl = (screen.width - 200) / 2;var wint = (screen.height - 200) / 2;
newWin=window.open("","ResizeBillede","width=300,height=200,status=no,top="+wint+",left="+winl);
txt='<ht'+'ml><he'+'ad><ti'+'tle>Slots- og Ejendomsstyrelsen Billedbank<\/ti'+'tle><scri';
txt+='pt language="javascript" type="text/javascript">';
txt+='function resPic(){h=document.images[0].scrollHeight;';
txt+='w=document.images[0].scrollWidth;var winl = (screen.width - w) / 2;var wint = (screen.height - h) / 2;window.resizeTo(w+6,h+32);window.moveTo(winl,wint)}<\/scri';
txt+='pt><\/he'+'ad><bo'+'dy style="overflow:hidden;';
txt+='border:0px;margin:0px"><i'+'mg src="'+$j(this).attr('href')+'" style="top:0px;left:0px;border:0px;';
txt+='" onload="resPic();"><\/bo'+'dy><\/ht'+'ml>';
newWin.document.write(txt);
newWin.document.close();
		return false;
	});
});

/* Pop window
---------------------------------------------------------------- */
$j(function(){
	$j('.pop').click(function (){
		PopUp($j(this).attr('href'),"Popped window",$j(this).attr('rel').split('|')[0],$j(this).attr('rel').split('|')[1],false);
		return false;
	});
});
/* Brevkasse
---------------------------------------------------------------- */
$j(function(){
	if($j('.brevkassesubjects').find('option:selected').attr('rel')=='1'){$j('#DropDownSlotte').show()}
	$j('.brevkassesubjects').change(function (){
		if($j(this).find('option:selected').attr('rel')=='1'){
			$j('#DropDownSlotte').show();
		}else{
			$j('#DropDownSlotte').hide();
			$j('.brevkasseslotte').find('option:first').attr('selected', 'selected');
		}
	});
});
/* Havekort links
---------------------------------------------------------------- */
$j(function(){
	$j('.popupKort').click(function (){
		PopUp($j(this).attr('href'),"Poppedwindow",980,688,false);
		return false;
	});
});
$j(function(){
	$j('.slotPopup').click(function (){
		PopUp($j(this).attr('href'),"Poppedwindow",980,688,false);
		return false;
	});
});
/* Slotselector
---------------------------------------------------------------- */
$j(function(){
	$j('#slotselector').change(function (){
		if($j(this).val()!=''){
			window.location = $j(this).val();
		}
	});
});
/* Highlight search
---------------------------------------------------------------- */
$j(function(){
	var highlight = '';hightlight = querySt('search');
	if(highlight!=''){
		highlightSearchTerms(highlight);
	}
});

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
    highlightEndTag = "</font>";
  }
  
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}


/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
  // if the treatAsPhrase parameter is true, then we should search for 
  // the entire phrase that was entered; otherwise, we will split the
  // search string so that each word is searched for and highlighted
  // individually
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }
  
  if (!document.body || typeof(document.body.innerHTML) == "undefined") {
    if (warnOnFailure) {
      alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
    }
    return false;
  }
  
  var bodyText = document.body.innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }
  
  document.body.innerHTML = bodyText;
  return true;
}

/* Arrangementer start / slut
---------------------------------------------------------------- */


/* Cookies
---------------------------------------*/
function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

/*-------------------------------------*/

/* BSC
---------------------------------------*/
$j(function(){
	$j('#map div.row').mouseover(function() {
		var head = $j('#head' + $j(this).attr('rel') + '.expand');
		if(head.attr('data-open') === '0'){
			$j(this).find('div.item').animate({'height':180},500,function (){
				head.attr('data-open','1');
				head.addClass('open');
				//head.css({'background-image':'url(/gfx/bscmapheadline_on.gif?cache=2)'});
			});
		}
	});
	
	$j('h2.expand').click(function (){
		var head = $j('#head' + $j(this).attr('rel') + '.expand');
		//if(head.attr('data-open') === '1'){
			$j('#row' + $j(this).attr('rel')).find('div.item').animate({'height':40},500,function (){
				head.attr('data-open','0');
				head.removeClass('open');
				//head.css({'background-image':'url(/gfx/bscmapheadline.gif?cache=2)'});
			});
		//}
	});
});
/*-------------------------------------*/

/* Eksempel samling
---------------------------------------*/
$j(function(){
	$j('#showall').click(function (){
		$j('#contenttrimmed').hide();
		$j('#contentfull').show();
	});
});