// Allgemeine Hilfsfunktionen

function quote(text) {
	return (isNaN(text))? text.replace('"', '\"') : text;
}

function setCookie(key, value, domain, expires, path, secure){
	var cookie = key + "=" + unescape(value);
	cookie += (domain) ? "; domain=" + domain : '';
	cookie += (expires) ? "; expires=" + expires : "; expires="+(new Date((new Date()).getTime() +1000*60*60*24*365)).toUTCString();
	cookie += (path) ? "; path=" + path : "; path=/";
	cookie += (secure) ? "; secure" : "";
	document.cookie = cookie;
}

function getCookie(key) {
	var i = 0;
	var search = key + "=";
	var length = document.cookie.length;
   
	while (i < length) {
		if (document.cookie.substring(i, i + search.length) == search) {
			var end_pos = document.cookie.indexOf(";", i + search.length);
			end_pos = (end_pos > -1) ? end_pos : document.cookie.length;
			var cookie = document.cookie.substring(i + search.length, end_pos);
			return unescape(cookie);
		}
		i++;
	}
   
	return "";
}

function setNavigationLeftVisibility() {
	if (getCookie('navigation_left') == 'false') {
		$('#navigation_left').hide();
		$('#navigation_left_toggle_button').text('+');
	}
}

function bindDataToggle() {
	//Gruppen ausblendung (Beta!)
	$('[data-toggle-group]').each(function() {
		var options = $(this).attr('data-toggle-group');
		options = eval('({'+options+'})');


		var selector = (options.limit == undefined || options.limit == 0) ? '' : ':gt('+(options.limit - 1)+')';
		var toggle_items = $(this).find('[data-toggle-item='+options.name+']'+selector);
		var toggle_trigger = $('[data-toggle-trigger='+options.name+']');
		toggle_items.hide();

		// Trigger ausblenden, wenn es nix zum ausblenden gibt
		if (toggle_items.size() == 0) {
			toggle_trigger.hide();
		} else {
			toggle_trigger.click(function() {
				toggle_items.toggle();
			});
		}
	});
}

function drawPrice(price, currency) {
	var result = '';
	var price_arr = price.toString().split('.');
	var dummy_image = '/templates/asmc/image/pixel.png';
	var chr = '';

	// Bei Fehler Standardpreis nehmen
	if (price_arr.length != 2) {
		return price;
	}
	// Vorkommastellen
	for (i = 0, n = price_arr[0].length; i < n; i++) {
		chr = price_arr[0].charAt(i).replace(',', 'Dot');
		result += '<img class="priceImg price'+chr+'" src="'+dummy_image+'">';
	}

	// Komma
	result += '<img class="priceImg priceComma" src="'+dummy_image+'">';

	// Nachkommastellen
	for (i = 0, n = price_arr[1].length; i < n; i++) {
		result += '<img class="priceSmallImg price'+price_arr[1].charAt(i)+'Small" src="'+dummy_image+'">';
	}

	// Währung
	result += '&nbsp;<img class="priceImg price'+currency+'" src="'+dummy_image+'">';
	result += '&nbsp;<img class="priceImg priceInputRequirement " src="'+dummy_image+'">';

	return result;
}

var Request = function() {}

Request.prototype.post = function(url, values) {
	var form = '<form id="hidden_js_post_form" action="'+url+'" method="post">';
	$.each(values, function(name, value) {
		form += '<input type="hidden" name="'+quote(name)+'" value="'+quote(value)+'">';
	})
	form += '</form>';
	$('body').append(form);
	$('#hidden_js_post_form').submit();
}

$(document).ready(function(){
	
	// Extension Hotfix
	var el_height = 0;
	$('.bestseller_info_box').css('height', '0');		
	$('div.extension div').each(function() {
		el_height = el_height + $(this).height();
	});
	$('.bestseller_info_box').css('height', 'auto');
	$('div.main').css('min-height', el_height-100);
	
	$('[data-placeholder]').each(function() {
		// Platzhalter beim Laden der Seite eintragen, ausser das Element hat focus
		try {
			if ($(this).val() == "" && $('*:focus').get(0) != this) {
				$(this).val($(this).attr('data-placeholder')).addClass('placeholder');
			}
		} catch(e){ // IE 7
			if ($(this).val() == "") {
				$(this).val($(this).attr('data-placeholder')).addClass('placeholder');
			}
		}
		
		// Gesetzte Platzhalter beim Klick in Input-Feld entfernen
		$(this).focus(function() {
			if ($(this).val() == $(this).attr('data-placeholder')) {
				$(this).val('').removeClass('placeholder');
			}
		});

		// Wenn Platzhalter gesetzt, beim Verlassen des Input-Feldes wieder eintragen
		$(this).blur(function() {
			if ($(this).val() == "") {
				$(this).val($(this).attr('data-placeholder')).addClass('placeholder');
			}
		});
	});

	// Placeholder bei Form Submit entfernen
	$('[data-placeholder]').parents('form').submit(function() {
		$(this).find('.placeholder').each(function() {
			if ($(this).val() == $(this).attr('data-placeholder')) {
				$(this).val('');
			}
		});
	});

	// Content mit Lightbox öffnen
	$("a[data-open=lightbox]").fancybox({
		'showNavArrows'	: true,
		'titleShow'	: true,
		'titlePosition'	:'outside',
		'overlayOpacity':'0.7',
		'overlayColor'	:'#000000',
		'transitionIn'	:'none',
		'transitionOut'	:'none'
	});
	
	// Content mit Popup öffnen
	$("a[data-open=popup]").click(function() {
		var default_width = 880;
		var default_height = 830;
		var width  = $(this).attr('data-width') > 0 ? $(this).attr('data-width') : default_width;
		var height = $(this).attr('data-height') > 0 ? $(this).attr('data-height') : default_height;

		window.open($(this).attr('href'), $(this).attr('title'), 'width=' + width  + ',height=' + height + ',scrollbars=yes');
		return false;
	});

	// data-link Elemente in Links umwandeln
	$('*[data-link]').each(function() {
		$(this).css('cursor', 'pointer');
		$(this).click(function(event) {
			// Klick auf child elemente ignorieren
			if (this == event.target || $(this).attr('data-link-include-children')) {
				if ($(this).attr('data-link-open-blank') == 'true') {
					window.open($(this).attr('data-link'));
				} else {
					window.location = $(this).attr('data-link');
				}
				return false;
			}
		})
	});

	// Content ändern (Beta!)
	// ATODO: universeller machen
	$('[data-toggle-content]').click(function() {
		// Ist das Element ein Bild, dann src tauschen statt Text
		if (this.tagName == 'IMG') {
			var old_src = $(this).attr('src');
			$(this).attr('src', $(this).attr('data-toggle-content'));
			$(this).attr('data-toggle-content', old_src);
		} else {
			var old_content = $(this).html();
			$(this).html($(this).attr('data-toggle-content'));
			$(this).attr('data-toggle-content', old_content);
		}
	});

	$('[data-confirm]').each(function() {
		$(this).data('confirmed', false);
		
		if (this.tagName == 'SELECT') {
			$(this).click(function() {				
				if ($(this).data('initial-state') == undefined) {
					$(this).data('initial-state', $(this).attr('selectedIndex'));
				}
			});
			$(this).change(function() {
				var confirm_text = $(this).attr('data-confirm');
				// Platzhalter ersetzen
				confirm_text = confirm_text.replace('{selected_text}', $(this).find('option:selected').text());
				confirm_text = confirm_text.replace('{selected_value}', $(this).val());
				var confirmed = confirm(confirm_text);
				
				$(this).data('confirmed', confirmed);
				if (confirmed) {
					$(this).data('initial-state', $(this).attr('selectedIndex'));
				} else {
					// Wenn confirm = false: Auswahl wieder zurücksetzen
					$(this).find('option')[$(this).data('initial-state')].selected = true;
				}
			});
		} else {
			$(this).click(function() {
				var confirmed = confirm($(this).attr('data-confirm'));
				$(this).data('confirmed', confirmed);
				return confirmed;
			});			
		}
	})

	// Ein/Ausblenden der Oberkategorien der linken Navigation
	$('[data-root-categories-box]').click(function() {
		var subcategories_box = $('.filterAttributes').find('[data-subcategories-box='+$(this).attr('data-root-categories-box')+']');

		if (subcategories_box.is(':visible')) {
			subcategories_box.slideUp(100);
			$(this).removeClass('iconMinus').addClass('iconPlus');
		} else {
			subcategories_box.slideDown(200);
			$(this).removeClass('iconPlus').addClass('iconMinus');
		}
	});

	$('#navigation_left_heading').click(function() {
		$('#navigation_left').toggle();
		var status = $('#navigation_left').is(':visible');
		var text = (status == true) ? '–' : '+';
		$('#navigation_left_toggle_button').text(text);
		setCookie('navigation_left', status);
	})

	$('#bestseller_box').find('li').each(function() {
		$(this).mouseenter(function() {
			var bestseller_box = $('#bestseller_box')
			var show_box = $(this).find('[data-index]');
			var bestseller_info_box = bestseller_box.find('[data-show-box='+show_box.attr('data-index')+']');
			var left = Math.round(bestseller_box.position().left - 200);
			var top = Math.round(bestseller_box.position().top);
			bestseller_info_box.show();
			bestseller_info_box.css('left', left+'px');
			bestseller_info_box.css('top', top+'px');
		});

		$(this).mouseleave(function() {
			$('#bestseller_box').find('[data-show-box]').hide();
		});
	});
	
	// Quickview Icon Hover
	$('[data-quickview]').mouseenter(function() {
		$('img[data-qvid='+$(this).attr('id')+']').show();
	});
	
	$('[data-quickview]').mouseleave(function() {
		$('img[data-qvid='+$(this).attr('id')+']').hide();
	});

	$('[data-lightbox-login]').fancybox({
		'href': '/login_lightbox.php',
		'title': 'Login',
		'overlayOpacity':'0.7',
		'overlayColor'	:'#000000',
		'titlePosition' :'outside',
		'transitionIn'	:'none',
		'transitionOut'	:'none'
	});

	var scroll = getCookie('scrollTo');
	if (scroll > 0) {
		$(document).scrollTop(scroll);
		setCookie('scrollTo', 0);
	}
	
	if (jQuery().tooltip) {
		$('[data-tooltip-title]').tooltip();		
	}
});
