// ***********************************************************************************************
// *
// *  Main FilterModule
//*

var FMdebug = false;
if( document.location.href.indexOf("file:") != -1 )
	FMdebug = false;

try {
	if( document.location.href == top.document.location.href && document.location.host.indexOf("dev") != -1)
		FMdebug = false;
} catch (e){}
if( FMdebug ) {
	document.write( "<h1><a name='FilterConsole'></a>FilterConsole (DebugMode)</h1><hr>" );
//	document.write( '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td>');
	document.write( "<div id='FilterConsoleOutput' onclick='select();' style='width:400px;height:600px;overflow:auto;float:left;background-color:silver;'>FilterConsole Opened!<br><div id='nextOutput'></div></div>" );
	
//	document.write( '</td><td width="100%" valign="top">');
}

var getCounterIntervall = "";

function fmDebug( module, message, scream ){
	var sPrefix = "FM-Debug ";
	if( FMdebug === true ){
		if( scream === true ){
			prompt( sPrefix, message );
		} else {
			xGetElementById("nextOutput").innerHTML += sPrefix + "<font color='red'><b>" + module + ": </b></font>" + message + "<div id='nextOutput'></div>";
		}
	}
}


function debugVal( v ) {
	return "<b><i>" + v + "</i></b>";
}

// **********************************************************************
// function OptionSort
//
// for numeric sort

function OptionSort( a, b ){
	var ia = Number(a[0].match(/\d*/)[0]);
	var ib = Number(b[0].match(/\d*/)[0]);
	return ia - ib;
}

// **********************************************************************
// function toggleView
//

function toggleView( ele, show ){
	var e = xGetElementById(ele);
	if( e ){
		e.style.display = ( show === true ? "inline" : "none" ); 
	}
}

// **********************************************************************
// function redrawElement
//

function redrawElement( re, currentFilter, content ){
	if( re == "" ) return;

	re += (currentFilter === false ? "Off" : "On" );
	
	var reArray = RedrawElements[ re ];
	if( reArray && reArray.length == 3 ){
		fmchangehtml( reArray[0], ( content == "" ? reArray[1] : content), reArray[2] );
	}
}


// **********************************************************************
// function checkMask
//
// find out if the array v element is guilty in arraz m

function checkMask( v, m ){
//	fmDebug( "FM.checkMask", "reached with " + v + " and  " + m );
	var allowed = 0;
	for( var i=0; i< Math.min(v.length, m.length); i++ ){
		if( v[i] == 0 ) continue;
//		fmDebug( "FM.checkMask (" + m[i] + ") " + ( v[i] & m[i]).toString(2), Number(v[i]).toString(2) + " with \n" + Number(m[i]).toString(2));
		allowed = v[i] & m[i]; 
		break;
	}
	return allowed;
}

function FilterModule() {
	var initialized=false;
	var activity = false;
	var visibility = false;
	var resultRows = 0;
	var isFiltered = false;
	var startupFilter = new Array();
	var currentFilter = new Array();
	var maxMask = new Array();
	var resetMask = new Array();
	var FilterElements = new Array();
	var currentIndex = "";
	var currentlyViewed = 0;
	var lastFilterElement = "";
	var BCmaxMask = new Array();
	var blockActivity = new Array();

	// **********************************************************************
	// Method active

	
	this.active = function ( newActivity ){
		var oldActivity = activity;
		fmDebug( "FM.active()","called with " + debugVal( newActivity ));
		
		var f = xGetElementById("FMform");
		if( newActivity === true ) {
			activity = newActivity;
			if( f.disabled ){
				f.disabled = false;
			} else {
				for( var fi=0; fi<f.length; fi++ ){
					f[fi].disabled = ( blockActivity.length == f.length ? blockActivity[fi] : false );
				}
			}
			fmDebug( "FM.active()", "changed from " + debugVal( oldActivity ) + " to " + debugVal( activity ));
		} else if( newActivity === false ){ 
			activity = newActivity;
			if( f.disabled ){
				f.disabled = true;
			} else {
				blockActivity = new Array();
				for( var fi=0; fi<f.length; fi++ ){
					blockActivity[fi] = f[fi].disabled;
					f[fi].disabled = true;
				}
			}
			fmDebug( "FM.active()", "changed from " + debugVal( oldActivity ) + " to " + debugVal( activity ));
		} else {
			// don't change activity
			fmDebug( "FM.active()", "current state is " + debugVal( activity ));
		}
		
		return activity;
	}
	if( FMdebug ) {
		document.write( "<a href='#FilterConsole' onclick='javascript:FM.active(true);'>FM.active(true)</a> ");
		document.write( "<a href='#FilterConsole' onclick='javascript:FM.active(false);'>FM.active(false)</a> ");
		document.write( "<a href='#FilterConsole' onclick='javascript:FM.active();'>FM.active()</a> ");
		document.write( "<br>" );
	}


	// **********************************************************************
	// Method visible

	
	this.visible = function ( newVisibility ){
//		if(!this.isOK())    Does not make any sense. Therefore disabled because of bug 1215. 
//			return false;    To solve the problem with this code, whatever it should do, please review with EKM.
		var oldVisibility = visibility;
		fmDebug( "FM.visible()", "called with " + debugVal( newVisibility ));
		
		try{
		if( newVisibility === true ) {
			if (!$.cookie("cookie-fmgr-auto-status"))
				$.cookie("cookie-fmgr-status", null);

			visibility = newVisibility;
			fmDebug( "FM.visible()", "changed from " + debugVal( oldVisibility ) + " to " + debugVal( visibility ));
		} else if( newVisibility === false ){ 
			if (!$.cookie("cookie-fmgr-auto-status"))
				$.cookie("cookie-fmgr-status", "fmgr-inaktiv");

			visibility = newVisibility;
			fmDebug( "FM.visible()", "changed from " + debugVal( oldVisibility ) + " to " + debugVal( visibility ));
		} else {
			// don't change visibility
			fmDebug( "FM.visible()", "current state is " + debugVal( visibility ));
		}
		} catch (e) {}
		return visibility;
	}

	if( FMdebug ) {
		document.write( "<a href='#FilterConsole' onclick='javascript:FM.visible(true);'>FM.visible(true)</a> ");
		document.write( "<a href='#FilterConsole' onclick='javascript:FM.visible(false);'>FM.visible(false)</a> ");
		document.write( "<a href='#FilterConsole' onclick='javascript:FM.visible();'>FM.visible()</a> ");
		document.write( "<br>" );
	}


	
	// **********************************************************************
	// Method noOfProducts

	
	this.noOfProducts = function( n, p, m ){
		currentlyViewed = n;

		fmDebug( "FM.noOfProducts() ", n );
		fmDebug( "FM.noOfProducts() ", "BCmaxMask " + m );
		
		BCmaxMask = m.split(";");
		
		JGO_noOfProducts(p);
		var reArray = RedrawElements[ "FM.title.Span.On" ];
		redrawElement( "FM.title.Span.", currentlyViewed > 0, reArray[1] + " " + currentlyViewed );
		var hiddenNrProducts = xGetElementById("fmkl-resizable");
		if( hiddenNrProducts ) hiddenNrProducts.title = reArray[1] + " " + currentlyViewed;

		var yanop = xGetElementById("yanop");
		if( yanop )
			yanop.innerHTML = n;
			
		this.active( true );
		JGO_Resize();
	}

	// **********************************************************************
	// Method resultCount

	
	this.resultCount = function(){
		var reArray = RedrawElements[ "FM.title.Span.On" ];
		var getCounterLink = NumberOfProductsLink + "&filterSelected=" + currentFilter.join(";");
		fmDebug( "FM.resultCount() ", "<a href='" + getCounterLink + "' target='NrProducts'>" + reArray[1] + getCounterLink + "</a>");

		$.get(getCounterLink, function(data){
			var 	$Filter = $(data).find('Filter'),
				n = $Filter.attr('numberOfProducts'),
				m = $Filter.attr('maxMask'),
				p = new Array();
			
			$Filter.children('item').each(function(i){
				p[p.length] = new Array($(this).attr('id'), $(this).attr('value'));
			});
			FM.noOfProducts( n, p, m );
			redrawElement( "FM.title.Span.", currentFilter.length > 0, reArray[1] + '<font style="font-family: Arial, Helvetica, sans-serif;font-size: 11px;color: white;font-weight: bold;">' + n + '</font>');
			
		});

		fmDebug( "FM.resultCount() ", "Redraw started!" );
	}
	
	if( FMdebug ) document.write( "<br><a href='#FilterConsole' onclick='javascript:FM.resultCount();'>FM.resultCount()</a> ");


	// **********************************************************************
	// Method filtered

	
	this.filtered = function(){
//		fmDebug( "FM.filtered()", "returns  " + currentFilter);
		return currentFilter;
	}
	
	if( FMdebug ) document.write( "<br><a href='#FilterConsole' onclick='javascript:FM.filtered();'>FM.filtered()</a> ");


	// **********************************************************************
	// Method init

	
	this.init = function(){
//		currentFilter.length = 0;
//		currentlyViewed = 0;
		//maxMask = resetMask.join(";").split(";");
		maxMask.length = 0;
		fmDebug( "FM.init()", "");
		initialized=true;
	}

	this.isOK = function() {
		return initialized;
	}

	// **********************************************************************
	// Method status

	
	this.status = function(){

		fmDebug( "FM.status", "startupFilter." + startupFilter.join(";"));
		fmDebug( "FM.status", "currentFilter." + currentFilter.join(";"));
		fmDebug( "FM.status", "resetMask....." + resetMask.join(";"));
		fmDebug( "FM.status", "maxMask......." + maxMask.join(";"));
//		fmDebug( "FM.status", "FilterElement" + FilterElements );
	}


	// **********************************************************************
	// Method reset

	
	this.reset = function(){
		if( blockActivity.length == 0 ) this.active( false );
		currentFilter.length = 0;
		currentlyViewed = 0;
		lastFilterElement = "";
		JGO_noOfProducts(null)
		maxMask.length = 0; 
		BCmaxMask.length = 0; 

		JGO_Redraw();

		for ( var id in FilterElements ){
			tmpELE = xGetElementById("FilterElement_" + id);
			if( tmpELE && tmpELE.type == "select-one" ) 
				tmpELE.selectedIndex = 0;
			else if( tmpELE && tmpELE.type == "checkbox" )
				tmpELE.checked = false;
		}

		this.active( true );
		
		fmDebug( "FM.reset()", "reset current Filter to defaults which are " + debugVal( currentFilter ));
		return currentFilter;
	}
	
	if( FMdebug ) document.write( "<br><a href='#FilterConsole' onclick='javascript:FM.reset();'>FM.reset()</a> ");
	if( FMdebug ) document.write( "<br><a href='javascript:FM.reset();'>FM.reset()</a> ");


	// **********************************************************************
	// Method visible

	
	this.disable = function (){
	}
	this.enable = function (){
	}


	// **********************************************************************
	// Method reset

	
	this.redraw = function(FMNoOfProductsUnfiltered){
		if( FMNoOfProductsUnfiltered != 0 && currentFilter.length == 0) currentlyViewed = FMNoOfProductsUnfiltered;
		if( FMisProductList && BCmaxMask.length == 0) BCmaxMask = FMBCMaxMask.split(";");
		redrawElement( "FM.reset.Icon.", currentlyViewed > 0 && currentFilter.length != 0, "" );
		redrawElement( "FM.reset.Span.", currentlyViewed > 0 && currentFilter.length != 0, "" );
		redrawElement( "FM.showas.Icon.", (currentlyViewed > 0 && currentlyViewed < FMNoOfProductsAllowed && FMisProductList === false) || (FMisProductList === true && FMnoHierarchy != "NoSwitchBack" ), "" );
		redrawElement( "FM.showas.Span.", (currentlyViewed > 0 && currentlyViewed < FMNoOfProductsAllowed && FMisProductList === false) || (FMisProductList === true && FMnoHierarchy != "NoSwitchBack" ), "" );
		redrawElement( "FM.title.Icon.", currentlyViewed > 0 && currentFilter.length != 0, "" );

		var reArray = RedrawElements[ "FM.title.Span.On" ];
		redrawElement( "FM.title.Span.", currentlyViewed > 0 && currentFilter.length != 0, reArray[1] + " " + (currentFilter.length == 0 ? FMNoOfProductsUnfiltered : currentlyViewed ));

		if(currentFilter.length == 0) {
			toggleView( "FilterPath", false );
			toggleView( "AllProductsPath", true );
		}
		else {
			toggleView( "FilterPath", true );
			toggleView( "AllProductsPath", false );
		}

			
		for (var id in FilterElements){
			ele = xGetElementById("FilterElement_" + id);
			if( !ele || ele.type == "select-one" ) continue;
			var curFE = FilterElements[id];
			var allowed = false;
			for( var i=0; i<curFE.length; i++ ){
				if( checkMask( curFE[i][1].split(";"), maxMask ) != 0 ){
					allowed = true;
					break;
				}
			}
			if( allowed === true || currentFilter.length == 0 ){
				ele.className = "fm-active";
				ele.disabled = false;
			} else {
				ele.className = "fm-inactive";
				ele.disabled = true;
			}
		}

		fmDebug( "FM.redraw()", "initiated" );
	}

	// **********************************************************************
	// Method refilter

	
	this.refilter = function( ele ){

		
		this.active( false );
	
		// remember the Mask that was used when the page was called
		if( resetMask.length == 0 ){
			fmDebug( "FM.refilter()", "maskswitch " + maxMask );
			resetMask = maxMask.join(";").split(";");
			maxMask = new Array();
		}
	
		// get the currently selected value
		if( ele && ele.type == "select-one" ){
			currentIndex = ele.options[ele.selectedIndex].value;
		}
		
		fmDebug( "FM.refilter()", "CurrentFilter" + currentFilter );
		
		// emtpy the currentFilter
		currentFilter.length = 0;
		
		// remember the last FilterElement
		lastFilterElement = ele.id;
		
		for ( var id in FilterElements ){
			tmpELE = xGetElementById("FilterElement_" + id);
			var mask = "";
			
			// get the mask bit for the newly selected FilterElement
			if( tmpELE.type == "select-one" ) {
				mask = tmpELE.options[tmpELE.selectedIndex].value;
				if( mask == "*" || mask == "" ) continue;
			} else if( tmpELE.type == "checkbox" && tmpELE.checked === true ) {
				mask = tmpELE.value;
			} else {
				continue;
			}
			
			// set the currentfilter with the mask if there is nothing selected until now
			if( mask == "" || mask == "*" ){
				mask = new Array();
				for( var i=0; i<maxMask.length; i++ ){
					mask[i] = 0;
				}
			} else 
			mask = mask.split(";");
			
			if( currentFilter.length == 0 ) {
				currentFilter = mask;
				continue;
			}
			
			// if there is already something filtered add only the additional bit to the currentfilter
			for( var i=0; i<Math.min(currentFilter.length, mask.length); i++ ){
				if( mask[i] == 0 ) continue;
				currentFilter[i] = mask[i];
				break;
			}
		}
		
		fmDebug( "FM.refilter()", "restart Filter changed with " + currentFilter );

		// request a new list if the selection could get bigger and productlist is shown
		if( FMnoHierarchy != "NoSwitchBack" ){
			fmDebug( "FM.refilter()", FMnoHierarchy + ', bFMListRequest: '+bFMListRequest);
			//if(bFMListRequest===true && confirm('loadList'))
			//	FMrequestList();
				
			var eleID = lastFilterElement.split("_")[1];
			if( (FilterElements[eleID] && FilterElements[eleID]["initialSelected"] != "*" && FMisProductList === true) || bFMListRequest === true  ) {
				fmDebug( "FM.refilter()", 'FMrequestList();');
				FMrequestList();
				return;
			}	
		}
		else
			fmDebug( "FM.refilter()", FMnoHierarchy );

		// check if all values are default ...
		if( currentIndex == "*" ){
			var bReset = true;
			for( var i=0; i<currentFilter.length; i++ ){
				if( currentFilter[i] != 0 ){
					bReset = false;
					break;
				}
			}
			// and if they are, call the reset funtion as if the user clicked the reset Button
			// instead of set the value back to default
			if( bReset === true ){
				this.reset();
				return false;
			}
		}

		
		this.resultCount();
		fmDebug( "FM.refilter()", "new maxMask = " + maxMask );
		return currentFilter;
	}
	
	if( FMdebug ) document.write( "<br><a href='#FilterConsole' onclick='javascript:FM.refilter();'>FM.refilter()</a> ");


	// **********************************************************************
	// Method request

	
	this.request = function(activeFilterFromServer, FMNoOfProductsAllowed){
		fmDebug( "FM.request()", "request a new Reload of all: OK and FM " + debugVal( activeFilterFromServer ) + " Filter " + currentFilter.join(";"));
		if( activeFilterFromServer == "" ) return currentFilter.join(";");
		
		startupFilter = activeFilterFromServer.split(";");
		currentFilter = activeFilterFromServer.split(";");
		
		for (var id in FilterElements){
			var ele = xGetElementById("FilterElement_" + id);
			if( ele && ele.type == "select-one" ){
				ele.options.length = 1;
				//fmDebug( "FM.request()", "default in Filter " + id + " set to " + FilterElements[id][i][0]);
				for( var i=0; i<FilterElements[id].length; i++ ){
					if( checkMask( FilterElements[id][i][1].split(";"), startupFilter ) != 0 ){
						fmDebug( "FM.request()", "default in Filter " + id + " set to " + FilterElements[id][i][0]);
						ele.options[2] = new Option( FilterElements[id][i][0], FilterElements[id][i][1], true, true );
						FilterElements[id]["initialSelected"] = FilterElements[id][i][1];
					} 
				}
			} else if ( ele && ele.type == "checkbox" ){
				if( checkMask( FilterElements[id][0][1].split(";"), startupFilter ) != 0 ){
					fmDebug( "FM.request()", "Filter " + id + " checked ");
					ele.checked = true;
					FilterElements[id]["initialSelected"] = FilterElements[id][0][1];
				}
			}
		}

		return currentFilter.join(";");
	}
	
	if( FMdebug ) document.write( "<br><a href='#FilterConsole' onclick='javascript:FM.request();'>FM.request()</a> ");


	// **********************************************************************
	// Method maxSelection

	
	this.maxSelection = function( bitmask ){
		for( var i=0; i<bitmask.length; i++ ){
			if( maxMask[i] )
				maxMask[i] = maxMask[i] | bitmask[i];
			else 
				maxMask[i] = bitmask[i];
		}
//		fmDebug( "FM maxSelection", maxMask.join(";") );
		return maxMask.join(";");
	}

	

	// **********************************************************************
	// Method addFilterElement

	
	this.addFilterElement = function( id, option, value ){
		if( !FilterElements[ id ] ){
			FilterElements[ id ] = new Array();
			FilterElements[id]["initialSelected"] = "*";
		}
			
		var eleFound = false;
		for( var i=0; i<FilterElements[ id ].length; i++ ){
			if( FilterElements[ id ][i][0] == option && FilterElements[ id ][i][1] == value ){
				eleFound = true;
				break;
			}
		}
		if( eleFound === true ){
//			fmDebug( "FM Filter found!" + id, "Value " + option );
		} else {
			FilterElements[ id ][FilterElements[ id ].length] = new Array( option, value );
//			fmDebug( "FM Filter " + id, "Value " + option );
		}
	}


	// **********************************************************************
	// Method addFilterElement
	//
	//
	// sorting:  0 = not sorted, 1 = number sorting, 2 = text sorting

	
	this.Sorting = function( id, sortType, sortOrder ){
		if( ! FilterElements[ id ] ) {
//			fmDebug( "FM FilterSorting nothing for ", id );
			return;
		}
		
		// numeric sort
		if( sortType == 1 ){
			FilterElements[ id ].sort(OptionSort);
		// alphanumeric sort
		} else {
			FilterElements[ id ].sort();
		}
		
		// sort order is reverse
		if( sortOrder == 1 )
			FilterElements[ id ].reverse();

		// add the Event Handlers
		var FE = xGetElementById("FilterElement_" + id);
		if( FE && FE.type == "select-one" ){
			if( document.all ){
				if( navigator.appVersion.indexOf("MSIE 6.0") == -1 ){
//					fmDebug( "FM FilterEvents IE set", navigator.appVersion );
					FE.setAttribute("onmouseover", "");
				} else {
//					fmDebug( "FM FilterEvents IE6 set", navigator.appVersion );
					FE.setAttribute("onfocusin", "");
				}
			} else {
//				fmDebug( "FM FilterEvents FF set", "" );
				FE.setAttribute("onfocus", "FM.SetOptions(this);");
				FE.setAttribute("onmouseover", "");
				FE.setAttribute("onfocusin", "");
			}
		} else {
//			fmDebug( "FM Sorting", "what about type " + FE.type );
		}


//		fmDebug( "FM FilterSorted ", id );
	}



	// **********************************************************************
	// Method onBlur

	
	this.onBlur = function( ele ){
		if( currentIndex == "" || ele.type != "select-one") return true;
		for( var i=0; i<ele.options.length; i++ ){
			if( ele.options[i].value == currentIndex ) {
				ele.options[i].selected = true;
				break;
			}
		}
		return true;
	}



	// **********************************************************************
	// Method SetOptions
	//
	// l.options[l.options.length] = new Option( sortOptions[i][0], sortOptions[i][1], (sortOptions[i][0] == selectedOptions[combo] ? true : false), (sortOptions[i][0] == selectedOptions[combo] ? true : false));

	
	this.SetOptions = function( ele ){
		if( ele.id == lastFilterElement && ele.selectedIndex!=0 ) {
			fmDebug("FM.setOptions ", "Refill Skipped!" );
			return;
		}
		if( ele.type == "select-one" ){
			currentIndex = ele.options[ele.selectedIndex].value;
			fmDebug("FM.setOptions ", "currentIndex = " + currentIndex );
			var curFE = FilterElements[ ele.id.replace(/FilterElement_/ig, "") ];

			if( curFE ) {
				while( ele.options.length > 1 ){
					ele.options[ele.options.length -1] = null;
				}
					
				fmDebug("FM.setOptions ", "start elements = " + ele.options.length + " FilterElements " + curFE.length );
				fmDebug("FM.setOptions " + ( BCmaxMask.length != 0 ? " use BC " : " use own " ), "maxMask = " + maxMask + " BCmaxMask " + BCmaxMask );

				for( var i=0; i<curFE.length; i++ ){
					if( checkMask( curFE[i][1].split(";"), ( BCmaxMask.length != 0 ? BCmaxMask : maxMask )) == 0 ){
						if( FMdebug === true ){
							ele.options[ele.options.length] = new Option( curFE[i][0] + " (disabled!)", curFE[i][1]);
							ele.options[ele.options.length-1].disabled = true;
							ele.options[ele.options.length-1].style.color = "red";
						}
					}else {
						ele.options[ele.options.length] = new Option( curFE[i][0], curFE[i][1] );
						if( curFE[i][1] == currentIndex ){
							ele.options[ele.options.length-1].selected = true;
							fmDebug("FM.setOptions ", "nowSelected = " + ele.options[ele.options.length-1].value );
						}
					}
				}
//				fmDebug("FM.setOptions ", "end elements = " + ele.options.length );
			}
			fmDebug("FM.setOptions ", "opening the field for selection!" );
		} else {
			fmDebug("FM.setOptions ", "ele.type is " + ele.type );
		}
	}



	// **********************************************************************
	// Method allowedMask

	
	this.allowedMask = function( mask ){
		var allowed = 1;
		if( currentFilter.length == 0 || mask == "" ) return allowed;

		var m = mask;
		var v = currentFilter;

		for( var i=0; i< Math.min(v.length, m.length); i++ ){
			if( v[i] == 0 ) continue;
			if( (v[i] & m[i]).toString(2) != Number(v[i]).toString(2) ) {
				allowed = 0;
//				fmDebug( "FM.allowedMask NOT allowed" + ( v[i] & m[i]).toString(2), Number(v[i]).toString(2) + " with \n" + Number(m[i]).toString(2));
				break;
			}
//			fmDebug( "FM.allowedMask allowed" + ( v[i] & m[i]).toString(2), Number(v[i]).toString(2) + " with \n" + Number(m[i]).toString(2));
		}
//		fmDebug("FM.allowedMask ", "allowed = " + allowed );
		return allowed;
	}

	fmDebug( "FM", "Filter Loaded!" );

}

var FM = new FilterModule();
fmDebug("Document Domain: ", document.domain );

if( FMdebug ) {
	
//	document.write( '</td></tr></table>');
}

