$(document).ready(function() {
	$('input:checkbox[name^="filter["]').click(function(){
		submitFilterForm( $(this) );	
	});
	$('select[name^="filter["],select[name^="order_by["]').change(function(){
		submitFilterForm( $(this) );	
	});
});

function submitFilterForm($elem)
{
	$elem.parents('form:first').submit();
}

function resetFilters() {
	$('select[name^="filter["],select[name^="order_by["]').val("0");
	$('input:checkbox[name^="filter["]').attr('checked',false).parents('form:first').submit();
}

function processVatID()
{
	$idContainer = $('#bdi_vatIDContainer');
	if( $('#order_person_company').val().length > 0 )
	{
		$idContainer.show();
	}
	else
	{
		$idContainer.hide();
	}
}

function setProductVariation(jdata, formIter, selIds, selItems)
{
	$.each(jdata, function(indexItem,item){
		
		var elements = { 
		  'price': 'price', 
		  'priceNonSpecial': 'priceNonSpecial',
		  'priceMsrp': 'msrp', 
		  'notice': 'price_notice',
		  'productNo': 'product_no', 
		  'issues': 'issues',
		  'shipping_costs': 'shipping_costs'
		};
		price_display = item['price_display'];
		
		$.each(elements, function(elementId, jdataIdent)
		{ 
			var namespace = (elementId.substr(0,5) == 'price' ? '_' + price_display + '_' : '_');
			
			$element = $('#' + elementId + namespace + formIter);
			if($element.text().length > 0)
	        {
				$element.text(item[ jdataIdent ]);
	        }
		});
		
		// replace image and teaser
		var image_elements = ['image', 'teaser'];
		//var image_elements = ['image'];
		
		$.each(image_elements, function()
		{
			$image_element = $('#' + this + '_' + formIter);
			if($image_element.size() && $image_element.attr('src').length > 0 && item[this].length > 0)
	        {
				$image_element.attr('src', item[this]);
	        }
		});
		
		$.each( ['default','special','msrp'], function(){
			$displayElement = $('#display_' + this + '_' + formIter);
			
			if(this == price_display)
	        {
				$displayElement.show();
	        }
			else
			{
				$displayElement.hide();
			}
		});
	    		
	    $shipping_costs_text = $('#shipping_costs_text_' + formIter);
	    if(parseFloat(item.shipping_costs.replace(',','.')) > 0)
	    {
	    	$shipping_costs_text.show();
	    }
	    else
	    {
	    	$shipping_costs_text.hide();
	    }
	    
	    i = 0;
	    $.each(item.variations, function(varKey, varArr){
	    	$select = $('#' + selIds[i]);
	    	$select.children('option').remove();
	    	$.each(varArr, function(key, option){
	    		$select.append('<option value="' + key + '">' + option + '</option>');
	    	});
	    	$select.children('option[value=' + selItems[i] + ']').attr("selected","selected") ;
	    	i++;
	    });
   });	
	
} 

function getProductVariation(formIter, imagewidth, imageheight)
{
	url = getAjaxUrl('/xml/json/product/', formIter);
	
	if(imagewidth != null && imageheight != null)
	{
		url += '&imagewidth=' + imagewidth + '&imageheight=' + imageheight;
	}

	$.getJSON(url, function(jdata ){
		setProductVariation(jdata, formIter, selIds, selItems);		
    });	
}

function getProductBundle(formIter, bundleContainer)
{
	url = getAjaxUrl('/xml/html/bundles/', formIter);
	
	$('#' + bundleContainer).hide;
	if ( $('#' + bundleContainer + '_loader').length > 0 ) {
		$('#' + bundleContainer).show;
	}
	
	$.ajax({
	  url: url,
	  success: function(data) {
		 $('#' + bundleContainer).replaceWith(data);
		 /*
		 $.each(selIds, function(varKey, varId){
			$select = $('#' + varId);
	    	$select.children('option[value=' + selItems[varKey] + ']').attr("selected","selected") ;
	    });
	    */
	  }
	});	
}

function getAjaxUrl(path, formIter)
{
	$form = $('#order_' + formIter + '_vv_1').parents('form:first');

	baseUrl = (typeof bdiShopBaseUrl != 'undefined' && bdiShopBaseUrl != '') ? bdiShopBaseUrl : '/home';
	qstr = baseUrl + path;
	productId = $form.find('input[name="product[product_id]"]').val();
	qstr += '?product_id=' + productId;

	$selects = $form.find('select[name="product[variations][' + productId + '][]"]');
	selIds = new Array($selects.length);
	selItems = new Array($selects.length);

	$selects.each(function (index) {		
		selIds[index] = $(this).attr('id');
		selItems[index] = $(this).children('option:selected').val();

		var_index = index + 1;
		qstr += '&variation_' + var_index + '=' + selItems[index];
    });

	return qstr;	
}

function getBookmarkLink(link, bookmarkTitle)
{	
	var url = window.location.href;
	var bookmarkUrl = url.substring(0, url.length - 1); // cut last character of url

	if (window.sidebar) { // For Mozilla Firefox Bookmark
		window.sidebar.addPanel(bookmarkTitle, bookmarkUrl,'');
	} else if( window.external || document.all) { // For IE Favorite
		window.external.AddFavorite( bookmarkUrl, bookmarkTitle);
	} else if(window.opera) { // For Opera Browsers
		link.attr('href',bookmarkUrl);
		link.attr('title',bookmarkTitle);
		link.attr('rel','sidebar');
		link.click();
	} 
	
	return false; // this will prevent the anchor tag from going the user off to the link
}


function changeNavigationItem(category_id)
{
	$('#bdi_navigationStartList a').removeClass('activeListElement').addClass('noactiveListElement');
	$('#bdi_navigationStartList a#listElem_' + category_id).removeClass('noactiveListElement').addClass('activeListElement');

	$('#bdi_navigationStartImage div').removeClass('activeImage').addClass('noactiveImage');
	$('#bdi_navigationStartImage div#image_' + category_id).removeClass('noactiveImage').addClass('activeImage');
}

function setProductQuantity(identifier, quantity)
{
	$('#' + identifier).val(quantity);
}

jQuery(function($){
	if(typeof $.datepicker != 'undefined')
	{
		$.datepicker.regional['de'] = {clearText: 'löschen', clearStatus: 'aktuelles Datum löschen',
	            closeText: 'schließen', closeStatus: 'ohne Änderungen schließen',
	            prevText: '&#x3c;zurück', prevStatus: 'letzten Monat zeigen',
	            nextText: 'Vor&#x3e;', nextStatus: 'nächsten Monat zeigen',
	            currentText: 'heute', currentStatus: '',
	            monthNames: ['Januar','Februar','März','April','Mai','Juni',
	            'Juli','August','September','Oktober','November','Dezember'],
	            monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
	            'Jul','Aug','Sep','Okt','Nov','Dez'],
	            monthStatus: 'anderen Monat anzeigen', yearStatus: 'anderes Jahr anzeigen',
	            weekHeader: 'Wo', weekStatus: 'Woche des Monats',
	            dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
	            dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
	            dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
	            dayStatus: 'Setze DD als ersten Wochentag', dateStatus: 'Wähle D, M d',
	            dateFormat: 'dd.mm.yy', firstDay: 1, 
	            initStatus: 'Wähle ein Datum', isRTL: false};
	   
	    $.datepicker.setDefaults($.datepicker.regional['de']);
	    $.datepicker.setDefaults({
			buttonImage: calendar_pic, buttonImageOnly: true, constrainInput: true, 
			duration: 'fast', firstDay: 1, maxDate: '+5Y', minDate: '-5Y', 
			showButtonPanel: true, showOn: 'button', inline: true
		});
	}
	
	if(typeof $.extend != 'undefined' && typeof $.ui != 'undefined')
	{
	    $.extend($.ui.dialog.prototype.options,{
	        autoOpen: false,
	        modal: true,
	        resizable: false
	    });
	}
});

function dateChoice(val)
{
	if(val!=0) {
		date = val.split(",")
		setDate(date[0],date[1]);
	}
}

function setDate(dateFrom, dateTo) {
	$('#dateFrom').val(dateFrom);
	$('#dateTo').val(dateTo);
}

function formCheck() {
	var inputValue = $('#jq_search_term').val();
	
	if(inputValue.length < 2) 
	{
		alert('Bitte geben Sie einen Suchbegriff mit mindestens zwei Zeichen ein'); 
		return false;
	} else {
		return true;
	}
}

