/* $Id: project.js 164 2008-10-06 11:41:27Z christofh $ */
/*
	minidoc:
	The four main function (countries, formats, parameters & browser) are initialized on each reload.
	Each function has several options to pass information on to and therefore influence the results.
*/
function output(msg, isAlert) {
	/* 
	 * author: tl, tiborlegat@e-7.com
	 * date: 10.08.2009
	 * for debugging purposes. Outputs to console when it's available and 
	 * 2nd param isn't set. Otherwise alert to avoid js errors in browsers 
	 * without console. Tested only with firebug console on win xp.
	 */
	(typeof isAlert != 'undefined' || typeof console == 'undefined') 
	? alert(msg) 
	: console.log(msg);
}

var pk;
if (!pk) {
    pk = {}
}

$.extend(pk, {
	// onload
	init: function() {
		// Variable Setup: variables to notice user changes of count & country
		isChangedCount = isChangedCountry = false;
		// setup: variables for script performance

		baseForm = $('#mainform');
		base = ['length','width','height','weight'];

		try {
			pk.ie.init()
			pk.countries.init()
			pk.formats.init(false, subformat || false)  // subformat = 'Versandtasche DIN B5'
			pk.parameter.init(false, dimensions || false, subformat || false, pk.disableditems || false) // dimensions = name of format category (e.g. 'Versandtasche'); subformat see above; pk.disableditems = array/dictionary
			pk.browser.init(false, shiptype || false) // first entry is for values, shiptype = e.g. 'rollenformat'. consider lower/upper case transition between front-/backend
			pk.specialcases.pkr501.init()
		}
		catch (e) {
			//output(e)
		}
		
		
		pk.pulldown()
		// iefix for divs overlapping selects
		if (isOldIE) {
			$('.products .pulldown').bgiframe()
			// using bgiframe on preloader currently destroys layout afterwards...
			// need pngFix for this single image?
		}

		
		// remove 'Bitte wählen' when js is enabled.
		$('select[name="add_combination"]').find('option[value="default_none"]').remove()
		
		// startpage right-hand side: link execution after slideUp
		$('.start ul li a').each(function(){
			$(this).bind('click', function(e) {
				delay_link = $(this).attr('href')
				e.preventDefault()
				$('ul.pulldown').slideUp(200, function() {
					// additional delay for a smooth transition after slideUp
					window.setTimeout("window.location.href = delay_link",100)
				})
			})
		})

		// add tooltips for promotions
		$('a','.promo-2').each(function(){
			if ($(this).attr('title')!='') {
				$(this).append('<div class="tooltip">' + $(this).attr('title') + '</div>')
				$(this).removeAttr('title')
			}
		})

		// 'activate' submit button on first change
		$('input, select, .ac_results').not('#pref_svc_secure,#pref_svc_mass,#pref_svc_speed,#pref_svc_values').one('change', function(){
			$('#btn-calc').removeClass('off')
		})

		// show when all initializations are done
		$('#preloader').livequery(
			function(){ 
				$(this).hide() 
				$('.page').addClass('visible')
			}
		)
		baseForm.livequery(
			function(){ $(this).removeAttr('style') }
		)

		// Auto submit on editable/clickable fields
		//[tl, PKR-125, 18.09.2009: Maximalwert Versicherung als Berechnungsgrundlage]
		$('.services select, .services input:text').not('[name="insert_item"],#insert_height').change(function(){
			if ($(this).attr('name') == 'add_versicherung' && $(this).val()=='add_versichert') {
				insuranceRange = $(this).find(':selected').text()
				insuranceVal = insuranceRange.substr(insuranceRange.indexOf(' ')+1)
				$(this).after('<input type="hidden" id="add_wert" name="add_wert" value="'+insuranceVal+'" />')
			}
			$('#dimensions').remove()

			// validate before submitting
			if (pk.validator.send()) {
				baseForm.submit()
			}
		})
		// presse national basket: set default '1 mm' for bills 
		$('select[name="insert_item"]').change(function(){
			if($(this).val().substr(0,4) == 'bill') {
				$('#insert_height').val('1 mm')
			}
		})

		// checks if a valid number has been entered
		$('#count').change(function(){
			if($(this).val() <= 0) {
				newCount = (current_count > 0) ? current_count : 1
				$(this).val(newCount)
			} else if ($(this).val() != current_count) {
				isChangedCount = true
			}
		}).focus()

		
		// submit on div click
		$('#btn-calc').click(function(e) {
			e.preventDefault();
			// validate before submitting
			if (pk.validator.countryinput() && pk.validator.send()) {
				baseForm.submit()
			}
		})
		
		//
		// validate before submit, error handling
		baseForm.submit(function(){
			$('#preloader').show();
			$('.visible').removeClass('visible');
			if ($('#shiptype').length > 0 && $('#shiptype').val()=='') {
				$('#shiptype').remove()
			}
			return true
		})
		
		// checkboxes right col beneath 'services'
		$('.services :checkbox').one('click', function() {
			clicked = $(this).attr('id') 
			if (clicked == 'add_e' && $('#add_e:checked').length > 0) {
				$('select[name="add_combination"]').removeAttr('disabled')
			} else {
				$('select[name="add_combination"]').attr('disabled','disabled')
			}
			if (pkcformula == 'int.brief' && clicked == 'einschreiben' && $('#einschreiben:checked', '.services').length == 0) {
				$('#rueckschein:checked, #nachnahme:checked, #eigenhaendig:checked').removeAttr('checked')
			}
			
			if (pkcformula == 'nat.postwurfspezial') {
				if (clicked == 'svc_dp' && $('#svc_dp:checked', '.services').length == 0) {
					$('#svc_etikett:checked, #svc_dicke:checked').removeAttr('checked')
				}
				if (clicked == 'svc_etikett' && $('#svc_dicke:checked', '.services').length > 0) {
					$('#svc_dicke:checked').removeAttr('checked')
				}
				if (clicked == 'svc_dicke' && $('#svc_etikett:checked', '.services').length > 0) {
					$('#svc_etikett:checked').removeAttr('checked')
				}
			}
			
			// validate before submitting
			if (pk.validator.send()) {
				baseForm.submit()
			}
		})
		
		// remove messages on click
		$('.msg').click(function(){
			$(this).fadeOut(300)
		})
		
		// empty/fill input fields with default
		var defaultval = ''
			
		$('#add_wert')
		.focus(function() {
			defaultval = $(this).val()
			$(this).val('')
		})
		.blur(function() {
			if ($(this).val() == '') {
				$(this).val(defaultval)
			}
		})
	},
	pulldown: function(selector) {
		if (typeof selector == 'undefined' || selector == '') {
			selector = '.pulldown'
		}

		// prep pulldowns
		$(selector).each(function(){
			var c = $(this)
			c.wrap('<div class="pulldown-wrap ' + (c.attr('class') || '') + '"></div>')
			var wrap = c.parent('div')
			var handleContent = this.title ? this.title : $('.selected', c).html()
			this.title = '' // remove to prevent tooltip
			c.hide()
			wrap.prepend('<b class="selected clearfix">' + handleContent + '</b>').show()

			// click: open; hover out: close. remove click to avoid firing second click and delay
			function wrap_pulldown(){
				wrap.addClass('pulldown-open')
				if (isOldIE) {
					c.show()
				} else {
					c.slideDown(200)
				}
				$(this).unbind('click',wrap_pulldown)
			}

			wrap.click(wrap_pulldown)
			.hover(
				function(){},
				function(){
					if (isOldIE) {
						c.hide()
						wrap.removeClass('pulldown-open')
					} else {
						c.slideUp(100, function() {
							wrap.removeClass('pulldown-open')
						})
					}
					$(this).bind('click',wrap_pulldown)
			})
		})
	},
	validator: {
		send: function() {
			// tests the users submitted values for a (valid) calculable combination
			// setup
			var errorlog = false
			var zerovalues = 0
		
			// test only measurements
			for (i=0, j=base; i<j.length;i++) {
				var val = $('#' + base[i]).val()
				if (typeof val != 'undefined') {
					val = val.replace(/,/,'.') // replacement for parseFloat to work
					if (parseFloat(val) == '0' && !(base[i] == 'height' && (shiptype == 'karte' || shiptype == 'rollenformat')) ) {
						zerovalues++
					}
				} else {
					// application error?
					errorlog = true
				}
			}
			if (!errorlog && (zerovalues == 0 || (zerovalues == 4 && (isChangedCount || isChangedCountry))) ) {
				return true
			} else {
				if ($('#directhint').text()=='') {
					$('.leftcol h2').after(
						'<div class="msg msg-error" id="directhint" style="display:none">'+
							'<p>Sie müssen für eine Produktberechnung eine der folgenden Aktionen ausführen:</p>'+
							'<ul>'+
								'<li>ein Format auswählen</li>'+
								'<li>die vier Maße angeben</li>'+
								'<li>Land oder Stückzahl anpassen</li>'+
							'</ul>'+
						'</div>')
					$('#directhint').fadeIn().click(function(){
						$(this).fadeOut(400, function() {
							$(this).remove()
						})
					})
				} else {
					$('#directhint').recover().pulse({
						runLength: 1, 
						speed: 400, 
						backgroundColors: ['#f00', '#eceae6', '#f00'],
						duration: 800
					})
				}
				return false
			}
		},
		countryinput: function(){
			// converts input, always returns true
			
			// updates country options when user changed country by typing manually without autocompleter
			/*	
			 	NOTICE: if the user types alias country names, this function can't handle them. 
				Therefore, the backend has its own alias list and returns the correct value.
				To trigger backend testing on #ac_country, #country must be empty.
			*/
			if ($('#ac_country').val() != $('#country_name').val()) {
				var fullname = ''
				var iso3 = ''
				var data = $('#ac_country').val().toLowerCase()
				var dataLen = data.length
				$('.select2list li a').each( function() {
					var t = $(this).text().toLowerCase()
					if (t.length >= dataLen && t.substr(0,dataLen) == data) {
						var thisHref = $(this).attr('href')
						paramIndex = thisHref.indexOf("#");
						iso3 = thisHref.substr(paramIndex+1)
						fullname = t
						return false
					}
				})
				if (fullname=='') {
					// if no result, country given could be an alias
					// so, check for matching alias and then search for the aliased country again
					var newData = ''
					for (i=0,y=pk.COUNTRIES.length;i<y;i++) {
						c = pk.COUNTRIES[i]
						if (c.indexOf('|') >= 0) {
							newData = c.substr(0,c.indexOf('|')).toLowerCase()
						}
						if (newData != '' && newData == data) {
							data = c.substr(c.indexOf('|')+1).toLowerCase()
							dataLen = data.length
							break
						}
					}
					$('.select2list li a').each( function(i) {
						var t = $(this).text().toLowerCase()
						if (t.length >= dataLen && t.substr(0,dataLen) == data) {
							var thisHref = $(this).attr('href')
							paramIndex = thisHref.indexOf("#");
							iso3 = thisHref.substr(paramIndex+1)
							fullname = t
							return false
						}
					})
				}
				$('input[name="country"]').val(iso3).change()
				$('input[name="country_name"]').val(fullname)
				isChangedCountry = true
			}
			return true
		}
	},

	ie: {
		init: function() {
			//check IE once
			isOldIE = ($.browser.msie && $.browser.version < 7)
			isIE = (navigator.userAgent.indexOf('MSIE') != -1)
			if (isIE) {
				$('.format_presets :first-child').addClass('firstChild')
				$('.minibrowser a:last-child').addClass('lastChild')
				
				// fix to provide tooltips.
				$('.promo-2 a').each(function() {
					$(this).hover(
						function(){ $(this).find('.tooltip').show() },
						function(){ $(this).find('.tooltip').hide() }
					)
				})
				if(isOldIE) {
					
					// CSS SUPPORT
					// styling helper
					var test = 0
					$('.pulldown li').each(function(){
						var t = $(this)
						if (t.hasClass('other')) {
							test = 1
							t.addClass('tiny')
						} else if (test > 0 ) {
							t.addClass('tiny')
							if (t.hasClass('lastChild')) {
								return false
							}
						}
					})
					
					// interactivity helper
					$('#btn-calc').hover(
						function(){ $(this).addClass('btn-calc-hover') },
						function(){ $(this).removeClass('btn-calc-hover') }
					)

					if (!$('.format_presets b').hasClass('no-subformat')) {
						$('.format_presets b').hover(
							function(){ $(this).addClass('hover') },
							function(){ $(this).removeClass('hover') }
						)
					}

					$('.products').hover(
						function(){ $(this).addClass('products-hover') },
						function(){ $(this).removeClass('products-hover') }
					)
				}
			}
		}
	},
	
	
	// all country related input
	countries: {
		// init autocomplete, country selections
		init: function() {
		// Pre-select autocomplete field
			var select = $('#country')
			
		// CODE CONVERSION: select -> ul
		// select field is converted to a list
			var newList = ''
			var optgroups = ''
			iso3 = ''
			label = ''
			
			$('optgroup', 'select#countryselect').each(function(){
				label = $(this).attr('label')
				optgroups += '<li><h3>'+label+'</h3></li>'
			
				$(this).find('option').each(function() {
					selected = ($(this).attr('selected')) ? ' class="selected"' : ''
					iso3 = $(this).val()
					label = $(this).text()
					optgroups += '<li'+selected+'><a href="#' + iso3 + '">' + label + '</a></li>'
				})
			}) 
			newList = '<div class="select2list"><ul>'+ optgroups +'</ul></div>'
			$('select#countryselect').before(newList).remove()

			var select2List = $('.select2list')

		// AUTOCOMPLETE
			$('.countcountry').append('<input id="ac_country" name="ac_country" value="' + country_name + '" />')
			$('#ac_country')
			.autocomplete(pk.COUNTRIES,{
				formatResult: function(row) {
					var index = row[0].indexOf('|')
					if (index != '-1') {
						row[0] = row[0].substr(index+1)
					}
					return row
				}
			})
			.result( function(event, data, formatted) {
				if (data) { // = country name
					iso3 = ''
					fullname = ''
					dataLen = String(data).length
					select2List.find('li a').each( function() {
						if ($(this).text().length >= dataLen && $(this).text().substr(0,dataLen) == data) {
							fullname = data
							thisHref = $(this).attr('href')
							paramIndex = thisHref.indexOf("#");
							iso3 = thisHref.substr(paramIndex+1)
							return false
						}
					})
					$('input[name="country"]').val(iso3).change()
					$('input[name="country_name"]').val(fullname)
					$('#btn-calc input').focus()
					
					isChangedCountry = (fullname != country_name)
				}
			})

			
		// EVENT CONVERSION: a -> input
		// the converted list links are retranslated to an input field
			select2List.find('li a').click(function(e){
				e.stopPropagation() // still necessary?
				thisHref = $(this).attr('href')
				paramIndex = thisHref.indexOf("#");
				iso3 = (thisHref.substr(paramIndex+1)) 
						? thisHref.substr(paramIndex+1) 
						: '' 
				$('input[name="country"]').val(iso3)
	
				fullname = ($(this).text()) 
						? $(this).text()
						: '' 
				$('input[name="country_name"], #ac_country').val(fullname).change()
	
				isChangedCountry = (fullname != country_name)
	
				$('#ac_country').show()
				select2List.removeClass('select2list_active')
				return false
			})

			
		// TOGGLE AUTOCOMPLETE - LIST/DROPDOWN
			select2List.click(function(){
				$(this).addClass('select2list_active').focus()
				
				$('#ac_country').hide()
				$(this).hover(
					function() { },
					function() {
						$('#ac_country').show()
						$(this).removeClass('select2list_active')
					}
				)
			})
			if (isOldIE) {
				select2List.hover(
					function(){ $(this).addClass('select2list-hover') },
					function(){ $(this).removeClass('select2list-hover') }
				)

				select2List.find('ul, li').hover(  // check this filter!!
					function(){ $(this).addClass('hover') }, 
					function(){ $(this).removeClass('hover') }
				)
			}
		}
	},

	// format selection
	formats: {
		VALUES:{
			'Format w&auml;hlen': {shiptype: ''},
			'Postkarte': {
				length: 'bis 23,5 cm',
				width: 'bis 12,5 cm',
				weight: 'bis 14,7 g',
				shiptype: 'karte',
				section: true
			},
			'Briefumschlag': {
				length: 'bis 23,5 cm',
				width: 'bis 12,5 cm',
				height: 'bis 5 mm',
				weight: 'bis 20 g',
				shiptype: 'umschlag',
				section: true
			},
			'Briefumschlag DIN B6':{
				length: '17,6 cm',
				width: '12,5 cm',
				shiptype: 'umschlag'
			},
			'Briefumschlag DIN C6':{
				length: '16,2 cm',
				width: '11,4 cm',
				shiptype: 'umschlag'
			},
			'Briefumschlag DIN Lang':{
				length: '22 cm',
				width: '11 cm',
				shiptype: 'umschlag'
			},
			'Briefumschlag DIN C6/5':{
				length: '22,9 cm',
				width: '11,4 cm',
				shiptype: 'umschlag'
			},
			'Versandtasche': {
				length: 'bis 35,3 cm',
				width: 'bis 25 cm',
				height: 'bis 2 cm',
				weight: 'bis 500 g',
				shiptype: 'versandtasche',
				section: true
			},
			'Versandtasche DIN A5':{
				length: '21 cm',
				width: '14,8 cm',
				shiptype: 'versandtasche'
			},
			'Versandtasche DIN C5':{
				length: '22,9 cm',
				width: '16,2 cm',
				shiptype: 'versandtasche'
			},			
			'Versandtasche DIN B5':{
				length: '25 cm',
				width: '17,6 cm',
				shiptype: 'versandtasche'
			},
			'Versandtasche DIN A4':{
				length: '29,7 cm',
				width: '21 cm',
				shiptype: 'versandtasche'
			},
			'Versandtasche DIN C4':{
				length: '32,4 cm',
				width: '22,9 cm',
				shiptype: 'versandtasche'
			},
			'Versandtasche DIN B4':{
				length: '35,3 cm',
				width: '25 cm',
				shiptype: 'versandtasche'
			},
			'Versandtasche DIN C3':{
				length: '45,8 cm',
				width: '32,4 cm',
				height: 'bis 11,8 cm',
				shiptype: 'versandtasche'
			},
			'Paket/Päckchen': {
				length: 'bis 45 cm',
				width: 'bis 30 cm',
				height: 'bis 15 cm',
				weight: 'bis 2 kg',
				shiptype: 'quaderformat',
				section: true
			},
			'Packset XS': {
				length: '22,5 cm',
				width: '14,5 cm',
				height: '3,5 cm',
				shiptype: 'quaderformat'
			},
			'Packset S': {
				length: '25 cm',
				width: '17,5 cm',
				height: '10 cm',
				shiptype: 'quaderformat'
			},
			'Packset M': {
				length: '37,5 cm',
				width: '30 cm',
				height: '13,5 cm',
				shiptype: 'quaderformat'
			},
			'Packset L': {
				length: '45 cm',
				width: '35 cm',
				height: '20 cm',
				shiptype: 'quaderformat'
			},
			'Packset F': {
				length: '38 cm',
				width: '12 cm',
				height: '12 cm',
				shiptype: 'quaderformat'
			},
			'Rolle': {
				length: 'bis 80 cm',
				width: 'bis 11 cm',
				weight: 'bis 2 kg',
				shiptype: 'rollenformat',
				section: true
			},
			'Rolle groß': {
				length: 'bis 120 cm',
				width: 'bis 15 cm',
				weight: 'bis 5 kg',
				shiptype: 'rollenformat' 
			},
			'Flyer': {
				length: 'bis 23,5 cm',
				width: 'bis 12,5 cm',
				height: 'bis 5 mm',
				weight: 'bis 20 g',
				shiptype: 'flyer',
				section: true
			},
			'Katalog': {
				length: 'bis 35,3 cm',
				width: 'bis 25 cm',
				height: 'bis 5 cm',
				weight: 'bis 1 kg',
				shiptype: 'katalog',
				section: true
			},
			'Presseartikel': {
				length: 'bis 35,3 cm',
				width: 'bis 25 cm',
				height: 'bis 5 cm',
				weight: 'bis 1 kg',
				shiptype: 'presseartikel',
				section: true
			},
			'Berliner Format': {
				length: '47 cm',
				width: '31,5 cm',
				shiptype: 'presseartikel'
			},
			'Rheinisches Format': {
				length: '51 cm',
				width: '35 cm',
				shiptype: 'presseartikel'
			},
			'Nordisches Format': {
				length: '57 cm',
				width: '40 cm',
				shiptype: 'presseartikel'
			},
			'Halbnordisches Format': {
				length: '40 cm',
				width: '28,5 cm',
				shiptype: 'presseartikel'
			},
			'Freies Format': {
				length: '22 cm',
				width: '11 cm',
				height: '5 mm',
				weight: '20 g',
				shiptype: 'freiesformat',
				section: true
			}
		},
		init: function(values, formatlabel) {
			// setup
			values = values || pk.formats.VALUES
			formatlabel = formatlabel || ''
			selected = (shiptype != '') ? shiptype : ''

			// add formats
			var formats = '<div class="format_presets"><b>{{selected}}</b>'+
				'{{items}}</div>'
			var ITEM = '<li>{{value}}</li>'	
			var SECTION = '<li class="section">{{value}}</li>'
	
			var items = [];
			var i = 0;
			var hideSection = true;
			var replaced = false;
			var currentSection = '';
			for (v in values) {
				// Adaption of format list by format browser
				tShiptype = values[v].shiptype
				if (typeof values[v].section != 'undefined') {
					currentSection = v;
				}
				if (formatlabel != '') {
					if (v == formatlabel) {
						var isSameSubFormat = true;
						for (i=0,j=base.length;i<j;i++) {
							var currentDimension = base[i]
							var subformatValue = values[v][currentDimension]
							if (typeof subformatValue != 'undefined' && subformatValue != $('#'+currentDimension).val()) {
								isSameSubFormat = false;
							}
						}
						if (isSameSubFormat) {
							formats = formats.replace('{{selected}}', v);
							replaced = true;
						} else {
							// possibly another subformat from same category / shiptype
							for (x in values) {
								if (values[x].shiptype!=tShiptype) {
									continue
								} else {
									var matchDim = undefinedDim = 0
									for (i=0,j=base.length;i<j;i++) {
										var currentDimension = base[i]
										var subformatValue = values[x][currentDimension]
										// subformatValue.match(/(bis\s?)?((\d+)(,\d+)?)\s?(mm|cm|kg|g)/i)
										// need an exact match, watch spaces and so on.
										if (typeof subformatValue == 'undefined' || typeof subformatValue != 'undefined' && subformatValue != $('#'+currentDimension).val()) {
											if (typeof subformatValue == 'undefined') {
												undefinedDim++;
											}
											continue;
										} else {
											matchDim++;
										}
									}
									if (matchDim+undefinedDim == 4) {
										// all 4 base dimensions didn't fail, either pass or undefined
										formats = formats.replace('{{selected}}',x);
										replaced = true;
										break;
									}
								}
							}
						}
						break;
					}
				} else if (selected == tShiptype) {
					formats = formats.replace('{{selected}}', v)
					replaced = true;
				} 

				//compare sections with html and hide unavailable sections as well as their children 
				if (values[v].section) {
					hideSection = true
					$('.formatbrowser a').each(function(w){
						if ($(this).attr('class') == values[v].shiptype) {
							hideSection = false
							return false
						}
					})
				}

				// remove other formats if it's not 'freies format' or 'Format wählen' -> skipping push commands
				// hide child elements from hidden sections
				if ((tShiptype != selected && selected != 'freiesformat') &&
					(tShiptype != selected && selected != '') ||
					(tShiptype == '' && selected == 'freiesformat') ||
					hideSection) {
					continue
				}
				if (values[v].section) {
					items.push(SECTION.replace('{{value}}', v))
				} else {
					items.push(ITEM.replace('{{value}}', v))
				}
				i++
			}
			if (!replaced) {
				formats = formats.replace('{{selected}}', currentSection)
				$('#shiptype').val(values[currentSection].shiptype)
			}

			var newFormats = ''
			var noSubFormat = false
			if (items.length > 1) { /* no dropdown for elements without subformat */
				itemList = '<ul class="inline">'+items.join('')+'</ul>'
				newFormats = formats.replace('{{items}}', itemList) 
			} else {
				newFormats = formats.replace('{{items}}', '')
				noSubFormat = true
			}

			if ($('.box .format_presets').length > 0) {
				$('.box .format_presets').replaceWith(newFormats)
				$('.box .format_presets b').recover().pulse({
					runLength: 1, 
					speed: 250, 
					backgroundColors: ['#eceae6', '#fc0', '#eceae6'],
					duration: 800
				})
			} else {
				$('.box').append(newFormats)
				if (noSubFormat) {
					$('.format_presets b').addClass('no-subformat')
				}
			}

			// add interaction
			var formats = $('.format_presets')
			var selected = formats.find('b')
			var options = formats.find('ul')


			// click: open; hover out: close
			formats.click(function(e){
				options.slideDown(100)
			})
			.hoverIntent(
				function() {},
				function() {
					options.slideUp(100)
				})


			options.find('li').each(function() {
				var o = $(this)
				if (isOldIE) {
					o.hover( /* < IE 7 fix */
						function() { o.addClass('hover') },
						function() { o.removeClass('hover')	}
					)
				}
				o.click(function(e){
					/* selection of clicked list element, setting values in dropdowns */
						e.stopPropagation()
						$('.box .format_presets b').html(o.html())
						options.slideUp(100)

						// pushing attributes into hidden fields 
						// excluding default 'format wählen'
						var tShiptype = values[o.html()].shiptype
						if (tShiptype != '') {
							// set format values
							$('#subformat').val(o.html())
							$('#shiptype').val(tShiptype) 
							title = pk.browser.VALUES[tShiptype].name
							$('#dimensions').val(title)

							for (f in values) {
								if (f == o.html()) {

									// get parents default values when dimension is missing
									var formatParent;
									if (!o.hasClass('section')) {
										formatParent = o.prevAll('.section').html()
										
										for (i=0,j=base.length;i<j;i++) {
											if (typeof values[f][base[i]] == 'undefined') {
												var parentval = values[formatParent][base[i]];
												$('input[name="'+base[i]+'"]').val(parentval);
											}
										}
									}
									for (attribute in values[f]) {
										if ($('input[name="'+attribute+'"]').length > 0) {
											$('input[name="'+attribute+'"]').val(values[f][attribute])
										} else {
											baseForm.prepend('<input type="hidden" name="' + attribute + '" value="' + values[f][attribute] + '" />')
										}
									}
									break
								}
							}
							if (pk.validator.send()) {
								baseForm.submit()
							}
						}
					})
			})
		}
	},
	
	
	// format browser
	browser: {
		VALUES: {
			'karte': {
				id: "karte",
				name: "Postkarte"
			},
			'umschlag': {
				id: "umschlag",
				name: "Briefumschlag"
			},
			'versandtasche': {
				id: "versandtasche",
				name: "Versandtasche"
			},
			'quaderformat': {
				id: "quaderformat",
				name: "Paket/Päckchen"
			},
			'rollenformat': {
				id: "rollenformat",
				name: "Rolle"
			},
			'freiesformat': {
				id: "freiesformat",
				name: "Freies Format"
			},
			'flyer': {
				id: "flyer",
				name: "Flyer"
			},
			'katalog': {
				id: "katalog",
				name: "Katalog"
			},
			'presseartikel': {
				id: "presseartikel",
				name: "Presseartikel"
			}
		},
		init: function(values, selected){
			var browservalues = values || pk.browser.VALUES
			var selected = selected || ''
			$('.formatbrowser').each(function(){
			// setup
				var f = $(this)
				var items = []

				// big browser: all elements have the same size, medium image size 
				var bigbrowser = '<div class="browser clearfix">{{items}}</div>';
				var BIGITEM = '<a href="#" class="{{class}}" title="{{name}} auswählen">{{name}}</a>'
				
				// tiny browser: a single elements is highlighted with a big image, all options are still available as thumbnails
				var tinybrowser = '<div class="format {{currentid}}"><div class="minibrowser clearfix">{{items}}</div></div>' // whenever a format is chosen
				var TINYITEM = '<a href="" class="{{class}}" title="{{name}} auswählen">{{name}}</a>'

			// generating graphical browser content
				// grab the existing items (html) and compare to browservalues
				activeShiptype = ''

				if (selected == '') {
					//choose browser with same size icons 
					template = bigbrowser
					ITEM = BIGITEM
				} else {
					//choose browser with a big background image & mini icons
					template = tinybrowser
					ITEM = TINYITEM
				}

				f.find('a').each(function() {
					var currentShiptype = $(this).attr('class')
					if (selected == currentShiptype) {
						activeShiptype = currentShiptype
					} else {
						var i = 0;
						// grab each property and replace template strings
						for (z in browservalues[currentShiptype]) {
								if (i == 0) { 
									// get ITEM once
									currentItem = ITEM
									currentItem = currentItem.replace('{{class}}',currentShiptype)
								}
								property = browservalues[currentShiptype][z]
								currentItem = currentItem.replace('{{'+z+'}}',property)
								i++
						}
						items.push(currentItem.replace('{{'+z+'}}',property))
					}
				})

				// OUTPUT: fill formatbrowser template and replace current html
				template = template.replace('{{items}}', items.join(''))
				template = template.replace('{{currentid}}', activeShiptype) // place f-class on tinybrowser in order to apply background image 
				f.html(template) // replace html with generated templates


				// click event trigger has to follow html replacement!
				// setting value for hidden field shiptype (necessary for backend, too.)
				f.find('a').click(function(){
					$('#shiptype').val($(this).attr('class'))
					$('#subformat, #pkcformula').remove() // reset subformat & pkcformula

					title = browservalues[$(this).attr('class')].name
					$('#dimensions').val(title)
					
					// backend info for calculation, redundant.
					for (f in pk.formats.VALUES) {
						if (pk.formats.VALUES[f].section && pk.formats.VALUES[f].shiptype == $(this).attr('class')) {
							formatobj = pk.formats.VALUES[f]
							for (val in formatobj) {
								if (val == 'length' || val == 'width' || val == 'height' || val == 'weight') {
									$('form').prepend('<input type="hidden" name="' + val + '" value="' + formatobj[val] + '" />')
								}
							}						
						}
					}
					
					baseForm.submit()
					return false /* IMPORTANT!! Otherwise, submitted form values will be overwritten immediately */
				})
			})
		}
	},
		
	// parameter selection dropdowns
	parameter: {
		VALUES: {
			length: ['bis 23,5 cm', 'bis 35,3 cm', 'bis 60 cm', 'bis 90 cm', 'bis 120 cm'], 
			width: ['bis 12,5 cm', 'bis 15 cm', 'bis 25 cm', 'bis 30 cm', 'bis 35 cm', 'bis 60 cm'], 
			height: ['bis 0,5 cm', 'bis 1 cm', 'bis 2 cm', 'bis 5 cm', 'bis 15 cm', 'bis 20 cm', 'bis 60 cm' ], 
			weight: ['bis 20 g', 'bis 50 g', 'bis 500 g', 'bis 1 kg', 'bis 2 kg', 'bis 5 kg', 'bis 10 kg', 'bis 20 kg', 'bis 31,5 kg']
		},
		init: function(values, dimensions, subformat, unavailable) {
			// setup
			values = values || pk.parameter.VALUES
			dimensions = dimensions || ''
			subformat = subformat || ''
			unavailable = unavailable || ''

			var LIST = '<div class="options"><ul class="inline">{{items}}</ul></div>'
			var ITEM = '<li>{{value}}</li>'
			var ITEM_UNAVAILABLE = '<li class="unavailable" title="Dieser Wert ist nicht mit dem ausgewählten Produkt kombinierbar">{{value}}</li>'


			$('#btn-calc').before('<p id="msg-parameterselection" class="msg"></p>')
			var msg = $('#msg-parameterselection')

			$('.parameterselection').each(function() {
				// setup
				var s = $(this)
				var v = s.find('input')
				var title = v.attr('title')
				v.removeAttr('title')
				var values = pk.parameter.VALUES[v.attr('id')]
				pulseoptions = {
					runLength: 2, 
					speed: 250, 
					backgroundColors: ['#fff', '#fc0', '#fff'],
					duration: 1500
				}

				// hide inapplicable dimensions
				if (typeof shiptype != 'undefined' && v.attr('id')=='height' && (shiptype == 'karte' || shiptype == 'rollenformat')) {
					baseForm.prepend('<input type="hidden" value="0" id="height" name="height" />')
					s.remove()
					return
				}

				// show/hide help text
				v.focus(function() {
					msg.text(title).addClass('msg-info')
					})
				.blur(function() {
					msg.text('').removeClass('msg-info')
					})

				// fill and add list
				var items = []
				if (unavailable != '') {
					for (var i=0; i<values.length; i++) {
						un = unavailable[v.attr('id')].join().indexOf(values[i]) // search item in string
						if (un > -1) {
							items.push(ITEM_UNAVAILABLE.replace('{{value}}', values[i]))
						} else {
							items.push(ITEM.replace('{{value}}', values[i]))
						}
					}
				} else {
					for (var i=0; i<values.length; i++) {
						items.push(ITEM.replace('{{value}}', values[i]))
					}
				}
				s.append(LIST.replace('{{items}}', items.join('')))
				
				
				// add interaction
				var optionlist = s.find('.options>ul') 
				s.find('.options')
				.click(function() {
					optionlist.slideDown(100)
				})
				.hoverIntent(
					function() {},
					function() {
						optionlist.slideUp(100)
				})
			
				s.find('li').click(function(e) {
					e.stopPropagation()
					v.val( $(this).text()).change()
					optionlist.hide()

					// setting user values in hidden fields for use after reload
					$('#dimensions').remove()
				})
				
				
				// ie6 'hover list elements' fix
				if (isOldIE) {
					s.find('li').hover(function() {
						$(this).addClass('hover')
					}, function() {						
						$(this).removeClass('hover')
					})
				}

				// update selected values (if a format change occurred) - this reacts on shiptype and subformat
				if ((previous_shiptype != '' && shiptype != previous_shiptype) || subformat != previous_subformat) {
					if (subformat != '') {
						updatevalues = pk.formats.VALUES[subformat]
					} else {
						updatevalues = pk.formats.VALUES[dimensions]
					}
					
					for (u in updatevalues) {
						switch (u) {
						case 'length':	$('#'+base[0]).val(updatevalues[u]).recover().pulse(pulseoptions);break;
						case 'width':	$('#'+base[1]).val(updatevalues[u]).recover().pulse(pulseoptions);break;
						case 'height':
							if (updatevalues[u] != 'f1' && updatevalues[u] != 'f5') {
								$('#'+base[2]).parent().show();
								$('#'+base[2]).val(updatevalues[u]).recover().pulse(pulseoptions);
							} else if (updatevalues[u] == 'f1' || updatevalues[u] == 'f5') {
								$('#'+base[2]).parent().hide();
							}
							break;
						case 'weight':	$('#'+base[3]).val(updatevalues[u]).recover().pulse(pulseoptions);break;
						default:		break;
						}
					}
				}
			})
		}
	},
	specialcases: {
		pkr501: {
			// weight dimension naming
			updater: function() {
				currentValue = $('#weight').val()
				var index = currentValue.indexOf('bis ')
				if (index >= 0) {
					var x = currentValue.substr(index+4);
					$('#weight').val(x);
				}
			},
			init: function() {
				if (pkcformula.search(/int\.info(brief|post)\.\w+/) != '-1') {
					// update val once
					pk.specialcases.pkr501.updater()
					// update on change
					$('#weight').change(function(){
						pk.specialcases.pkr501.updater()
					})
				}
			}
		}
	}
})
// no 404
if ($('.application-error').length <= 0) {
	$(setTimeout(pk.init, 500))
}

/* global header & footer */
var v1;
if (!v1) {
    v1 = {}
}

$.extend(v1, {
    /* called onload */
    init: function(){
        // init all tabsets
        $('.head .tabset').tabset()
        
        // init search fields
        $('.head .input-text').each(function(){
            var ip = $(this)
            var def = ip.attr('value')
            ip.focus(function(){
                if (ip.attr('value') == def) {
                    ip.attr('value', '')
                }
            })
        })
    }
})
$(setTimeout(v1.init, 500))