/***jQuery initialization***/
google.setOnLoadCallback(function() {
	(function($){	
    //manipulate filter links on product detail page
    $.fn.nfcGreateVariationUrl = function(data) {
        var defaultUrls = [];
        $(data.target).each(function(i) {
            defaultUrls[i] = $(this).attr('href');
        });

        return $(this).each(function() {
            if($(this).find('option:selected') && $(this).val() > 0) {
                var variationValueId = $.trim($(this).find('option:selected').text());
                $(data.target).each(function(index) {
										var seperator = '&';
										if(defaultUrls[index].indexOf('?') == -1) seperator = '?';
                    var newUrl = defaultUrls[index]+seperator+data.param+'='+variationValueId;
                    $(this).attr('href', newUrl);
                });
            }

            $(this).change(function() {
                if($(this).val() > 0) {
                    var variationValueId = $.trim($(this).find('option:selected').text());
                    $(data.target).each(function(index) {
												var seperator = '&';
												if(defaultUrls[index].indexOf('?') == -1) seperator = '?';
                        var newUrl = defaultUrls[index]+seperator+data.param+'='+variationValueId;
                        $(this).attr('href', newUrl);
                    });
                } else {
                    $(data.target).each(function(index) {
                        $(this).attr('href', defaultUrls[index]);
                    });
                }
            });
        });
    }		
		
		
		
		var loc = document.location;
		var ajaxUrl = loc.protocol+'//'+loc.host+'/index.php?type=6667';	

		updateProductContent = function(productId,variationId,contentConfig){
			productId = parseInt(productId);
			variationId = parseInt(variationId);
			if(typeof(contentConfig) =='string')
			{
				var contentConfig = $.parseJSON(contentConfig);
				if(contentConfig == null) return false;
			}	

			if(productId > 0 && contentConfig)
			{
				var requestData = {
					'tx_nfcshop_pi1[a]':'gcfpv',
					'tx_nfcshop_pi1[product_id]':productId,
					'tx_nfcshop_pi1[content_config]':{}
				};

				if(variationId > 0){
					requestData['tx_nfcshop_pi1[variation_id]'] = variationId;
				}
				$.each(contentConfig,function(scope,contentKeys){
					requestData['tx_nfcshop_pi1[content_config]['+scope+']'] = new Array();
					$.each(contentKeys,function(contentKey,callback){
						requestData['tx_nfcshop_pi1[content_config]['+ scope +']'].push(contentKey);			
					});
				});

				$.ajax({
					url:ajaxUrl,
					type: 'POST',
					dataType: 'json',
					data: requestData,
					success: function(data) {
						if(data.state == 1 && data.payload)
						{
							if(data.payload.variation){
								if(data.payload.variation.attributes && typeof(contentConfig.variation.attributes.callback) == 'function'){
									contentConfig.variation.attributes.callback(data.payload.variation.attributes);
								}
								if(data.payload.variation.scaleprices && typeof(contentConfig.variation.scaleprices.callback) == 'function'){
									contentConfig.variation.scaleprices.callback(data.payload.variation.scaleprices);
								}
								if(data.payload.variation.deliverytime && typeof(contentConfig.variation.deliverytime.callback) == 'function'){
									contentConfig.variation.deliverytime.callback(data.payload.variation.deliverytime);
								}
								if(data.payload.variation.images && typeof(contentConfig.variation.images.callback) == 'function'){
									contentConfig.variation.images.callback(data.payload.variation.images);
								}
							}
							if(data.payload.product){
								if(data.payload.product.attributes && typeof(contentConfig.product.attributes.callback) == 'function'){
									contentConfig.product.attributes.callback(data.payload.product.attributes);
								}
								if(data.payload.product.scaleprices && typeof(contentConfig.product.scaleprices.callback) == 'function'){
									contentConfig.product.scaleprices.callback(data.payload.product.scaleprices);
								}
								if(data.payload.product.deliverytime && typeof(contentConfig.product.deliverytime.callback) == 'function'){
									contentConfig.product.deliverytime.callback(data.payload.product.deliverytime);
								}					
								if(data.payload.product.images && typeof(contentConfig.product.images.callback) == 'function'){
									contentConfig.product.images.callback(data.payload.product.images);
								}			
							}
						}
						jQuery('.fix-column-heights').fixColumnHeights({elementsSelector:'.box-special-middle',additionalHeight:0,setOnlyMinHeight:true});
					}
				});
			}
		}

		replaceAttributes = function(wrapper,content){
			$(wrapper).replaceWith(content);
		}

		replaceDeliveryTime = function(wrapper,content){
			$(wrapper).replaceWith(content);
		}

		replaceScalePrices = function(wrapper,content){
			$(wrapper).replaceWith(content);
		}

		replaceImages = function(wrapper,content){
			$(wrapper).replaceWith(content);
			initJQZoom();
			/***product image slider ***/
			initProductImageSlider();
		}

		/* handle document ready */
		$(document).ready(function(){

			//product detail, reload variation data
			$('.product-data-wrapper:first').live('variationSelected',function(ev,data){
				if(data && data.payload && data.payload.variationPriceContent){
					$(this).find('.ajax-variation-prices-wrapper:first').replaceWith(data.payload.variationPriceContent);
				}
				var productWrapper = $(this);
				var variationId = parseInt($(this).find('input[name*=variation_id]').val());
				var productId = parseInt($(this).find('input[name*=product_id]').val());
				var contentConfig = {
					variation:{
						scaleprices:{
							callback: function(content){
								replaceScalePrices($(productWrapper).find('.scaleprices-wrapper'),content)
							}
						},
						deliverytime:{
							callback: function(content){
								replaceDeliveryTime($(productWrapper).find('.product-availability-wrapper'),content)
							}
						},
						attributes:{
							callback: function(content){
								replaceAttributes($(productWrapper).find('.attribute-variation-wrapper'),content)
							}
						},
						images:{
							callback: function(content){
								replaceImages($(productWrapper).find('.product-image-wrapper'),content)
							}
						}
					}
				};
				updateProductContent(productId,variationId,contentConfig);
				
				/*preselect first color option if variation selected*/
				var colorimages = $(this).find('.select_colors .variation-option-image');
				if(colorimages.length > 0 && $(colorimages).filter('.active').length == 0){
					$(colorimages).first().addClass('active');
				}
			});

				if($('.select_variation_option_size').size() > 0) {
            $('.select_variation_option_size').nfcGreateVariationUrl({
                'param':$('.select_variation_option_size').parents('.filter-row:first').children('label:first').text(),
                'target':'.variation-option-image a.colorbox'
            });
        }
			// checkout payment
			$('.payment .payment-trigger').bind('click',function(ev){
						var paymentKey = $(this).attr('id');
						var subFormSelected = $('.payment').find('fieldset.sub-form.'+paymentKey+':first');
						if($(subFormSelected).size()>0)
						{
								var further_btn = $(subFormSelected).find('.payment-btn-wrap input');
								var placeholder = $('.tx-nfccheckout-pi1').find('#placeholder');
								placeholder.css('display','inline-block');
								placeholder.unbind('click');
								
								//set banktransfer msg to display none 
								if( $(subFormSelected).find('#payment-message').size() > 0 )
								{
									$(subFormSelected).find('#payment-message').css('display','none');
								}
								
								placeholder.bind('click',function(){
									var form = subFormSelected.parents('form:first');
									//checks to the banktransfer checkbox
									if( $(subFormSelected).find('#accept_banktransfer').size() > 0)
									{
										if( $(subFormSelected).find('#accept_banktransfer:checked').size() > 0 )
										{
											form.trigger('submit');
										}
										else
										{
											$(subFormSelected).find('#payment-message').css('display','block');											
										}
									}
									//triggers all other paymentforms
									else
									{
										form.trigger('submit');
									}
								});
						}
			});
											
			$('.payment .payment-trigger.selected').trigger('click');		
			//make payment rows clickable, not only payment-trigger box
			$('.payment form .checkout-row').bind('click',function(ev){
				$(this).find('.payment-trigger:not(.selected)').trigger('click');
			});


			/* PRICE-SLIDER */
			if(jQuery.ui){
				if(jQuery.ui.slider){
					$('.filter-slider-wrapper').each(function(index,el){
						var obj = $(this);
						var sliderMin = parseInt(obj.find('span.sliderMin').text());
						var sliderMax = parseInt(obj.find('span.sliderMax').text());
						var minSelected = parseInt(obj.find('span.minSelected').text());
						var maxSelected =  parseInt(obj.find('span.maxSelected').text());

						var inputMinSelection = $(el).find('input[class="selection_min"]:first');
						var inputMaxSelection = $(el).find('input[class="selection_max"]:first');
						var sliderElement = $(el).find('.slider-range:first');								

						if(sliderElement.length == 1 && sliderMin >= 0 && sliderMax > 0 && sliderMax > sliderMin && sliderMin <= minSelected &&	sliderMax >= maxSelected &&	maxSelected >= minSelected){

							$(sliderElement).slider({							
								range: true,
								min: sliderMin,
								max: sliderMax,
								values: [ minSelected, maxSelected ],
								slide: function( event, ui ) {
									$(inputMinSelection).val( ui.values[ 0 ]);
									$(inputMaxSelection).val(  ui.values[ 1 ]);
								},
								change: function(event, ui) {
									$('#filters-slider-form').submit();								
								}
							});

							$(inputMinSelection).val($(sliderElement).slider("values",0));
							$(inputMaxSelection).val($(sliderElement).slider("values",1));		
						}
					});
				}
			}		
			if($('#search-packet-station').length == 1){
				var shippingCountrySelect = $('select[name="tx_nfccheckout_pi1[country_id]"]');
				if(shippingCountrySelect.length == 0){
					shippingCountrySelect = $('select[name="tx_nfccheckout_pi2[country_id]"]');
				}
				if(shippingCountrySelect.length == 1){
					var allowedValue = 54; /* only in DE */
					$(shippingCountrySelect).bind('change',function(){

						if($(this).val() != allowedValue){
							$('#search-packet-station').hide();
							$('#search-packet-station-result').hide();
							if($('#packet-station-requiredfields-error:visible').length == 1){
								$('#packet-station-requiredfields-error').hide();
							}
						} else {
							$('#search-packet-station').show();
							$('#search-packet-station-result').show();
						}
					});
				}
			}
		});
	})(jQuery);
});
