// INITIALIZE HIGHSLIDE

//hs.graphicsDir = '/highslide/';

/*
hs.fadeInOut = true;
hs.showCredits = 0;
hs.padToMinWidth = true;
hs.allowMultipleInstances = false;
hs.transitions = ['expand', 'crossfade'];

// normal options
var normalOptions = {
	outlineType: 'rounded-white'
};


if (hs.registerOverlay) {
	hs.registerOverlay({
		thumbnailId: 'null',
    	overlayId: 'controlbar',
    	position: 'top right',
    	hideOnMouseOut: true
	});
}


// is initialized internally.
if (hs.addEventListener && hs.Outline) hs.addEventListener(window, 'load', function () {
	new hs.Outline('rounded-white');
	new hs.Outline('glossy-dark');
});
*/

jQuery(document).ready(function($){
	if(top.functionQueue){
		//alert("functionQueue: " + top.functionQueue);
		for(var i=0; i<functionQueue.length; i++){
			functionQueue[i]($);
		}
	}
	
	//onChange event handler to enable navigation via dropdown element
	$("#dtnSelect").change(function(){
		document.location.href = $(this).find("option:selected").attr("value");
	});
	
	//Initialize video players
	$(".video-player").each(function(){
		$(this).flash({ 
			swf: '/media/system/swf/video_player.swf',
			width: 626,
			height: 353,
			flashvars: {
				videoURL: $.trim($(this).find(".url").text())
			}
		});
	});
	
	var $newsSubmit = $("#press-filter .press-filter-submit");
	var wrappedElm = $newsSubmit.get(0);
	$newsSubmit.click(function(e){
		//Init function for elements that get returned by ajax request
		//$('body').scrollTop(600);
		
		function initSearchResult(f, html){
			$("#per_page").change(function(){
				$.ajax({
					url: top.hlp_newsResultAjaxUrl,
					data: {perPage:$("#per_page").val()},
					cache:false,
					success: function(html){
						
						successFunction(html);
						//$("#results").html(html);
						//f(f); //call this function (initSearchResult) again
						
					}
				});
			});
			$(".pager .prev").click(function(e){
				$.ajax({
					url: top.hlp_newsResultAjaxUrl,
					data: {move:"back"},
					cache:false,
					success: function(html){
						successFunction(html);
					}
				});
				//e.preventDefault();
			});
			$(".pager .next").click(function(e){
				$.ajax({
					url: top.hlp_newsResultAjaxUrl,
					data: {move:"fore"},
					cache:false,
					success: function(html){
						successFunction(html);
					}
				});
				//e.preventDefault();
			});
			
			$(".pager li:not(.prev, .next) a").click(function(){
				//alert($(this).text());
				$.ajax({
					url: top.hlp_newsResultAjaxUrl,
					data: {move:$(this).text()},
					cache:false,
					success: function(html){
						successFunction(html);
					}
				});
				//e.preventDefault();
			});
			
			$(".result-header h3 a, .result-content p a").click(function(e){
				var href = $(this).attr("href");
				var concat = "?";
				if(href.indexOf("?") > -1){
					concat = "&";
				}
				href = href + concat + "fromSearch=true";
				top.location.href = href;
				e.preventDefault();
			});
		}
		
		//Callback for ajax request
		function successFunction(html){
			//Insert ajax response into DOM
			$("#results").html(html);
			//Init elements received via ajax
			initSearchResult(initSearchResult, html);
		}
		
		//Ajax submit of the query
		var containsDefaultText = $("#search-terms").hasClass("example"); //The class "example" is set by a function defined in general.js line 410

		$.ajax({
			url: top.hlp_newsResultAjaxUrl,
			data: {	searchTerms:  containsDefaultText ? "" : $("#search-terms").val(),
					category:$("#press-filter .field-select-category select").val(),
					period:$("#press-filter .field-select-period select").val(),
					fromCache:wrappedElm.fromCache},
			cache:false,
			success: function(html){
				successFunction(html);
				//$("#results").html(html);
				//initSearchResult(initSearchResult);
			}
		});
		if(wrappedElm.fromCache){
			//delete flag on element
			wrappedElm.fromCache=false;
		}
		e.preventDefault();
	});
	$newsSubmit.parents("form:first").submit(function(e){
		$newsSubmit.click();
		e.preventDefault();
	});
	$newsSubmit.click();//Submit press query for default display of all news
	
	$newsSubmit.mouseup(function(){
		$('html, body').animate({scrollTop:580}, 500);
	});
	
	$('#search-terms').keypress(function(event) {
		if (event.which == '13') {
			$('html, body').animate({scrollTop:580}, 500);
	    }
	});
	
	
 




  $eventsSubmit = $("#event-search .event-search-submit");
  $eventsSubmit.mouseup(function(){
		$('html, body').animate({scrollTop:580}, 500);
	});
  $("#key-word").keypress(function(event) {
		if (event.which == '13') {
			$('html, body').animate({scrollTop:580}, 500);
	    }
	});
	$eventsSubmit.click
  (
    function(e)
    {
  		//Init function for elements that get returned by ajax request
  		function initSearchResult(f, html)
      {
        $("#per_page").change
        (
          function()
          {
            $.ajax
            (
              {
                url: top.hlp_eventResultAjaxUrl,
                data:
                {
                  perPage: $("#per_page").val(),
                  keyWord: containsDefaultText ? "" : $("#key-word").val(),
          				eventType: $("#event-search .field-event-type select").val(),
          				venue: $("#event-search .field-event-venue select").val(),
          				period: $("#event-search .field-event-date select").val()
                },
      					cache:false,
      					success: function(html)
                {
      						successFunction(html);
      						//$("#results").html(html);
      						//f(f); //call this function (initSearchResult) again
      					}
      				}
            );
  		    }
        );
  			$(".pager .prev").click
        (
          function(e)
          {
  				  $.ajax
            (
              {
      					url: top.hlp_eventResultAjaxUrl,
      					data:
                {
                  perPage: $("#per_page").val(),
                  keyWord: containsDefaultText ? "" : $("#key-word").val(),
          				eventType: $("#event-search .field-event-type select").val(),
          				venue: $("#event-search .field-event-venue select").val(),
          				period: $("#event-search .field-event-date select").val()
                },
      					cache:false,
      					success: function(html)
                {
      						successFunction(html);
  					     }
  				    }
            );
  				  //e.preventDefault();
  			  }
        );
  			$(".pager .next").click
        (
          function(e)
          {
  				  $.ajax
            (
              {
      					url: top.hlp_eventResultAjaxUrl,
      					data:
                {
                  perPage: $("#per_page").val(),
                  keyWord: containsDefaultText ? "" : $("#key-word").val(),
          				eventType: $("#event-search .field-event-type select").val(),
          				venue: $("#event-search .field-event-venue select").val(),
          				period: $("#event-search .field-event-date select").val()
                },
      					cache:false,
      					success: function(html){
      						successFunction(html);
      					}
      				}
            );
  				  //e.preventDefault();
  			  }
        );
  			
  			$(".pager li:not(.prev, .next) a").click
        (
          function()
          {
    				$.ajax
            (
              {
      					url: top.hlp_eventResultAjaxUrl,
      					data:
                {
                  perPage: $("#per_page").val(),
                  keyWord: containsDefaultText ? "" : $("#key-word").val(),
          				eventType: $("#event-search .field-event-type select").val(),
          				venue: $("#event-search .field-event-venue select").val(),
          				period: $("#event-search .field-event-date select").val()
                },
      					cache:false,
      					success: function(html)
                {
      						successFunction(html);
      					}
    				  }
            );
    				//e.preventDefault();
    			}
        );
        
        $(".sort .orderbydate").click
        (
          function()
          {
            $.ajax
            (
              {
                url: top.hlp_eventResultAjaxUrl,
                data:
                {
                  perPage: $("#per_page").val(),
                  keyWord: containsDefaultText ? "" : $("#key-word").val(),
          				eventType: $("#event-search .field-event-type select").val(),
          				venue: $("#event-search .field-event-venue select").val(),
          				period: $("#event-search .field-event-date select").val(),
          				orderByPlace: ""
                },
      					cache:false,
      					success: function(html)
                {
      						successFunction(html);
      						//$("#results").html(html);
      						//f(f); //call this function (initSearchResult) again
      					}
      				}
            );
    				//e.preventDefault();
    			}
        );
        $(".sort .orderbyplace").click
        (
          function()
          {
            $.ajax
            (
              {
                url: top.hlp_eventResultAjaxUrl,
                data:
                {
                  perPage: $("#per_page").val(),
                  keyWord: containsDefaultText ? "" : $("#key-word").val(),
          				eventType: $("#event-search .field-event-type select").val(),
          				venue: $("#event-search .field-event-venue select").val(),
          				period: $("#event-search .field-event-date select").val(),
          				orderByPlace:"X"
                },
      					cache:false,
      					success: function(html)
                {
      						successFunction(html);
      						//$("#results").html(html);
      						//f(f); //call this function (initSearchResult) again
      					}
      				}
            );
    				//e.preventDefault();
    			}
        );
  		}
  		
  		//Callback for ajax request
  		function successFunction(html)
      {
  			//Insert ajax response into DOM
  			$("#results").html(html);
  			//Init elements received via ajax
  			initSearchResult(initSearchResult, html);
  		}
  		
  		//Ajax submit of the query
  		var containsDefaultText = $("#key-word").hasClass("example"); //The class "example" is set by a function defined in general.js line 410
  		$.ajax
      (
        {
    			url: top.hlp_eventResultAjaxUrl,
    			data:
          {
            perPage: $("#per_page").val(),
            keyWord: containsDefaultText ? "" : $("#key-word").val(),
    				eventType: $("#event-search .field-event-type select").val(),
    				venue: $("#event-search .field-event-venue select").val(),
    				period: $("#event-search .field-event-date select").val()
          },
    			cache:false,
    			success: function(html)
          {
    				successFunction(html);
    				//$("#results").html(html);
    				//initSearchResult(initSearchResult);
    			}
  		  }
      );
  		e.preventDefault();
  	}
  );
	$eventsSubmit.parents("form:first").submit
  (
    function(e)
    {
  		$eventsSubmit.click();
  		e.preventDefault();
  	}
  );
	$eventsSubmit.click();//Submit press query for default display of all news




	//shorten breadcrumb
	$("#breadcrumb").each(function(){
		var $this = $(this);
		var i; //loop counter
		var cushion = 10; //some extra space to avoid last element touching the right side
		var breadWidth = 0;
		var MAX_BREAD_WIDTH = $this.width() - getPxVal($this.css("padding-left")) - cushion; //that's how large we can get without line wrapping
		var $ellipsis = $("<li class='ellipsis'> ... </li>").css("display", "none");
		var $homeElm = $this.find("li.home");
		var rightSpace = getPxVal($homeElm.css("padding-right")) + getPxVal($homeElm.css("margin-right"));// margin + padding at the right side of each breadcrumb element
		var $items;
		var $excessList = $();//empty jQuery bag
		
		$homeElm.after($ellipsis);//add ellipsis to breadcrumb so we can correctly determine it's width
		$items = $this.find("li");
		MAX_BREAD_WIDTH = MAX_BREAD_WIDTH - $homeElm.width() - rightSpace;
		MAX_BREAD_WIDTH_WITH_ELLIPSIS = MAX_BREAD_WIDTH - $ellipsis.width() - rightSpace;	//Link to home page is always generated (see further down). 
																							//It's width must therefore be subtracted from the max available width.
																							//The width of the ellipsis must also be taken into account.
																							//Also subtract right margin + padding for both elements
		
		var $item;
		var itemsSize = $items.size();
		for(i = itemsSize - 1; i >= 2; i--){
			//Accumulate width of LI elements starting from end of list. That way we only need one go 
			//to calculate the total width and collect the elements that can be hidden if the available widht is exceeded
			$item = $items.eq(i);
			breadWidth = breadWidth + $item.width(); 
			if(i != itemsSize - 1){
				breadWidth = breadWidth + rightSpace; //11 = padding & margin, don't add to last element of list
			}
			if(breadWidth >= MAX_BREAD_WIDTH_WITH_ELLIPSIS){
				//Collect elements who are outside the bound
				$excessList = $excessList.add($item);
			}
		}

		if(breadWidth > MAX_BREAD_WIDTH){
			//Hide excess elements
			$excessList.css("display", "none");
			
			//Show ellipsis
			$ellipsis.css("display", "inline");
		}else{
			$ellipsis.remove();
		}
	});
	
	function getPxVal(val){
		if(typeof val === 'string'){
			if(val.indexOf("px") > -1){
				val = val.replace("px", "");
			}
		}
		
		return isNaN(parseInt(val)) ? 0 : parseInt(val);
	}

	$(".eventdetail .back").click(function(e){
		var $this = $(this);
		if($this.hasClass("fromSearch")){
			var href = $this.attr("href");
			var concat = "?";
			if(href.indexOf("?") > -1){
				concat = "&";
			}
			href = href + concat + "fromCache=true";
			top.location.href = href;
			e.preventDefault();
		}
	});
	
	$(".newsDetail .back").click(function(e){
		var $this = $(this);
		if($this.hasClass("fromSearch")){
			var href = $this.attr("href");
			var concat = "?";
			if(href.indexOf("?") > -1){
				concat = "&";
			}
			href = href + concat + "fromCache=true";
			top.location.href = href;
			e.preventDefault();
		}
	});
	
	
	//Remove empty detail navigation
	if($("#sidebar .nav-wrap").children().size() === 0){
		$("#sidebar .nav-sub").remove();
	}
	
	(function(){
		//Position support-boxes if necessary 
		var ignoreList = ['t42-detailpage'];
		if($.inArray($('body').attr('id'), ignoreList) === -1){ //if body id not in ignore list
			var $subNav = $("#sidebar .nav-sub");
			var MIN_DISTANCE = 295;
			var distance = 0;
			
			if($subNav.length > 0){
				distance = $subNav.height();
			}
			
			if(distance < MIN_DISTANCE){
				var diff = MIN_DISTANCE - distance;
				$("#support-boxes").css("margin-top", diff);
			}
		}
	}());
	
	//Collect all text/pic elements that contain a picture (.asset-left) that is not followed by a h3 and mark first p that is not the picture
	$("#content div.textPic").has(".asset-left").not(
		function(){
			return $(this).has(".asset-left+h3").size() > 0;
    }).find("p:eq(1)").addClass("first");
	
});
