jQuery.fn.extend({
    param: function( a ) {
        var s = [];
 
        // If an array was passed in, assume that it is an array
        // of form elements
        if ( a.constructor == Array || a.jquery ){
            // Serialize the form elements
            jQuery.each( a, function(){
                s.push(unescape(encodeURIComponent(escape(this.name))) + "=" + unescape(encodeURIComponent(escape(this.value))));
            });
        }
        // Otherwise, assume that it's an object of key/value pairs
        else{
            // Serialize the key/values
            for ( var j in a )
                // If the value is an array then the key names need to be repeated
                if ( a[j] && a[j].constructor == Array )
                    jQuery.each( a[j], function(){
                        s.push(unescape(encodeURIComponent(escape(j)) + "=" + encodeURIComponent(escape(this))));
                    });
                else
                    s.push(unescape(encodeURIComponent(escape(j)) + "=" + encodeURIComponent(escape(a[j]))));
        }
        // Return the resulting serialization
        return s.join("&").replace(/ /g, "+");
    },

    serialize: function() {
        return this.param(this.serializeArray());
    }
}); 

function setCmp_Checkbox()
{
	$( "div[id*='field_'] input").click( function()
			{
				divId = $( this).parent().attr( 'id');
				changeField( divId, $( this));
				$( this).blur();
			});
}

function setCompareFnc()
{
	//console.debug('setCompareFnc');
	//$('input:checked').attr('disabled', true);
	$( "div[id*='field_'] input:checked").attr('disabled', true);
}

function resetCompareFnc( sCaid)
{
	$( '#_tocompare_form input[name=caid['+ sCaid +']]').remove();
	$('input[name=caid['+ sCaid +']]').attr('disabled', false).attr('checked', false);
	oDivElm = document.getElementById( 'field_'+sCaid);
	$( oDivElm).removeClass('active');
}

function changeField( sId, oInp)
{
	oDiv = document.getElementById( sId);
	sInpName = $( oInp).attr( 'name');
	if( $( oInp).attr('checked'))
	{
		$( oDiv).addClass( 'active');
		//oInpCopy = oInp.clone();
		//oInpCopy.attr( 'type', 'hidden');
		//oInpCopy.attr( 'checked', 'checked');
		sInpName = oInp.attr( 'name');
		sInpVal = oInp.attr( 'value');
		sNewInput = '<input type="hidden" name="' + sInpName + '" value="' + sInpVal + '">';
		$( '#_tocompare_form').append( sNewInput);
	}
	else
	{
		$( oDiv).removeClass( 'active');
		$( '#_tocompare_form input[name=' + sInpName + ']').remove();
	}		
}

$(document). ready( function(){
	//loadVariantsInListview();
	var dDoczoneStart = $( window).scrollTop();
	var dDoczoneEnd = dDoczoneStart + $( window).height();
	loadProductPics( dDoczoneStart, dDoczoneEnd);
	$( '.gallery_box').hover( function ()
			{
				$('.to_detail', this).css( 'display', 'block');
			},
			function ()
			{
				$('.to_detail', this).css( 'display', 'none');
			});
	$( '.tree .open_cat').click( function ()
			{
				if ( $( '.tree .subcat').css( 'display') == 'none')
				{
					$( '.tree .subcat').css( 'display', 'block');
					$(this).addClass( 'close');
				}
				else
				{
					$( '.tree .subcat').css( 'display', 'none');
					$(this).removeClass( 'close');
				}
				return false;
			}
			);
	$( '.attributes .checkbox').click( function ()
			{
				actUl = $(this).parent().parent();
				name = $(this).attr('name');
				if ( $(this).hasClass( 'checked'))
				{
					$(this).removeClass( 'checked');
					//console.debug( $( 'input[name='+name+']', actUl));
					$( 'input[name='+name+']', actUl).val( '');
					var str = $( '#_filterlist').serialize();
					//console.debug(str);
					//console.debug(sShopUrl);
					//ajax_load( 'on');
					//$( '#body').load( sShopUrl, str, function (responseText) { setAjax(); ajax_load( 'off'); });
					$( '#_filterlist').submit();
				}
				else
				{
					//$( 'span', actUl).removeClass( 'checked');
					$(this).addClass( 'checked');
					$( 'input[name='+name+']', actUl).val( $(this).attr('value'));
					var str = $( '#_filterlist').serialize();
					//console.debug($( 'input[type=hidden]', actUl));
					//console.debug(str);
					//console.debug(sShopUrl);
					//ajax_load( 'on');
					//$( '#body').load( sShopUrl, str, function (responseText) { setAjax(); ajax_load( 'off'); });
					$( '#_filterlist').submit();
				}
			});
	$( '.attributes .attr_count').click( function ()
			{
				actLi = $(this).parent().parent();
				valuesUl = $( '.values', actLi);
				if ( $( valuesUl).css( 'display') == 'none')
				{
					$( valuesUl).css( 'display', 'block');
					$(this).addClass( 'close');
				}
				else
				{
					$( valuesUl).css( 'display', 'none');
					$(this).removeClass( 'close');
				}
				return false;
			});
	$( '.attributes .attr_count').filter(function()
			{
				actLi = $(this).parent().parent();
				if ($ ( '.checkbox', actLi).hasClass( 'checked'))
				{ 
					$('.values', actLi).css('display', 'block');
					
					//$( 'input', actLi).val( $( '.checked', actLi).attr('value'));
					return true;
				}
				return false;
			}).addClass('close');
	setCmp_Checkbox();
	$( '#delfilter').click( function()
			{
				$( 'ul.values input').val('');
				$( '#_filterlist').submit();
				return false;
				
			});
	//setAjax();
	setAvailability();
});

function setAjax()
{
	setAnsicht();
	setAvailability();
}

function setAnsicht()
{
	$( '#ansicht a').click( function()
			{
				var str = $( this).attr( 'href');
				var aStr = str.split('?');
				//console.debug( aStr);
				ajax_load( 'on');
				$( '#body').load( sShopUrl, aStr[1], function (responseText) { setAjax(); ajax_load( 'off'); });
				return false;
			});
}

function setAvailability()
{
	$( '#slct_availability').change( function ()
			{
				//var str = $( '#_availability').serialize();
				//ajax_load( 'on');
				//console.debug( str);
				//$( '#body').load( sShopUrl, str, function (responseText) { setAjax(); ajax_load( 'off'); });
				$( '#_availability').submit();
			});
}

function setSelectEvent( sUrl, sPBoxId, sCntr, sActId, bSlider)
{
	$( 'select', sPBoxId).change( function () 
			{
				if( $('option:selected', this).val() != '' && $('option:selected', this).val() != sActId)
				{
					var aid = $('option:selected', this).val();
					//ajax_load('on');
					productBoxLoad( true, sPBoxId);
					$( sPBoxId).load( sUrl + "index.php?cl=dd_productlist_cnt&anid=" + aid + "&cntr=" + sCntr, function (responseText) { 
																														 setSelectEvent( sUrl, sPBoxId, sCntr, sActId); 
																														 productBoxLoad( false, sPBoxId); 
																														 if ( bSlider)
																														 {
																															 //alert( '*');
																															 setSlider( 4, '#slider_list_' + sCntr, 4);
																														 }
																														 } );
				}
			});
}

function productBoxLoad( schalter, sPBox)
{
	if( schalter)
	{
		$( '.load', sPBox).addClass( 'on');
	}
	else
	{
		$( '.load', sPBox).removeClass( 'on');
	}
}

function setSlideAfterAjax( sSliderId, sUrl, sPBoxId)
{
	//console.debug( sSliderId + '  ' + sUrl + '  ' + sPBoxId);
	//setSlider(7, sSliderId, 1);
	//setSlideEvent(sSliderId, sUrl, sPBoxId);
	ajax_load( 'off');
}

// loading variants per AJAX on Listview
$aImg = new Array();
function loadVariantsInListview( oWrappingContainer)
{
	//// alle variants-Div holen
	//$( '.list_variants[rel]').each( function()
	$( '.list_variants', oWrappingContainer).each( function()
	{
		//load variants per AJAX
		var $sUrl = $( this).attr( 'rel');
		if( $sUrl != '')
		{
			$( this).load( $sUrl, function()
			{
				// Loading-bg entfernen
				$( this).removeClass( 'loading');
				
				//Set onmouse-Event for loading variant-Pic
				$( '.list_variants_icon', this).each( function()
					{
						$( this).mouseover( function()
						{
							oLi = $( this).parent();
							$( oLi).addClass( 'active');
							$sOxid = $( this).parent().parent().attr( 'id');
							$sOxid = $sOxid.substr( 7);
							$aImg[ $sOxid] = $( '#img_'+$sOxid).attr( 'src');
							$oPicCont = $( '#img_'+$sOxid).parent().parent();
							$sVarPicUrl = $( this).attr( 'rel');
							if( $sVarPicUrl != '')
							{
								var img = new Image();
								$( img).load( function()
								{
									if( $sVarPicUrl == $( this).attr( 'src'))
									{
										$( '#img_'+$sOxid).attr( 'src', $( img).attr( 'src'));
										$oPicCont = $( '#img_'+$sOxid).parent().parent();
									}
								}).attr( 'src', $sVarPicUrl);
							}
						});
						$( this).mouseout( function()
						{
							oLi = $( this).parent();
							$( oLi).removeClass( 'active');
						});
					}
				);
			});
		}
	});
}
// Binding Scroll-Event for Window to load the Product-Pics on scroll
$( window).load( function()
{
	var dDoczoneStart = $( window).scrollTop();
	var dDoczoneEnd = dDoczoneStart + $( window).height();
	
	$( window).scroll( function()
	{
		dDoczoneStart = $( window).scrollTop();
		dDoczoneEnd = dDoczoneStart + $( window).height();
		loadProductPics( dDoczoneStart, dDoczoneEnd);
	});
});
// show Load-Graphic for Variant-Icons
function showLoadForVars( sLoadContId)
{
	$( '#'+sLoadContId).addClass( 'list_variants');
}
// show Load-Graphic for Product-Thumb
function showLoadForPic( sLoadPicUrl, sPicUrl, sImgId)
{
	$( '#'+sImgId).attr( 'src', sLoadPicUrl);
}
// Show loading-pic for Product-Pic and Var-pics
aProduct_pics = new Object();
function setLoadOnScroll( oProductPicParam, oVarPicParam)
{
	showLoadForPic( oProductPicParam.sLoadPicUrl, oProductPicParam.sPicUrl, oProductPicParam.sImgId);
	aProduct_pics[ oProductPicParam.sImgId] = oProductPicParam.sPicUrl;
	if( oVarPicParam)
	{
		showLoadForVars( oVarPicParam.sLoadContId);
	}
}
// Load Pics on Scroll
function loadProductPics( dDoczStart, dDoczEnd)
{
	$( '.itemtoload').filter( function( index)
	{
		var dItemTop = $( this).offset().top;
		var dItemBottom = $( this).offset().top + $( this).innerHeight();
		if( ( dItemTop >= dDoczStart && dItemTop <= dDoczEnd) || ( dItemBottom >= dDoczStart && dItemBottom <= dDoczEnd))
		{
			var sWrapContainerId = $( this).attr( 'id');
//			var jetzt = new Date();
//			var sOut = ' (' + dDoczStart + '-' + dDoczEnd + ')';
//			console.info( jetzt.getMinutes()+'.'+jetzt.getMilliseconds() + ": " + sWrapContainerId + sOut);
			window.setTimeout( function(){startPicLoading(sWrapContainerId);}, 250);
			
			
		}
	});
}

function startPicLoading( sWrapContainerId)
{
	var oWrapContainer = $( '#' + sWrapContainerId);
	var dDoczStart = $( window).scrollTop();
	var dDoczEnd = dDoczStart + $( window).height();
	var dItemTop = $( oWrapContainer).offset().top + 5;
	var dItemBottom = $( oWrapContainer).offset().top + $( oWrapContainer).innerHeight();
	if ($( oWrapContainer).hasClass( 'itemtoload') && ( ( dItemTop >= dDoczStart && dItemTop <= dDoczEnd) || ( dItemBottom >= dDoczStart && dItemBottom <= dDoczEnd))) 
	{
//		var jetzt = new Date();
//		var sOut = ' (' + dDoczStart + '-' + dDoczEnd + ') -> ' + dItemTop;
//		console.info(jetzt.getMinutes()+'.'+jetzt.getMilliseconds() + ": " + sWrapContainerId + " <==" + sOut);
		var sImgId = $( '.product_pic', oWrapContainer).attr( 'id');
		var sPicUrl = aProduct_pics[ sImgId];
		$( '.product_pic', oWrapContainer).attr( 'src', sPicUrl);
		$( oWrapContainer).removeClass( 'itemtoload');
		loadVariantsInListview( oWrapContainer);
	}
}



