var templatePath = "fileadmin/templates/page/";

var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 28;

var deajaxifiedPages = new Array();
var debugging = false;

/*
 * AJAX-LOADING-CONTENT-STUFF
 * --------------------------------------------------
 */

function deajaxifiedPage()
{
  deajaxifiedPages.each(function(page){
    if (window.splittedUrl["combinedpath"] && window.splittedUrl["combinedpath"].test(page))
    {
      return true;
    }
  });

  return false;
}

function ajaxifyLinks(links, force, doHistory)
{
	if (links == null) return;

	// ajaxify links
	links.each(function(link)
	{
    link.origLink = linkStripContentPart(link.href);

	  // set homelink
    if (link.origLink.test(new RegExp(".*home\.html")))
    {
      window.homeLink = link;
    }

	  // blur on focus of every link
		link.addEvent("focus", function()
		{
			link.blur();
		});

		// ajaxify only following links
		if (force ||
        link.href.test(window.currentHost + "*") &&
        link.href.test(new RegExp(".*html")) &&
        !link.getAttribute('rel') &&
        link.id != "vcard" &&
        link.id != "l-link" &&
        link.href.test("benutzerverwaltung.html") == false &&
        link.href != window.currentHost + "/#")
		{
      link.addEvent('click', function()
      {
        if (!this.deAjaxified) this.setProperty('href', 'javascript:void(0)');
      });

      link.addEvent('mouseenter', resetLink);
      link.addEvent('mouseleave', resetLink);

      link.addEvent('click', function()
      {
  			var splittedLinkUrl = splitUrl(link.origLink);

        // link in page -> scroll to section
  			if(!force && splittedLinkUrl["section"] != null && window.splittedUrl["combinedpath"] == splittedLinkUrl["combinedpath"])
  			{
  					scrollToSection($(splittedLinkUrl["section"]));
  			}
  			else
  			{
          var linkInMenu = false;


          $$('#mainmenu a').each(function(menuLink)
          {
     			  // check if link exists in menu
            if (!linkInMenu && cleanLink(splittedLinkUrl["combinedpath"]) == cleanLink(splitUrl(menuLink.origLink)["combinedpath"]))
            {
              linkInMenu = true;

              if (link.deAjaxified) return;
              // reload content only if page-url is different to link
              if ((link.origLink) != (window.splittedUrl["link"]) || force)
        	    {
        		    activateMenuItem(menuLink);
        		    setContent(link.origLink, 0, doHistory);
        	    }
            }
          });

          if (!linkInMenu)
          {
            if (link.deAjaxified) return;
            if (link.origLink != window.currentLocation)
            {
              var dummyMenuEntry = $('mainmenu-dummy');
        	    if (dummyMenuEntry)
              {
                debugOut("Fire dummy");
                dummyMenuEntry.fireEvent('click');
              }
        	    setContent(link.origLink, 0, doHistory);

        			if (isHomePage(window.splittedUrl["combinedpath"]))
        			{
        			 activateMenuItem(window.homeLink);
        			}
            }
          }
  			}
  		});
		}
		else
		{
      link.addEvent('click', function()
      {
        if(link.href.test("benutzerverwaltung.html"))
        {
        	displayLoadingImage();
      	}
      });
    }
	});
}



function deAjaxifyLinks(links){
  return;
  links.each(function(link){
    link.deAjaxified = true;
  });
}






function ajaxifyForm(form)
{
  if(form.getParent('div').getProperty("class") == "tx-felogin-pi1" || form.getProperty('id') == "tx-srfeuserregister-pi1-fe_users_form")
  {
    form.setProperty('action', linkStripContentPart(form.getProperty('action')));
    return;
  }

  form.addEvent('submit', function(e) {
    e.stop();
    form.ajaxsubmit();
  });

  form.ajaxsubmit = function() {
    // Fill the PostValue-Object with input form values
    var postValues = new Object();

    form.getElements('input').each(function(input)
    {
        var extend = new Object();
        extend[input.name] = input.value;
        if (input.name)
        {
          if ((input.getProperty('type') != 'radio' && input.getProperty('type') != 'checkbox') || input.getProperty('checked'))
          {
              $extend(postValues, extend);
          }

          if (input.getProperty('type') == 'checkbox' && !input.getProperty('checked'))
          {
              extend[input.name] = 0;
              $extend(postValues, extend);
          }
        }
    });

    form.getElements('textarea').each(function(input)
    {
        var extend = new Object();
        extend[input.name] = input.value;

        if ((input.getProperty('type') != 'radio' && input.getProperty('type') != 'checkbox') || input.getProperty('checked'))
        {
            $extend(postValues, extend);
        }
    });

    form.getElements('select').each(function(select)
    {
        if (select.selectedIndex > -1)
        {
            var extend = new Object();
            extend[select.name] = select.options[select.selectedIndex].value;

            $extend(postValues, extend);
        }
    });

    var splittedRequestUrl = splitUrl(linkStripContentPart(form.action));
  	displayLoadingImage();
    var myHTMLRequest = new Request(
    {
  		evalScripts: !Browser.Engine.trident,
      url: "/content/" + (splittedRequestUrl["combinedpath"] == "" ? "/home.html" : splittedRequestUrl["combinedpath"]),
      onSuccess : function(html) {
        insertContentHTML(html, linkStripContentPart(form.action), true);
      }
    }).post(postValues);
  }
}





function resetLink(link)
{
  var linkToReset = link ? link : this;
	if(linkToReset.origLink)
	{
		linkToReset.href = linkToReset.origLink;
	}
}


function linkStripCachePart(link)
{
    var regExp = new RegExp("([.^\/]*\/?)(no_cache\/)+(.*)");

    var splits = regExp.exec(link);

    if (!splits || !splits[2]) {
      result = link;
    }
    else
    {
      result = splits[1] + splits[3];
    }

    return result;
}




function isNoCacheLink(link)
{
    var regExp = new RegExp("([.^\/]*\/?)(no_cache\/)+(.*)");

    var splits = regExp.exec(link);

    return (splits != null && splits[2] != null);
}




function linkStripParams(link)
{
    var regExp = new RegExp("(.*)\/([^?]*)");

    var splits = regExp.exec(link);

    if (!splits || !splits[2]) {
      result =link;
    }
    else
    {
      result = splits[1] + "/" + splits[2];
    }

    return result;
}

function cleanLink(link)
{
  return linkStripCachePart(linkStripParams(link));
}


function splitUrl(url)
{
    //debugOut("Url: " + url);
    var regExp = new RegExp("(" + window.currentHost + ")*\/([^#]*)(#p=(.*)__section=(.*))?(#p=(.*))?(#(.*))?");

    var splits = regExp.exec(url);

    var result = new Object();

    if (splits == null)
    {
        result["section"] = null;
        result["path"] = null;
        result["hashpath"] = null;
    }

    else if (splits[3])
    {
        result["section"] = splits[5];
        result["path"] = splits[2];
        result["hashpath"] = splits[4];
    }

    else if (splits[7])
    {
        result["section"] = null;
        result["hashpath"] = splits[7];
        result["path"] = splits[2];
    }

    else if (splits[9])
    {
        result["section"] = splits[9];
        result["path"] = splits[2];
        result["hashpath"] = null;
    }

    else
    {
        result["section"] = null;
        result["path"] = splits[2];
        result["hashpath"] = null;
    }

    //debugOut("section: " + result["section"]);
    //debugOut("path: " + result["path"]);
    //debugOut("hashpath: " + result["hashpath"]);


    result["combinedpath"] = result["hashpath"] == null ? result["path"] : result["hashpath"];
    result["link"] = window.currentHost + "/" + result["combinedpath"] + (result["section"] != null ? "#" + result["section"] : "");
    result["combinedhash"] = result["combinedpath"] == "" ? "" : ("p=" + result["combinedpath"] + (result["section"] == null ? "" : "__section=" + result["section"]));


    return result;
}


function isHomePage(href)
{
  return window.homeLink && (
        href == "en.html" ||
        href == "en/" ||
        href == "de/" ||
        href == "en" ||
        href == "de" ||
        href == "de.html" ||
        href == "home.html" ||
        href == "de/home.html" ||
        href == "en/home.html"
        );
}


function checkHashChange() {
	if (Browser.Engine.trident)
	{
    if (!window.stopCheckHistoryFrame && $('history-frame').contentWindow.document.getElementById('historyURL'))
    {
      var frameHref = $('history-frame').contentWindow.document.getElementById('historyURL').innerText;

      if (window.oldHistoryFrameHref != frameHref)
      {
        window.stopCheckHistoryFrame = true;
        window.oldHistoryFrameHref = frameHref;
        window.oldHash = "#" + splitUrl(window.currentHost + "/" + frameHref)["combinedhash"];
        simulateLinkClick(window.currentHost + "/" + frameHref);
      }
	    else if (window.location.hash != window.oldHash)
	    {
        window.stopCheckHistoryFrame = true;
		    window.oldHash = window.location.hash;
        window.oldHistoryFrameHref = frameHref;
		    simulateLinkClick(window.location.href);
	    }
    }
	}

  else
  {
    if (window.location.hash != window.oldHash)
    {
      window.oldHash = window.location.hash;
      simulateLinkClick(window.location.href);
    }
  }
};




function simulateLinkClick(href)
{
	var anchor = new Element("a", {"href" : href});

	ajaxifyLinks(new Array(anchor), true, false);

	anchor.fireEvent('click');

	anchor.destroy();
}


function checkRedirects()
{
    if($('login-successfull'))
    {
    	displayLoadingImage();
      document.location = window.currentHost + "/de/xcalibur-portal.html";
    }

    if($('user_logout_form'))
    {
      displayLoadingOverlay();
      $('user_logout_form').submit();
    }
}

function insertContentHTML(html, url, doHistory)
{
	  //debugOut("Request Successfull");

	  if($('debugBox') && debugging != false)
	  {
  	 $('debugBox').grab(new Element('a', {href: url, text: url}), 'top');
  	}

    window.splittedUrl = splitUrl(url);

    document.location.hash = window.splittedUrl["combinedhash"] == "" ? "p=/home.html" : window.splittedUrl["combinedhash"];

		if (doHistory)
		{
		    window.oldHash = window.location.hash;
		}

		// set document-title
		var titleCandidates = html.match(/<title>(.*)<\/title>/);
		var title = "www.diomex.com";

		if(titleCandidates && titleCandidates.length == 2)
		{
		  title = titleCandidates[1];
    }

		var titleDummy = new Element('div');
		titleDummy.set('html', title);
		document.title = titleDummy.get('text');

		// set content
		var contentHTML = "Inhalt konnte nicht geladen werden.";
		var contentHTMLCandidates = html.match(/<body>([\s\S]*)<\/body>/);

		if(contentHTMLCandidates && contentHTMLCandidates.length == 2)
		{
		  contentHTML = contentHTMLCandidates[1];
  		var lLink = contentHTML.match(/<a[^>]*href="([\s\S^"]*)"[^>]*id="content-l-link"/)[1];
      $('l-link').setProperty('href', lLink);
    }

		$('content').innerHTML = contentHTML;

		if($('content-l-link'))
    {
    		$('content-l-link').dispose();
    }

		hideContentCurtain();

		var loadingOverlay = $('loading-overlay');

		if(loadingOverlay)
		{
		  loadingOverlay.dispose();
    }

		if (Slimbox)
		{
			Slimbox.scanPage();
		}

		if(window.splittedUrl["section"])
		{
			scrollToSection($(window.splittedUrl["section"]));
		}

    if($('loading-image'))
    {
		  $('loading-image').setStyle('display', 'none');
    }
		ajaxifyLinks($$('#content a'), false, true);

    if (Browser.Engine.trident)
    {
        window.stopCheckHistoryFrame = false;
    }

		$$('#content form').each(function(form){ ajaxifyForm(form)});

    initDetailTogglers();

    checkRedirects();

    checkIntegratorStatus();

    positionLayout();
}


var setContent = function setContent(url, delayTime, doHistory)
{
  if (deajaxifiedPage())
  {
    deAjaxifyLinks($$('a'));
  }

  if (Browser.Engine.trident && doHistory)
  {
    window.stopCheckHistoryFrame = true;
  }

  var splittedRequestUrl = splitUrl(url);

  if (splittedRequestUrl["section"] == null)
  {
    scrollToSection(null);
  }

  if (Browser.Engine.trident && doHistory)
  {
    $('history-frame').src = window.currentHost + "/history.php?historyURL=" + escape(splittedRequestUrl['combinedpath']);
    window.oldHistoryFrameHref = splittedRequestUrl['combinedpath'];
  }

  var headers = "";
  if (isNoCacheLink(url))
  {
    //debugOut("nocachelink");
    headers = {'If-Modified-Since': 'Sat, 1 Jan 2000 00:00:00 GMT'};
  }

	var req = new Request({
		url: "/content/" + (splittedRequestUrl["combinedpath"] == "" ? "/home.html" : splittedRequestUrl["combinedpath"]),
		method: 'get',
    headers: headers,
  	evalScripts: !Browser.Engine.trident,
		link : 'cancel',
		onRequest: function(){
  displayLoadingOverlay();
    	//displayLoadingImage();
    },
		onSuccess: function(html)
		{
		  insertContentHTML(html, linkStripContentPart(url), doHistory);
		},

		onFailure: function() {
			$('content').set('text', "Der Inhalt konnte nicht geladen werden.");
      window.stopCheckHistoryFrame = false;
		}
	});

	(function() { req.send() }).delay(delayTime);
}



function linkStripContentPart(link) {
    var regExp = new RegExp("([.^\/]*\/?)([\/]?content\/)+(.*)");
    var splits = regExp.exec(link);

    if (!splits || !splits[2]) {
      result = link;
    }
    else
    {
      result = splits[1] + splits[3];
    }

    return result;
}




function debugOut(message)
{
	var debugBox = $('debugBox');

	if (!debugBox || debugging == false) return;

	debugBox.setStyles(
	{
		'position'  :'absolute',
		'bottom' : '0px',
		'right' : '0px',
		'z-index' : '999',
		'width' : '300px',
		'height' : '800px',
		'opacity' : '0.7',
		'background-color' : '#ffffff',
		'border' : '1px solid #bbbbbb',
		'padding' : '10px',
		'overflow' : 'auto'
	});

	debugBox.inject($('body'));

	debugBox.grab(new Element('p', {text: message}), 'top');
}






/*
 * LAYOUT-STUFF
 * --------------------------------------------------
 */

function scrollToSection(section)
{
	if (section != null)
	{
		var effect = new Fx.Scroll(window).toElement(section).setOptions({duration: 900});
	}
	else
	{
		var effect = new Fx.Scroll(window).start(null, 250);
	}
}


function getPageHeight()
{
	var containerBottom = $('footer').getCoordinates()['bottom'];
	var bodyHeight = $('body').getSize().y;

	return bodyHeight > containerBottom ? bodyHeight : containerBottom;
}




function positionLayout()
{
	if (!$('body')) return;

	var containerBottom = $('footer').getCoordinates()['bottom'];
	var bodyHeight = $('body').getSize().y;

	var height = bodyHeight > containerBottom ? bodyHeight : containerBottom;

	var bgBottom = $('bg-bottom');

	var bgBottomHeight = 514;
	var bgTopHeight = 414;

	if (height < bgTopHeight + bgBottomHeight)
	{
		bgBottomHeight = (height - bgTopHeight) > 0 ? (height - bgTopHeight) : 0;
	}

	bgBottom.setStyles({
		'top' : (height - bgBottomHeight) + "px",
		'height' : bgBottomHeight + "px"
	});

	var containerHeight = $('container').getSize().y + 'px';

	$('bdleft-container').setStyle('height', containerHeight);
	$('bdright-container').setStyle('height', containerHeight);
	$('bdright-container').setProperty('height', containerHeight);
}





function displayLoadingImage()
{
	if (!$('loading-image'))
	{
		var loadingImage = new Element('img', {
			id: 'loading-image',
			src: templatePath + 'images/loading.gif',
			alt: 'Inhalt wird geladen...'
		});
		loadingImage.inject($('body'));
	}
	else
	{
		$('loading-image').setStyle('display', 'block');
	}

  displayLoadingOverlay();
}




function hideContentCurtain()
{
  $('content').setStyle('visibility', 'visible');
	var curtain = $('content-curtain');

	if (curtain != null)
	{
		curtain.dispose();
	}
}


function displayLoadingOverlay()
{
	if(!$('loading-overlay'))
	{
		var overlay = new Element('div', {
			id: 'loading-overlay'
		});

		overlay.setStyles({
			width: $('body').getSize().x + 'px',
			height: getPageHeight() + 'px',
			opacity: 0.7
		});

		overlay.inject($('body'));
	}
}

function displayContentCurtain()
{
	if(!$('content-curtain'))
	{
		var curtain = new Element('div', {
			id: 'content-curtain'
		});

		curtain.inject($('content'));

		curtain.setStyles({
			width: ($('content').getSize().x - 10) + 'px',
			height: $('content').getSize().y + 'px'
		});
	}
}






function correctPNG()
{
	$$('img').each(function(image, index)
	{
		if (image.src.toUpperCase().test(/.*\.PNG/))
		{
			var imgSubstitute = new Element('span',
			{
				id : image.id,
				'class': image.className
			});

			imgSubstitute.setStyles(image.getStyles('height', 'width', 'position', 'top', 'right'));

			imgSubstitute.setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale', src='" + image.src + "');");

			imgSubstitute.replaces(image);
		}
	});
}



/*
 * MENU
 * --------------------------------------------------
 */

function activateMenuItem(link)
{
	if (!link.getParent('#mainmenu') || link.id == 'mainmenu-dummy')
	{
		var menuLevel1SelectionEffect = new Fx.Tween($('mainmenu'),
		{
			duration: 1000,
			transition: Fx.Transitions.Sine.easeInOut
		});

		menuLevel1SelectionEffect.start('background-position', '1px -30px');

		return;
	}

	if (link.getProperty('class').contains('level1'))
	{
		var level1ListItem = link.getParent('li');
	}

	if (link.getProperty('class').contains('level2'))
	{
		var level1ListItem = link.getParent('li').getParent('li');

		var level2ListItem = link.getParent('li');

	}

  if(level1ListItem && !level2ListItem) {
  	// Level1 selection
  	var yPosition = getSiblingIndex(level1ListItem) * 34 + 12;

  	if (level1ListItem.getFirst('ul') && level1ListItem.getFirst('ul').getSize().y == 0)
  	{
  		window.level1Foldout.display(getSiblingIndex(level1ListItem));
  	}

  	var menuLevel1SelectionEffect = new Fx.Tween($('mainmenu'),
  	{
  		duration: 1500,
  		transition: Fx.Transitions.Sine.easeInOut
  	});

  	menuLevel1SelectionEffect.start('background-position', '1px ' + yPosition + 'px');
  }


	if (level2ListItem)
	{
		if (level2ListItem.getFirst('ul').getSize().y == 0)
		{
			level1ListItem.level2Foldout.display(getSiblingIndex(level2ListItem));
		}

		var menuLevel2SelectionEffect = new Fx.Tween(level2ListItem.getParent('ul'),
		{
			duration: 1500,
			transition: Fx.Transitions.Sine.easeInOut
		});

		var yPosition = getSiblingIndex(level2ListItem) * 29;

		menuLevel2SelectionEffect.start('background-position', '30px ' + yPosition + 'px');
	}
}






function getSiblingIndex(element)
{
	var parent = element.getParent();

	if (parent)
	{
		return parent.getChildren().indexOf(element);
	}
	else
	{
		return -1;
	}
}





function initDetailTogglers()
{
  if ($('hidealldetails')) $('hidealldetails').addEvent('click', function() {
  	$$('.toggledetails').each(function(link)
  	{
  	 link.fireEvent('click');
  	});
  });

	$$('.toggledetails').each(function(link)
	{
	 link.addEvent('click', function()
	 {
	   var details = link.getNext("div");
	   if (details)
	   {
  	   if (!details.toggleData)
  	   {
  	     details.toggleData = {foldedin: false, height: details.getSize().y};
       }

       if (details.toggleData.foldedin)
       {
  	     details.morph({'height': details.toggleData.height});
       }
       else
       {
  	     details.morph({'height': 0});
       }
	     details.toggleData.foldedin = !details.toggleData.foldedin;
     }
   });
  });


  new Accordion(".sectionheader", ".section", {alwaysHide:true, display:0});

  var showFilters = window.acquisitionFilterActive ? 0 : 99;

  new Accordion("#togglesearchandfilter", "#searchandfilter", {alwaysHide:true, show:showFilters});

}



/*
 * INIT
 * --------------------------------------------------
 */


window.addEvent('domready', function()
{
	window.stopCheckHistoryFrame = true;
  $('content').setStyle('visibility', 'hidden');
	displayContentCurtain();
	window.currentHost = window.location.protocol + "//" + window.location.host;
	window.oldHash = window.location.hash;
	window.splittedUrl = splitUrl(window.location.href);
	window.oldHistoryFrameHref = window.splittedUrl["combinedpath"];
	window.homeLink = null;

	debugOut("Sprache: " + window.langCode);
	debugOut("Debugging enabled");

	if (window.splittedUrl["hashpath"] != null && window.splittedUrl["path"] != window.splittedUrl["hashpath"])
	{
	  debugOut("Abort loading");
	  displayLoadingOverlay();
		window.location = window.splittedUrl["link"];
	}
	else
	{
    hideContentCurtain();

	  if(window.splittedUrl["hashpath"] == "")
    {
      scrollToSection($(window.splittedUrl["section"]));
    }


      // history-frame for ie
  	if (Browser.Engine.trident)
  	{
  		var iframe = new Element('iframe',
  		{
  			width : '0',
  			height : '0',
  			frameBorder : '0',
  			name : 'history-frame',
  			id : 'history-frame'
  		});

  		iframe.inject($('body'));
  		iframe.src = window.currentHost + "/history.php?historyURL=" + escape(window.splittedUrl["combinedpath"]);
      window.stopCheckHistoryFrame = false;
  	}


  	// init menu-selectors for ie
  	$('mainmenu').setStyle('background-position', '1px -30px');

  	$$('#mainmenu a').each(function(item)
  	{
  		if (item.getProperty('class').contains('level2'))
  		{
  			item.getParent('ul').setStyle('background-position', '30px -29px');
  		}
  	});


  	// foldout-effects for menu level1
  	var togglersLevel1 = new Array();
  	var stretchersLevel1 = new Array();

  	$$('#mainmenu a.level1').each(function(link)
  	{
  		var listItem = link.getParent('li');

  		var subListItem = listItem.getFirst('ul.level2');

  		if(subListItem)
  		{
  			togglersLevel1.include(link);
  			stretchersLevel1.include(subListItem);
  		}
  	});

  	window.level1Foldout = new Accordion(togglersLevel1, stretchersLevel1, {
  		alwaysHide : false,
  		show : 99,
  		opacity : false,
  		onActive : function(link, element)
  		{
        /*
  			var level2ListItem = link.getParent('li').getFirst('ul');

  			var menuLevel2SelectionEffect = new Fx.Tween(level2ListItem,
  			{
  				duration: 1000,
  				transition: Fx.Transitions.Sine.easeInOut
  			});

  			menuLevel2SelectionEffect.start('background-position', '30px -29px');
  			*/
  		}
  	});

  	// foldout-effects for menu level2
  	$('mainmenu').getChildren('li').each(function(liLevel1, index)
  	{
  		var togglersLevel2 = new Array();
  		var stretchersLevel2 = new Array();

  		liLevel1.getElements('a.level2').each(function(link)
  		{
  			var listItem = link.getParent('li');

  			var subListItem = listItem.getFirst('ul.level3');

  			if(subListItem)
  			{
  				togglersLevel2.include(link);
  				stretchersLevel2.include(subListItem);
  			}
  		});

  		liLevel1.level2Foldout = new Accordion(togglersLevel2, stretchersLevel2, {
  			alwaysHide : false,
  			show : 99,
  			opacity : false,
  			onActive: function(link, element)
  			{
  				var level2ListItem = link.getParent('li');

  				var itemCount = level2ListItem.getElement('ul').getChildren('li').filter(function(item){ return !item.getParent('ul').className.contains('empty')}).length;

  				var list = level2ListItem.getParent('ul');

  				var sizeEffect = new Fx.Tween(list, {
  					duration: 500,
  					transition: Fx.Transitions.Sine.easeInOut
  				});

  				var siblingCount = (list.getChildren('li').length);

  				var height = siblingCount * 29  + 34 * itemCount + 20;

  				sizeEffect.start('height', height + "px");
  			}
  		});
  	});



  	// add bottom-vista-effect
  	var bgBottom = new Element('div',
  	{
  		id: 'bg-bottom'
  	});

  	var bgVistaEffect = new Element('img',
  	{
  		id: 'bg-vistaeffect',
  		src: templatePath + 'images/bg-vistaeffect.png',
  		alt: 'Hintergrundbild',
  		'class': 'noprint'
  	});

  	bgVistaEffect.inject(bgBottom);
  	bgBottom.inject($('body'));


  	// add borders with gradient
  	var borderLeftContanier = new Element('img', {
  		id: 'bdleft-container',
  		src: templatePath + 'images/bdleft-container.png',
  		alt: 'Hintergrundbild',
  		'class': 'noprint container-border'
  	});

  	var borderRightContanier = new Element('img', {
  		id: 'bdright-container',
  		src: templatePath + 'images/bdright-container.png',
  		alt: 'Hintergrundbild',
  		'class': 'noprint container-border'
  	});

  	var borderRightContainer = $('bdright-container');

  	borderLeftContanier.inject($('container'));
  	borderRightContanier.inject($('container'));

  	var arVersion = navigator.appVersion.split("MSIE")
  	var version = parseFloat(arVersion[1])


  	// Transparency for IE5.5 IE6
  	if ((version >= 5.5) && (document.body.filters) && (version < 7))
  	{
  		var transparencyElements = new Array(
  			$('footer'),
  			$('topnav')
  		);

  		transparencyElements.each(function(element)
  		{
  			var backgroundUrl = element.getStyle('background-image').match(/url\(\"(.*)\"\)/)[1];

  			if (backgroundUrl)
  			{
  				element.setStyle('background-image', 'none');
  			}

  			element.setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + backgroundUrl + "')");
  		});

  		correctPNG();
  	}


  	// Flash Header
  	var hasProductInstall = DetectFlashVer(6, 0, 65);

  	var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

  	if ( hasProductInstall && !hasRequestedVersion )
  	{
  		var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
  		var MMredirectURL = window.location;
  		document.title = document.title.slice(0, 47) + " - Flash Player Installation";
  		var MMdoctitle = document.title;
  	}
  	else if (hasRequestedVersion)
  	{
  		$('flash-header').set('html', '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="DiomexLocal" width="100%" height="100%" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="wmode" value="transparent" /><param name="movie" value="' + templatePath + 'flash/FlashHeader.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#869ca7" /><param name="allowScriptAccess" value="sameDomain" /><embed src="' + templatePath + 'flash/FlashHeader.swf" quality="high" bgcolor="#869ca7" width="100%" height="100%" name="FlashHeader" align="middle" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" wmode="transparent"></embed>');
  	}
  	else
  	{
  		var alternateContent = 'Alternate HTML content should be placed here. '
  		+ 'This content requires the Adobe Flash Player. '
  		+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
  		//document.write(alternateContent);  // insert non-flash content
  	}


    ajaxifyLinks($$('a'), false, true);

  	// activate menu-item matched to submitted url
  	var found = false;

  	if (isHomePage(window.splittedUrl["combinedpath"]))
  	{
  	 activateMenuItem(window.homeLink);
  	}
  	else
  	{
  		$$('#mainmenu a').each(function(link)
  		{
  			if (cleanLink(splitUrl(link.href)["combinedpath"]) == cleanLink(window.splittedUrl["combinedpath"]))
  			{
  				activateMenuItem(link);
  			}
  		});
  }

  	$$('#content form').each(function(form){ ajaxifyForm(form)});

  	positionLayout();


  	// position all
  	positionLayout.periodical(800);
  	window.addEvent('resize', positionLayout);

  	checkHashChange.periodical(100);

  	checkRedirects();

  	checkIntegratorStatus();
  }
});




function editSupplierPriority(htmlElement, prioseturl)
{
  var editSupplierPriorityDialog = $('editSupplierPriorityDialog');

  var prio3link = $('editSupplierPriorityDialogPrio3');
  var prio2link = $('editSupplierPriorityDialogPrio2');
  var prio1link = $('editSupplierPriorityDialogPrio1');
  var prio0link = $('editSupplierPriorityDialogPrio0');

  if(!editSupplierPriorityDialog)
  {
    editSupplierPriorityDialog = new Element('div', {'id': 'editSupplierPriorityDialog'});

    var prio3link = new Element('a', {'id' : 'editSupplierPriorityDialogPrio3', 'text' : 'As soon as possible', 'class' : 'prio-4'});
    prio3link.supplierPriority = 3;
    prio3link.addEvent('click', setSupplierPriority);
    prio3link.inject(editSupplierPriorityDialog);

    var prio2link = new Element('a', {'id' : 'editSupplierPriorityDialogPrio2', 'text' : 'Interessiert', 'class' : 'prio-3'});
    prio2link.supplierPriority = 2;
    prio2link.addEvent('click', setSupplierPriority);
    prio2link.inject(editSupplierPriorityDialog);

    var prio1link = new Element('a', {'id' : 'editSupplierPriorityDialogPrio1', 'text' : 'Nice to have', 'class' : 'prio-2'});
    prio1link.supplierPriority = 1;
    prio1link.addEvent('click', setSupplierPriority);
    prio1link.inject(editSupplierPriorityDialog);

    var prio0link = new Element('a', {'id' : 'editSupplierPriorityDialogPrio0', 'text' : 'Nicht interessiert', 'class' : 'prio-1'});
    prio0link.supplierPriority = 0;
    prio0link.addEvent('click', setSupplierPriority);
    prio0link.inject(editSupplierPriorityDialog);

    var abortLink = new Element('a', {'text' : 'Abbrechen'});
    abortLink.addEvent('click', function() {
      hideEditSupplierPriorityDialog();
    });

    abortLink.setStyle('border', '1px solid #ddd');

    abortLink.inject(editSupplierPriorityDialog);

    editSupplierPriorityDialog.inject($('body'));
  }

  prio3link.prioSetUrl = prioseturl;
  prio2link.prioSetUrl = prioseturl;
  prio1link.prioSetUrl = prioseturl;
  prio0link.prioSetUrl = prioseturl;

  prio0link.prioTableCell = htmlElement;
  prio1link.prioTableCell = htmlElement;
  prio2link.prioTableCell = htmlElement;
  prio3link.prioTableCell = htmlElement;

  var position = $(htmlElement).getCoordinates();

  editSupplierPriorityDialog.setStyles({
    'top' : position.top + "px",
    'left' : position.left + "px",
    'display' : 'block'
  });
}




function hideEditSupplierPriorityDialog()
{
  $('editSupplierPriorityDialog').setStyle('display', 'none');
}





var setSupplierPriority = function()
{
	hideEditSupplierPriorityDialog();

	this.prioTableCell.setProperty('text', this.supplierPriority);

  this.prioTableCell.getAllNext("td").each(function(element)
  {
    element.setProperty("text", "-");
  });

	var req = new Request({
		url: this.prioSetUrl + "p" + (this.supplierPriority + 1),
		method: 'get',
		link: 'chain',
		onFailure: function(xhr)
		{
		  alert("Beim Setzen der Priorit&auml;t ist ein Fehler aufgetreten.");
    }
	});

	req.send();
};


function checkIntegratorStatus()
{
  $$('.integrator-status').each(function(item, index) {
    if(item.getElement('.url')) {
      var integratorUrl = item.getElement('.url').getProperty('text');

      new Request({
      	url: '/typo3conf/ext/dmx_xcr_acquisition/pi1/integratorstatus.php',
      	headers: {'If-Modified-Since': 'Sat, 1 Jan 2000 00:00:00 GMT'},
      	evalScripts: false,
      	onSuccess: function(html)
      	{
      	 item.getElement('.url').setProperty('class', 'status-' + html);
      	}
      }).post({"integratorurl" : integratorUrl});
    }
  });
}
