

/**
 * Fades the background of a element to the background of another css class
 * @param targetElement
 * @param newClass
 * @return
 */
function backgroundFade(targetElement,newClass){

    if(!targetElement){
        console.error("unavailable targetElement in newClass");
        return;
    }
    targetElement.cleanWhitespace();
   
    // if there is a childNode => if childNode is a span, as it is the case on the "new" system of the CompareBox.tag, jump to 'else'
    if(targetElement.childNodes.length > 0 && targetElement.childNodes[0].nodeName != "SPAN"){
        var div = targetElement.childNodes[0];
        div.className="";
    }else {
        var div = document.createElement('div');
    }
       
    div.className=newClass;
    div.style.height='100%';
    div.style.width='100%';
    div.style.visibility='hidden';
    div.style.opacity='0';
    targetElement.insert(div);
    new Effect.Opacity(div, {duration:0.2, from:0.0, to:1.0,
        beforeStart:function(){
            div.style.visibility='visible';
        },
        afterFinish:function(){
            // TODO: very dirty
            var cssClass;
            if(targetElement.hasClassName("mir"))
                cssClass="mir";
            targetElement.className=cssClass+" "+newClass;
       
        }
    });
}



/**
 * links back to opener window
 * @param url
 * @return
 */
function to_old_win(url) {
    if(typeof(parent) != "undefined" && parent != null && parent.send_to_old_win) {
        parent.send_to_old_win(url);
    } else {
        try {
            opener.location.href = url;
            opener.focus();
        } catch( ex ) {
            //if(error) alert(ex);
        }
    }
    return false;
}


/**
 * Ajax.Request.abort
 * extend the prototype.js Ajax.Request object so that it supports an abort method
 */
 
if(window.Ajax && window.Ajax.Request){
    Ajax.Request.prototype.abort = function() {
        // prevent and state change callbacks from being issued
        this.transport.onreadystatechange = Prototype.emptyFunction;
        // abort the XHR
        this.transport.abort();
        // update the request counter
        Ajax.activeRequestCount--;
    };
}


/**
 * SequenceBox
 */
var SequenceBox = Class.create({
	   
    initialize: function(outerBox,boxClass, pageInfo, buttonLeft, buttonRight){
       
        if(!outerBox)
            return;
       
        // outerBox = box width overflow hidden; innerBox = boxcontainer to shift
        this.outerBox = outerBox;
        this.innerBox = outerBox.childElements()[0];

        // boxes = boxes in sequence box
        this.boxes = outerBox.select(boxClass);
        this.boxNumber = this.boxes.length;
        this.currentBox = 1;

        // calculate widths and heights
        this.setHeight();
       
        // page info
        this.pageInfo = pageInfo ? pageInfo : false;
        if(this.pageInfo)
            this.pageInfo.innerHTML = "1 / "+this.boxNumber;
       
        // buttons
        this.buttonLeft = buttonLeft;
        this.buttonRight = buttonRight;
    },
    setHeight: function() {
        // calculate widths and heights
        this.boxWidth = this.outerBox.getDimensions()['width'];//this.boxes[0].getDimensions()['width'];
        
        var width = this.boxWidth;
        
        this.boxes.each(function(a){
      
        	a.setStyle({"width":width+"px"});
        	
        });
        
        //debugger;
        //alert(this.innerBox.getHeight());
   
        this.outerBox.setStyle({"height":this.innerBox.getDimensions()['height']+"px"});
    },
   
    previous: function(){
       
        if(this.currentBox <= 1)
            return;
        this.currentBox--;
   
        new Effect.Morph(this.innerBox, {
            style: 'left:-'+this.boxWidth*(this.currentBox-1)+'px',
            duration:0.4,
            transition: Effect.Transitions.linear
        });   
       
        if(this.currentBox <= 1){
            $$$("."+this.buttonLeft).addClassName(this.buttonLeft+"Inactive");
            $$$("."+this.buttonLeft).addClassName("inactive");
        }else{
            $$$("."+this.buttonLeft).removeClassName(this.buttonLeft+"Inactive");
            $$$("."+this.buttonLeft).removeClassName("inactive");
        }
        $$$("."+this.buttonRight).removeClassName(this.buttonRight+"Inactive");
        $$$("."+this.buttonRight).removeClassName("inactive");
        this.pageInfo.innerHTML = this.currentBox + " / "+this.boxNumber;
       
    },
    next: function(){
       
        if(this.currentBox >= this.boxNumber)
            return;
        this.currentBox++;
       
        new Effect.Morph(this.innerBox, {
            style: 'left:-'+this.boxWidth*(this.currentBox-1)+'px',
            duration:0.4,
            transition: Effect.Transitions.linear
        });   
       
        if(this.currentBox >= this.boxNumber){
            $$$("."+this.buttonRight).addClassName(this.buttonRight+"Inactive");
            $$$("."+this.buttonRight).addClassName("inactive");
        }else{
            $$$("."+this.buttonRight).removeClassName(this.buttonRight+"Inactive");
            $$$("."+this.buttonRight).removeClassName("inactive");
        }
        $$$("."+this.buttonLeft).removeClassName(this.buttonLeft+"Inactive");
        $$$("."+this.buttonLeft).removeClassName("inactive");
        this.pageInfo.innerHTML = this.currentBox + " / "+this.boxNumber;
    }
});



/**
 * 
 * function, which hides and shows collapsible containers (attributes and/or answerinfos)
 * 
 * @param link
 * 			the link, which toggles the classes onclick()
 * @param id
 * 			id of the container, which will be hidden or shown
 * @param closeOthers
 * 			if true (for example in AttributesView) - only one hidden container is opened at a time, all others are closed (not enough space for all opened)
 * @return
 */
function toggleContainer(link, id, closeOthers) {

	if($(link).hasClassName("collapsed-container")) {
		if(closeOthers) {
			$$(".collapse-link").each(function(el) {
				if(el.hasClassName("opened-container")) {
					el.removeClassName("opened-container");
					el.addClassName("collapsed-container");
				}
			});
		}
		$(link).removeClassName("collapsed-container");
		$(link).addClassName("opened-container");
	} else {
		$(link).removeClassName("opened-container");
		$(link).addClassName("collapsed-container");
	}

	if($(id).style.display == "none" || $(id).hasClassName("hiddenInfo")) {
		if(closeOthers) {
			$$(".hidden-container").each(function(el) {
				if(el.style.display == "block") {
					el.style.display = "none";
				}
			});
		}
		$(id).style.display = "block";
		$(id).removeClassName("hidden");
	} else {
		$(id).style.display = "none";
	}     
} 


/**
 * this function checks for positive or negative attributes in the product wrapper, then marks the wrapper with one of 3 CSS-classes (independent of the clustering)
 * useful for some sort of product marking (for example "100% grafic"), if the sort order is other than "needs" (because the clusters are ordered another way then)
 * 
 */
function markProductWrapper() {
	$$(".product-wrapper").each(function(wrapper) {
		
		var negativeAttributes = wrapper.getElementsBySelector("span.negative").length;
		var positiveAttributes = wrapper.getElementsBySelector("span.positive").length;

		if(negativeAttributes == 0 && positiveAttributes > 0) {
			wrapper.addClassName("product-matches-all");
		} else if(negativeAttributes > 0 && positiveAttributes > 0) {
			wrapper.addClassName("product-matches-most");
		} else if(negativeAttributes > 0 && positiveAttributes == 0) {
			wrapper.addClassName("product-matches-some");
		}
	});
}

/**
 * checks for selected compare checkboxes and disables them, if limit is reached - limit has to be defined in the jsp and reached to this function as parameter
 */
function setChecks(compareLimit) {
	var maxChecks = compareLimit;
	var checkCount = 0;
	  
	if(document.consresult){
		// Determine the number of checked boxes
		for (var i=0; i<document.consresult.compare.length; i++) {
			if (document.consresult.compare[i].checked) {
			    checkCount++;
			 }
		}

		// Enable/disable unchecked boxes
		for (var i=0; i<document.consresult.compare.length; i++) {
		   if (!document.consresult.compare[i].checked) {
		      document.consresult.compare[i].disabled = (checkCount==maxChecks);
		   }
		}
	}
}

//this function determines whether the event is the equivalent of the microsoft
//mouseleave or mouseenter events. see http://dynamic-tools.net/toolbox/isMouseLeaveOrEnter/
function isMouseLeaveOrEnter(e, handler)
{		
	var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
	while (reltg && reltg != handler) reltg = reltg.parentNode;
	return (reltg != handler);
}
