Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

function checkSearchInput(inputfield)
{
	searchfield = $(inputfield);
	
	if (searchfield.value != '') 
	{
		return true;
	}
	else 
	{
		searchfield.className = 'error';
		return false;
	}
}

//  arrangeHalfColouredBoxes bringt nebeneinanderstehende boxen mit css "csc-frame-half-coloured" und "csc-frame-half-coloured half-right" auf die gleiche höhe
function arrangeHalfColouredBoxes()
{
	var myBlueFrames = $$(".csc-frame-half, .csc-frame-half-coloured");
	myBlueFrames.each(function(myBlueFrame, counter)
	{
		var myBlueFrameHeight = myBlueFrame.getHeight();
		var myOtherBlueFrame, myOtherBlueFrameHeight;
		if (myBlueFrame.hasClassName("half-right")) 
		{
			if ($(myBlueFrames[counter - 1])) 
			{
				myOtherBlueFrame = myBlueFrames[counter - 1];
				myOtherBlueFrameHeight = myOtherBlueFrame.getHeight();
			}
		}
		else 
		{
			if ($(myBlueFrames[counter + 1])) 
			{
				myOtherBlueFrame = myBlueFrames[counter + 1];
				myOtherBlueFrameHeight = myOtherBlueFrame.getHeight();
			}
		}
		maxHeight = (myBlueFrameHeight > myOtherBlueFrameHeight) ? myBlueFrameHeight : myOtherBlueFrameHeight;
		if (myBlueFrame)
			myBlueFrame.setStyle({
				height: maxHeight + 'px'
			});
		if (myOtherBlueFrame)
			myOtherBlueFrame.setStyle({
				height: maxHeight + 'px'
			});
	});
}

function arrangeMaincontentBoxes()
{

	if(!$('main-content')) return false;

		var mainContentHeight = $('main-content').getHeight();
		var sideContentHeight = $('secondary-content').getHeight()-30;

		maxHeight = (mainContentHeight > sideContentHeight) ? mainContentHeight : sideContentHeight;
//		$('main-content', 'secondary-content').invoke('setStyle', { height: maxHeight + 'px' });

}


function __resizeImagesInForum()
{
	var images = $$('div.tx-mmforum-pi1 img');
	var maxW = 600;
	
	images.each(function(pic){
		w=pic.width;
		h=pic.height;
		if (w > maxW) {
			f=1-((w - maxW) / w);
			pic.width=w * f;
			pic.height=h * f;
		}
	});
}

function resizeImagesInForum()
{
	var container = $("main-content_wide");
	if (!container) return;
	var maxW = 600;
	var pix=container.getElementsByTagName('img');
	for (i=0; i<pix.length; i++) 
	{
		w=pix[i].width;
		h=pix[i].height;
		if (w > maxW) {
			f=1-((w - maxW) / w);
			pix[i].width=w * f;
			pix[i].height=h * f;
		}
	}
}


function rawurldecode( str ) {
    // Decodes URL-encodes string  
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';


    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }

    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = ret.replace(/%([a-fA-F][0-9a-fA-F])/g, function (all, hex) {return String.fromCharCode('0x'+hex);}); // These Latin-B have the same values in Unicode, so we can convert them like this
    ret = decodeURIComponent(ret);

    return ret;
}



function startsWith(string, pattern) 
{
    return string.indexOf(pattern) === 0;
}

function endsWith(string, pattern) 
{
	var d = string.length - pattern.length;
	return d >= 0 && string.lastIndexOf(pattern) === d;
}


function trackFlash(type, url)
{
    urchinTracker(type);
    if (url)
    {
//	if (!startsWith(url, 'http'))
//	    url = document.location.host + '/' + url;
	document.location.href = url;
    }
}


function trackDownload(type, url){
    switch (type) {
        case 'trackDownloads':
			// google
            urchinTracker(url);
			// wiredminds
			// if (endsWith(url, '/'))
			//	url = url.substr(0, url.length-1);
			// wm_page_name = url;
			// wm_group_name = 'Documents';
			// wm_milestone = 'Document_Download';
			// wiredminds.count();
            break;
        case '.external':
			// google
            urchinTracker('/' + type + url);
			// wiredminds
			// wiredminds.trackEvent('External_Links' + url);
            break;
        default:
            return
    }
}






function checkApplicationtype(){
	if($F("applicationtype") == "Associate")
	{
		$("associate_container").show();
	}
	else
	{
		$("associate_container").hide();
	}
 }
 
 
function randomString() 
{
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

 
// if spam doesn't stop, try encrpytion: http://www.vincentcheung.ca/jsencryption/instructions.html
function avoidSpam()
{
	var my_forms = $$(".contactform");
	my_forms.each(function(my_form)
	{
		var the_string = 'HE5hDGuK' + randomString();
		// var the_string = '';
		var hidden = document.createElement('input');
		hidden.setAttribute('type', 'hidden');
		hidden.setAttribute('name', 'tx_pilmailform_pi1[text][spam]');
		hidden.setAttribute('value', the_string);
		my_form.appendChild(hidden);
	});
}



function menus()
{
	$$('.hover-menu').each(function(m)
	{
		if (!m.hasClassName('hovered')) 
		{
			menu(m, m.hasClassName('no-delay'));
			m.addClassName('hovered');
		}
	});
}

function menu(container, no_delay)
{
	var container = $(container);
	var timeout = no_delay ? 0 : 400;
	if (!container) 
		return;
	var currentMenu = null;
	var timer = null;
	var my_elements = container.select('li');
	my_elements.each(function(li)
	{
		Event.observe(li, 'mouseover', function()
		{
			if (currentMenu) 
			{
				if (timer) 
					window.clearTimeout(timer);
				currentMenu.removeClassName('hover');
			}
			var that = currentMenu = this;
			li.addClassName('hover');
		});
		Event.observe(li, "mouseout", function()
		{
			var that = currentMenu = this;
			timer = window.setTimeout(function()
			{
				if (currentMenu == that) 
				{
					that.removeClassName("hover");
					currentMenu = null;
				}
			}, timeout);
			return true;
		});
	});
}




function styleMyForms()
{
		jsStyledForm = new JsStyledForm('my_form0');
		jsStyledForm = new JsStyledForm('my_form1');
		jsStyledForm = new JsStyledForm('Kontaktformular');
		/* old stuff
		jsStyledForm = new JsStyledForm('hersteller');
		jsStyledForm = new JsStyledForm('anwendungsgebiet');
		jsStyledForm = new JsStyledForm('frequency');
		jsStyledForm = new JsStyledForm('produktkategorien');
		jsStyledForm = new JsStyledForm('perpage_1');
		jsStyledForm = new JsStyledForm('perpage_2');
		*/
		jsStyledForm = new JsStyledForm('sortby');
		jsStyledForm = new JsStyledForm('Applicationform');

		// js browsercheck
		/* 
		var checkform = true;
		if (Prototype.Browser.IE7 || Prototype.Browser.IE6) {
			var checkform = false;
		}
		if (checkform){
		}
		*/
			jsStyledForm = new JsStyledForm('productlistform');
}

function centerLogo() {
	var sView = $('pi6-singleView');
	if (sView) {
		if (Prototype.Browser.IE7 || Prototype.Browser.IE6) {
			var logoWrap = $('pi6-logo');
			var logoWrapHeight = logoWrap.getHeight();
			var logo = $('pi6-logo').down(1);
			var logoHeight = logo.getHeight();
			if (logoWrapHeight>logoHeight){
				var margin = (logoWrapHeight - logoHeight)/2;
				logo.setStyle({
					marginTop: margin-5 + 'px'
				});
			}
			if (logoWrapHeight <= logoHeight) {
				logoWrap.setStyle({
					height: logoHeight + 'px'
				});
			}
		}
	}
}





/*
 * produktlistenfilter
 */
function activateProductlistform()
{
	var productlistform = $('productlistform');
	if(!productlistform) return;
	// go ahead if form is present
	
	// observer zum highlighten des submit buttons
	var inputs = productlistform.select('input:not(#advanced)');
	var submit_button = productlistform.down('button.refresh');
	var serialized = Form.serializeElements(inputs);
	inputs.each(function(i){
		new Form.Element.Observer(i, 0.1, function()
		{
			if (serialized != Form.serializeElements(inputs))
				submit_button.addClassName('activated');
			else
				submit_button.removeClassName('activated');
		});
	});
	
	var fieldsets = productlistform.select('.filter fieldset');
	fieldsets.each(function(fieldset)
	{
		var checkboxes = fieldset.select('input[type=checkbox]')
		/*
		 * function zum checken und unchecken
		 * 
		 */
		var checkUncheck = function(checkbox)
		{
			rel = checkbox.getAttribute('rel');
			if (rel)
			{
				var all_checked = true;
				var none_checked = true;
				var rel = rel;
				var parent_checkbox = $(rel);
				checkboxes.each(function(other_checkbox)
				{
					if (other_checkbox.getAttribute('rel') == rel )
					{
						if (all_checked)
							all_checked = other_checkbox.checked ? true : false;
						if (none_checked)
							none_checked = other_checkbox.checked ? false : true;
					}
				});
				// parent checkbox hat id wie gecheckte checkbox den wert von rel
				parent_checkbox.removeClassName('half');
				parent_checkbox.checked = true;
				if(none_checked)
				{
					parent_checkbox.checked = false;
				}
				else if( !all_checked )
				{
					parent_checkbox.addClassName('half');
					parent_checkbox.checked = false;
				}
				halfOrNotHalfTheLabel(parent_checkbox);
			}
			else
			{
				checkboxes.each(function(child_checkbox)
				{
					if (child_checkbox.hasAttribute('rel') && child_checkbox.getAttribute('rel') == checkbox.id)
					{
						child_checkbox.checked = checkbox.checked ? 'checked' : false;
					}
				});
			}
		}
		var halfOrNotHalfTheLabel = function(checkbox, label){
			var label = label || checkbox.next('label');
			label.removeClassName('half');
			if (checkbox.hasClassName('half'))
				label.addClassName('half');
		}
		/*
		 * click handler für alle checkboxen respektive labels innerhalb des fieldsets
		 * observer für labels von styledform
		 */
		checkboxes.each(function(checkbox)
		{
			var label = checkbox.next('label');
			if (checkbox.getAttribute('rel'))
				checkUncheck(checkbox);
			new Form.Element.Observer(checkbox, 0.1, function()
			{
				if (label && (label.hasClassName('checkbox-checked') || label.hasClassName('checkbox-unchecked')))
				{
					
					label.className = checkbox.checked ? 'checkbox-checked' : 'checkbox-unchecked';
					halfOrNotHalfTheLabel(checkbox, label);
				}
			});
			Event.observe(label, 'mouseup', function(){
				window.setTimeout(function(){
					checkUncheck(checkbox);
				}, 10);
			});
		});
		/*
		 * function der auschliessen buttons
		 */
		var excludes = fieldset.select('span.exclude');
		excludes.each(function(exclude)
		{
			new Event.observe(exclude, 'click', function()
			{
				checkboxes.each(function(checkbox)
				{
					if (exclude.getAttribute('rel') != checkbox.id && ! ( checkbox.hasAttribute('rel') && checkbox.getAttribute('rel') == exclude.getAttribute('rel') ))
					{
						checkbox.checked = false;
					}
					else
					{
						checkbox.checked = true;
					}
				});
			});
		});
	});
	
	
	var more_or_less_button = productlistform.down('button.moreorless');
	more_or_less_button.observe('click', function(ev)
	{
		ev.stop();
		productlistform.toggleClassName('more');
		$('advanced').value = productlistform.hasClassName('more') ? 'true' : '';
	});
	
}












function init()
{
	avoidSpam();
	activateProductlistform();
	menus();
	styleMyForms();
	resizeImagesInForum();
	arrangeHalfColouredBoxes();
	arrangeMaincontentBoxes();
	centerLogo();
}

document.observe('dom:loaded', init);