/* $Id: project.js 2138 2010-06-07 11:09:28Z peterg $ */
var pk;
if (!pk) {
    pk = {}
}

$.extend(pk, {
	IE6: ($.browser.msie && $.browser.version < 7),
	GLOBAL: {
		// Variable Setup: variables to notice user changes of count & country
		isChangedCount: false,
		isChangedCountry: false,
		base: ['length','width','height','weight'],
		mainForm: $('#mainform'),
		btnCalc: $('#btn-calc'),
		dimensions: $('#dimensions'),
		inputCountryName: $('input[name="country_name"]'),
		inputShiptype: $('#shiptype'),
		selectAddCombination: $('select[name="add_combination"]')
	},
	// onload
	init: function() {
		// disable animations for ie6
		if (pk.IE6) { 
			$.fx.off = true
		}


		try {
			pk.ie.init()
			pk.countries.init()
			var shownLabel = 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, shownLabel || 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 (pk.IE6) {
			$('.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.
		pk.GLOBAL.selectAddCombination.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 services
		 * [tl, 21.05.2010, PKM-41: remove tooltips]
		$('div.services dt a.doubleinfo').hoverIntent(
			function(){ 
				$(this).prev('div.tooltip').fadeIn() 
			},
			function(){	 }
		).focus(function(){
			$(this).prev('div.tooltip').show()
		})
		$('div.services dt').mouseleave(function() {
			$(this).find('div.tooltip').fadeOut()
		})
		*/
		
		// add tooltips for promotions
		$('a','.promo-2').each(function(){
			var t = $(this)
			if (t.attr('title')!='') {
				t.append('<div class="tooltip">' + t.attr('title') + '</div>')
					.removeAttr('title')
			}
		})

		// 'activate' submit button on first change
		$('input, select, .ac_results').one('change', function(){
			pk.GLOBAL.btnCalc.removeClass('off')
		})

		// show when all initializations are done
		$('#preloader').livequery(
			function(){ 
				$(this).hide() 
				$('.page').addClass('visible')
			}
		)
		pk.GLOBAL.mainForm.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.replace(/^.*?([,.\-0-9].*)$/,'$1')
				$(this).after('<input type="hidden" id="wert" name="wert" value="'+insuranceVal+'" />')
				/* input, {
				 *		type: 'hidden',
				 *		id:'wert',
				 *		name:'wert',
				 *		value: insuranceVal
				 * } */
			}
			pk.GLOBAL.dimensions.remove()

			// validate before submitting
			if (pk.validator.send()) {
				pk.GLOBAL.mainForm.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(){
			var t = $(this)
			if(t.val() <= 0) {
				newCount = (current_count > 0) ? current_count : 1
				t.val(newCount)
			} else if (t.val() != current_count) {
				pk.GLOBAL.isChangedCount = true
			}
		}).focus()

		
		// submit on div click
		pk.GLOBAL.btnCalc.click(function(e) {
			e.preventDefault();
			// validate before submitting
			if (pk.validator.countryinput() && pk.validator.send()) {
				pk.GLOBAL.mainForm.submit()
			}
		})
		
		//
		// validate before submit, error handling
		pk.GLOBAL.mainForm.submit(function(){
			//bugfix: firefox back history
			//$('#preloader').show();
			//$('.visible').removeClass('visible');
			
			if (pk.GLOBAL.inputShiptype.length > 0 && pk.GLOBAL.inputShiptype.val()=='') {
				pk.GLOBAL.inputShiptype.remove()
			}
			return true
		})
		
		// checkboxes right col beneath 'services'
		$('.services :checkbox').one('click', function() {
			var clicked = $(this).attr('id')
			if (clicked == 'add_e' && $('#add_e:checked').length > 0) {
				pk.GLOBAL.selectAddCombination.removeAttr('disabled')
			} else if ($('#add_e:checked').length == 0) {
				//[pg:PKR-520:11.01.2010]
				pk.GLOBAL.selectAddCombination.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()) {
				pk.GLOBAL.mainForm.submit()
			}
		})
		
		// remove messages on click
		$('.msg').click(function(){
			$(this).fadeOut(300)
		})
		
		// empty/fill input fields with default
		var defaultval = '',
			wert = $('#wert');
		
		wert
		.focus(function() {
			defaultval = wert.val()
			wert.val('')
		})
		.blur(function() {
			if (wert.val() == '') {
				wert.val(defaultval)
			}
		})
	},
	pulldown: function(selector) {
		if (typeof selector == 'undefined' || selector == '') {
			selector = '.pulldown'
		}

		// prep pulldowns
		$(selector).each(function(){
			var c = $(this),
				wrap = c.wrap('<div class="pulldown-wrap ' + (c.attr('class') || '') + '"></div>').parent(),
				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')
				c.slideDown(200)
				$(this).unbind('click',wrap_pulldown)
			}

			wrap.click(wrap_pulldown)
			.hover(
				function(){},
				function(){
					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,
				zerovalues = 0
		
			// test only measurements
			for (var i=0, j=pk.GLOBAL.base.length; i<j; i++) {
				var val = $('#' + pk.GLOBAL.base[i]).val()
				if (typeof val != 'undefined') {
					val = val.replace(/,/,'.') // replacement for parseFloat to work
					if (parseFloat(val) == '0' && !(pk.GLOBAL.base[i] == 'height' && (shiptype == 'karte' || shiptype == 'rollenformat')) ) {
						zerovalues++
					}
				} else {
					// application error?
					errorlog = true
				}
			}
			if (!errorlog && (zerovalues == 0 || (zerovalues == 4 && (pk.GLOBAL.isChangedCount || pk.GLOBAL.isChangedCountry))) ) {
				return true
			} else {
				
				var hint = $('#directhint') 
				if (hint.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 {
					hint.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 (pk.GLOBAL.inputACCountry.val() != pk.GLOBAL.inputCountryName.val()) {
				var fullname = '',
					iso3 = '',
					data = pk.GLOBAL.inputACCountry.val().toLowerCase(),
					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 (var 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
						}
					})
				}
				pk.GLOBAL.country.val(iso3).change()
				pk.GLOBAL.inputCountryName.val(fullname)
				pk.GLOBAL.isChangedCountry = true
			}
			return true
		}
	},

	ie: {
		init: function() {
			//check IE once
			isIE = (navigator.userAgent.indexOf('MSIE') != -1)
			if (isIE) {
				$('.format_presets :first-child').addClass('firstChild')
				$('.minibrowser a:last-child, .sum li:last-child').addClass('lastChild')
				
				// fix to provide tooltips.
				$('.promo-2 a').each(function() {
					var t = $(this),
						tooltip = t.find('.tooltip')
					t.hover(
						function(){ tooltip.show() },
						function(){ tooltip.hide() }
					)
				})

				if(pk.IE6) {
					var test = false,
						format_presets = $('.format_presets b'), 
						products = $('.products');

					// CSS SUPPORT
					// styling helper
					$('.pulldown li').each(function(){
						var t = $(this)
						if (t.hasClass('other')) {
							test = true
							t.addClass('tiny')
						} else if (test) {
							t.addClass('tiny')
							if (t.hasClass('lastChild')) {
								return false
							}
						}
					})
					
					// interactivity helper
					pk.GLOBAL.btnCalc.hover(
						function(){ pk.GLOBAL.btnCalc.addClass('btn-calc-hover') },
						function(){ pk.GLOBAL.btnCalc.removeClass('btn-calc-hover') }
					)
					products.hover(
						function(){ products.addClass('products-hover') },
						function(){ products.removeClass('products-hover') }
					)
					if (!format_presets.hasClass('no-subformat')) {
						format_presets.hover(
							function(){ format_presets.addClass('hover') },
							function(){ format_presets.removeClass('hover') }
						)
					}
				}
			}
		}
	},
	
	
	// all country related input
	countries: {
		// init autocomplete, country selections
		init: function() {
		// insert hidden field country, rename select#country to countryselect
			$('select#country').attr('id','countryselect')
			$.extend(pk.GLOBAL, {
				country: $('<input id="country" name="country" type="hidden"/>').prependTo('form#mainform')
			})
			$('select#countryselect').find('option').each(function(){
				if($(this).attr('selected')) {
					$('input#country').val($(this).val())
				}
			})
			
		// CODE CONVERSION: select -> ul
		// select field is converted to a list
			var newList = optgroups = iso3 = label = '';
			
			$('optgroup', 'select#countryselect').each(function(){
				var t = $(this)
				optgroups += '<li><h3>' + t.attr('label') + '</h3></li>'
			
				$(this).find('option').each(function() {
					var t = $(this),
						selected = (t.attr('selected')) ? ' class="selected"' : '';
					
					optgroups += '<li' + selected + '><a href="#' + t.val() + '">' + t.text() + '</a></li>'
				})
			}) 
			newList = '<div class="select2list"><ul>'+ optgroups +'</ul></div>'
			$('select#countryselect').before(newList).remove()

			var select2List = $('.select2list')

		// AUTOCOMPLETE
			$.extend(pk.GLOBAL, {
				inputACCountry: $('<input id="ac_country" name="ac_country" value="' + country_name + '" />').appendTo('.countcountry')
			})
			$('label[for="country"]').attr('for','ac_country')
			pk.GLOBAL.inputACCountry
			.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
						}
					})
					pk.GLOBAL.country.val(iso3).change()
					pk.GLOBAL.inputCountryName.val(fullname)
					$('#btn-calc input').focus()
					
					pk.GLOBAL.isChangedCountry = (fullname != pk.GLOBAL.inputCountryName)
				}
			})

		// 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) 
						: '' 
				pk.GLOBAL.country.val(iso3)
	
				fullname = ($(this).text()) 
						? $(this).text()
						: '' 
				$('input[name="country_name"], #ac_country').val(fullname).change()
	
				pk.GLOBAL.isChangedCountry = (fullname != country_name)
	
				pk.GLOBAL.inputACCountry.show()
				select2List.removeClass('select2list_active')
				return false
			})

			
		// TOGGLE AUTOCOMPLETE - LIST/DROPDOWN
			select2List.click(function(){
				var t = $(this)
				t.addClass('select2list_active').focus()
				
				pk.GLOBAL.inputACCountry.hide()
				t.hover(
					function() { },
					function() {
						pk.GLOBAL.inputACCountry.show()
						t.removeClass('select2list_active')
					}
				)
			})
			if (pk.IE6) {
				select2List.hover(
					function(){ t.addClass('select2list-hover') },
					function(){ t.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: '23,5 cm',
				width: '12,5 cm',
				weight: '14,7 g',
				shiptype: 'karte',
				section: true
			},
			'Briefumschlag': {
				length: '23,5 cm',
				width: '12,5 cm',
				height: '5 mm',
				weight: '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: '35,3 cm',
				width: '25 cm',
				height: '2 cm',
				weight: '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: '11,8 cm',
				shiptype: 'versandtasche'
			},
			'Paket/Päckchen': {
				length: '45 cm',
				width: '30 cm',
				height: '15 cm',
				weight: '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: '80 cm',
				width: '11 cm',
				weight: '2 kg',
				shiptype: 'rollenformat',
				section: true
			},
			'Rolle groß': {
				length: '120 cm',
				width: '15 cm',
				weight: '5 kg',
				shiptype: 'rollenformat' 
			},
			'Flyer': {
				length: '23,5 cm',
				width: '12,5 cm',
				height: '5 mm',
				weight: '20 g',
				shiptype: 'flyer',
				section: true
			},
			'Katalog': {
				length: '35,3 cm',
				width: '25 cm',
				height: '5 cm',
				weight: '1 kg',
				shiptype: 'katalog',
				section: true
			},
			'Presseartikel': {
				length: '35,3 cm',
				width: '25 cm',
				height: '5 cm',
				weight: '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 || '';	// current subformat

			// add formats
			var TPL_FORMAT_PRESETS = '<div class="format_presets"><b>{{selected}}</b>'+
							'{{items}}</div>',
				TPL_ITEM = '<li>{{value}}</li>',	
				TPL_SECTION = '<li class="section">{{value}}</li>'	
				currentLabel = shownLabel = '',
				hideSection = true,
				i = 0,
				items = [];
			
			// fill template list with filtered values
			for (var v in values) {
				
				// choose list item layout
				var tShiptype = values[v].shiptype,
					valueType = (values[v].section) ? TPL_SECTION : TPL_ITEM;

				// item is a section
				if (typeof values[v].section != 'undefined') {
					currentLabel = v;
				}
				// case: subformat is set
				if (formatlabel != '') {
					// find subformat for shown label
					if (v == formatlabel) {
						
						var isSameSubFormat = true,
							currentDimension,
							subformatValue,
							subformatSection;

						// compare subformat dimensions with chosen dimensions.
						// available dimensions must match, otherwise flag "isSameSubFormat"
						for (var i=0,j=pk.GLOBAL.base.length; i<j ;i++) {
							currentDimension = pk.GLOBAL.base[i];
							subformatValue = values[v][currentDimension];
							if (typeof subformatValue != 'undefined' && subformatValue != $('#'+currentDimension).val()) {
								isSameSubFormat = false;
							}
						}
						
						// choose given subformat as label
						if (isSameSubFormat) {
							TPL_FORMAT_PRESETS = TPL_FORMAT_PRESETS.replace('{{selected}}', v);
							shownLabel = values[v].shiptype;
						} else {
							// dimensions don't match, can't be the given subformat
							// possibly another subformat from same category / shiptype
							// search all values for a match
							// note section in case of failure
							for (var x in values) {
								
								//skip values with different shiptype
								if (values[x].shiptype!=tShiptype) {
									continue
								} else {
									// note section
									if (values[x].section) {
										subformatSection = x
									}
									
									var processedResults = 0;
									
									// compare available dimensions and set matching subformat as label
									for (var i=0,j=pk.GLOBAL.base.length; i<j; i++) {
										currentDimension = pk.GLOBAL.base[i];
										subformatValue = values[x][currentDimension];

										// need an exact match, watch spaces and so on.
										if (typeof subformatValue != 'undefined' && subformatValue != $('#'+currentDimension).val()) {
											break;
										} else {
											processedResults++;
										}
									}

									// set label (for manually entered dimensions)
									if (processedResults == 4) {
										// all 4 base dimensions didn't fail, either pass or undefined
										TPL_FORMAT_PRESETS = TPL_FORMAT_PRESETS.replace('{{selected}}',x);
										shownLabel = values[x].shiptype;
										break;
									}
								}
							}
							// search didn't succeed, display parent section
							if (shownLabel=='') {
								// set parent label
								TPL_FORMAT_PRESETS = TPL_FORMAT_PRESETS.replace('{{selected}}',subformatSection);
							}
						}
					}
				// subformat isnt set but shiptypes match
				} else if (shiptype == tShiptype) {
					TPL_FORMAT_PRESETS = TPL_FORMAT_PRESETS.replace('{{selected}}', v)
					shownLabel = values[v].shiptype;
				}

				//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 != shiptype && shiptype != 'freiesformat') &&
					(tShiptype != shiptype && shiptype != '') ||
					(tShiptype == '' && shiptype == 'freiesformat') ||
					hideSection) {
					continue
				}

				// add item to items with either section or item template
				items.push(valueType.replace('{{value}}', v))
				i++
			}
			if (shownLabel=='') {
				TPL_FORMAT_PRESETS = TPL_FORMAT_PRESETS.replace('{{selected}}', currentLabel)
				// shiptype
				shownLabel = pk.GLOBAL.inputShiptype.val()
			}

			var newFormats = '',
				noSubFormat = false;
			
			/* remove dropdown for elements without subformat */
			if (items.length > 1) { 
				itemList = '<ul class="inline">'+items.join('')+'</ul>'
				newFormats = TPL_FORMAT_PRESETS.replace('{{items}}', itemList)
			} else {
				newFormats = TPL_FORMAT_PRESETS.replace('{{items}}', '')
				noSubFormat = true
			}
			
			// fill preset list
			$('.box').append(newFormats)
			if (noSubFormat) {
				$('.box .format_presets b').addClass('no-subformat')
			}

			// add interaction to filled preset list 
			var formats = $('.format_presets'),
				selected = formats.find('b'),
				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 (pk.IE6) {
					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())
						pk.GLOBAL.inputShiptype.val(tShiptype) 
						title = pk.browser.VALUES[tShiptype].name
						pk.GLOBAL.dimensions.val(title)

						for (var 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 (var i=0,j=pk.GLOBAL.base.length;i<j;i++) {
										if (typeof values[f][pk.GLOBAL.base[i]] == 'undefined') {
											var parentval = values[formatParent][pk.GLOBAL.base[i]];
											$('input[name="'+pk.GLOBAL.base[i]+'"]').val(parentval);
										}
									}
								}
								for (var attribute in values[f]) {
									if ($('input[name="'+attribute+'"]').length > 0) {
										$('input[name="'+attribute+'"]').val(values[f][attribute])
									} else {
										pk.GLOBAL.mainForm.prepend('<input type="hidden" name="' + attribute + '" value="' + values[f][attribute] + '" />')
									}
								}
								break
							}
						}
						if (pk.validator.send()) {
							pk.GLOBAL.mainForm.submit()
						}
					}
				})
			})
			return shownLabel;
		}
	},
	
	
	// format browser
	browser: {
		VALUES: {
			// id : name
			'karte': "Postkarte",
			'umschlag': "Briefumschlag",
			'versandtasche': "Versandtasche",
			'quaderformat': "Paket/Päckchen",
			'rollenformat': "Rolle",
			'freiesformat': "Freies Format",
			'flyer': "Flyer",
			'katalog': "Katalog",
			'presseartikel': "Presseartikel"
		},
		init: function(values, selected, section){
			var browservalues = values || pk.browser.VALUES,
				selected = selected || '';
				section = section || '';
			$('.formatbrowser').each(function(){
			// setup
				var activeShiptype = '',
					f = $(this),
					ITEM,
					items = [],
				// big browser: all elements have the same size, medium image size 
					bigbrowser = '<div class="browser clearfix">{{items}}</div>',
					BIGITEM = '<a href="{{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
					tinybrowser = '<div class="format {{currentid}}"><div class="minibrowser clearfix">{{items}}</div></div>', // whenever a format is chosen
					TINYITEM = '<a href="{{href}}" class="{{class}}" title="{{name}} auswählen">{{name}}</a>';

			// generating graphical browser content
				if (selected == '') {
					//choose browser with equally sized icons 
					template = bigbrowser
					ITEM = BIGITEM
				} else {
					//choose browser with a big background image & mini icons
					template = tinybrowser
					ITEM = TINYITEM
				}

				// grab the existing items (html) and compare to browservalues
				// generate icons from links
				f.find('a').each(function() {
					var t = $(this),
						currentShiptype = t.attr('class'),
						property = browservalues[currentShiptype];
					
					if (selected == currentShiptype) {
						activeShiptype = currentShiptype
					} else {
						// grab each property and replace template strings
						currentItem = ITEM
						currentItem = currentItem.replace(/{{class}}/g,currentShiptype).replace(/{{name}}/g,property)

						// set each items name
						items.push(currentItem.replace('{{name}}',property))
						var lastItem = items.pop()
						items.push(lastItem.replace('{{href}}',t.attr('href')))
					}
				})

				// 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(){
					var t = $(this)
						currentHref = t.attr('href'),
						params = currentHref.substr(currentHref.indexOf('?')+1).split('&'),
						pairs = new Array();
					
					pk.GLOBAL.inputShiptype.val(t.attr('class'))
					$('#subformat').remove() // reset subformat

					// check for pkcformula and forward its value, otherwise delete it
					for (i=0,j=params.length;i<j;i++) {
						var pair = params[i].split('=')
						pairs[pair[0]] = pair[1];
					}
					
					var pkcf = $('#pkcformula')
					if(pairs['pkcformula']) {
						pkcf.val(pairs['pkcformula'])
					} else {
						pkcf.remove()
					}
					
					title = browservalues[$(this).attr('class')]
					pk.GLOBAL.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 (var val in formatobj) {
								if (val == 'length' || val == 'width' || val == 'height' || val == 'weight') {
									$('form').prepend('<input type="hidden" name="' + val + '" value="' + formatobj[val] + '" />')
								}
							}						
						}
					}
					pk.GLOBAL.mainForm.submit()
					return false /* IMPORTANT!! Otherwise, submitted form values will be overwritten immediately */
				})
			})
		}
	},
		
	// parameter selection dropdowns
	parameter: {
		VALUES: {
			length: ['23,5 cm', '35,3 cm', '60 cm', '90 cm', '120 cm'], 
			width: ['12,5 cm', '15 cm', '25 cm', '30 cm', '35 cm', '60 cm'], 
			height: ['0,5 cm', '1 cm', '2 cm', '5 cm', '15 cm', '20 cm', '60 cm' ], 
			weight: ['20 g', '50 g', '500 g', '1 kg', '2 kg', '5 kg', '10 kg', '20 kg', '31,5 kg']
		},
		init: function(values, dimensions, subformat, unavailable) {
			// setup
			values = values || pk.parameter.VALUES
			dimensions = dimensions || ''
			subformat = subformat || ''
			unavailable = unavailable || ''

			var TPL_LIST = '<div class="options"><ul class="inline">{{items}}</ul></div>',
				TPL_ITEM = '<li>{{value}}</li>',
				TPL_ITEM_UNAVAILABLE = '<li class="unavailable" title="Dieser Wert ist nicht mit dem ausgewählten Produkt kombinierbar">{{value}}</li>';


			pk.GLOBAL.btnCalc.before('<p id="msg-parameterselection" class="msg"></p>')
			var msg = $('#msg-parameterselection')

			$('.parameterselection').each(function() {
				// setup
				var s = $(this),
					v = s.find('input'),
					title = v.attr('title'),
					values = pk.parameter.VALUES[v.attr('id')];
				v.removeAttr('title');
				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')) {
					pk.GLOBAL.mainForm.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++) {
						// case1: 31,5 kg matches when indexOf is used - 5kg
						// case2: no match when string comparison is used and there are multiple values to disable
						var comparestring = unavailable[v.attr('id')].join(),
							un = comparestring.indexOf(values[i]);  // search item in string
						if (un > -1 && isNaN(comparestring.substr(un-2,1))){
							items.push(TPL_ITEM_UNAVAILABLE.replace('{{value}}', values[i]))
						} else {
							items.push(TPL_ITEM.replace('{{value}}', values[i]))
						}
					}
				} else {
					for (var i=0; i<values.length; i++) {
						items.push(TPL_ITEM.replace('{{value}}', values[i]))
					}
				}
				s.append(TPL_LIST.replace('{{items}}', items.join('')))
				
				
				// add interaction
				var optionlist = s.find('.options>ul') 
				s.find('.options')
				.click(function() {
					optionlist.slideDown(100)
					v.focus()
					window.getSelection().removeAllRanges()
				})
				.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
					pk.GLOBAL.dimensions.remove()
				})
				
				
				// ie6 'hover list elements' fix
				if (pk.IE6) {
					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 && subformat != '') {
					// check for pkcformula and forward its value, otherwise delete it
					var objURL = new Object();
					if (window.location.search.length>1) {
						
						// Use the String::replace method to iterate over each name-value pair in the query string.
						window.location.search.replace(
							new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
							 
							// For each matched query string pair, add that
							// pair to the URL struct using the pre-equals
							// value as the key.
							function( $0, $1, $2, $3 ){
								objURL[ $1 ] = $3;
							}
						);
					}
					if (window.location.search.length<=1 || typeof objURL['width']=='undefined' && typeof objURL['height']=='undefined' && typeof objURL['length']=='undefined' && typeof objURL['weight']=='undefined') {
						updatevalues = (subformat != '') ? pk.formats.VALUES[subformat] : updatevalues = pk.formats.VALUES[dimensions];
						// console.log(d)
       					for (var u in updatevalues) {
       						switch (u) {
       						case 'length':	$('#'+pk.GLOBAL.base[0]).val(updatevalues[u]).pulse(pulseoptions);break;
       						case 'width':	$('#'+pk.GLOBAL.base[1]).val(updatevalues[u]).pulse(pulseoptions);break;
       						case 'height':
       							if (updatevalues[u] != 'f1' && updatevalues[u] != 'f5') {
       								$('#'+pk.GLOBAL.base[2]).parent().show();
       								$('#'+pk.GLOBAL.base[2]).val(updatevalues[u]).pulse(pulseoptions);
       							} else if (updatevalues[u] == 'f1' || updatevalues[u] == 'f5') {
       								$('#'+pk.GLOBAL.base[2]).parent().hide();
       							}
       							break;
       						case 'weight':	$('#'+pk.GLOBAL.base[3]).val(updatevalues[u]).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),
            	def = ip.attr('value');
            ip.focus(function(){
                if (ip.attr('value') == def) {
                    ip.attr('value', '')
                }
            })
        })
    }
})
$(setTimeout(v1.init, 500))