
/**
 * DomReady handler for review details
 */

$(document).ready(function() {
	
	$('body').append('<div></div>');
	dialogDiv = $("<div></div>").first();
	//var targetUrl = $(this).attr("href");
	
	$('a.confirm').bind('click', function(e) {
		dialogTitle = $(this).attr('title');
		confirmText = $(this).attr('rev');
		linkUrl = $(this).attr('href');
		e.preventDefault();
		dialogDiv.html(confirmText);
		dialogDiv.dialog({
			resizable: false,
			height: 'auto',
			modal: true,
			title: dialogTitle,
			buttons: {
				"Abbruch": function() {
					$( this ).dialog( "close" );
					return false;
				}, 
				"Ok": function() {
				$( this ).dialog( "close" );
				window.location.href = linkUrl;
				}
			}
		});
	});
	/*
	$('#kat').change(function(){
		if ($(this).val() != '') {
			$('#sort option').attr('disabled', '');
		} else {
			$('#sort option').attr('disabled', 'disabled');
		}
	} );
	$('#sort option').attr('disabled', $('#kat').val() != '' ? '' : 'disabled');
	*/
	//
	// Suchfilter
	$('#prodfilter input[type=checkbox]').bind('change', this, function (fo) { f = this.form; window.setTimeout("f.submit();",100); });
	$('#prodfilter input[type=radio]').bind('change', this, function (fo) { f = this.form; window.setTimeout("f.submit();",100); });
	$('#prodfilter select').bind('change', this, function (fo) { f = this.form; window.setTimeout("f.submit();",100); });
	// multibuy checkbox
	$('input[type=checkbox].mbcb').bind('change', this, mbchange);
	
//	$( '.bew_main' ).each(function(item){
//		if (item && (subdiv = $(item).find( '.bew_more' )) != undefined) {
//			var thisSlider = new Fx.Slide(subdiv);
//			var thisImg = item.getElement('img');
//			thisSlider.hide();
//			thisImg.addEvent('click', function(e){
//				e.stop();
//				thisImg.src = "/ci/expanding.png";
//				thisSlider.addEvent('complete', function(e) {
//					thisImg.src = this.open ? "/ci/expanded.png" : "/ci/expand.png";
//					e.stop();
//				});
//				thisSlider.toggle();
//			});
//		}
//	});

	if ($('#quicksearch').length) {
		$('#quicksearch').
			autocomplete({source: "/shop/quicksearch"}, {
				formatItem: function(item) { return "AA"+item.text; }
			}).
			attr("autocomplete", "off").
			bind("autocompleteselect", function(e,ui) {
				if (ui.item.disabled) return false;
				if (ui.item.id != undefined && ui.item.id != '') {
					window.location.href = ui.item.id;
					return false;
				}
				alert(ui.item.id);
			}).
			data("autocomplete")._renderItem = function( ul, item ) {
					result = $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>"+ item.label + "</a>" )
					.appendTo( ul );
					if (item.disabled) {
						$(result).find('a').attr('disabled', 'disabled');
					}
					return result;
					};
	}
	
});

var mbdata = new Array();

var mbvalid = 0;

function mbinit(id, name, count, price) {
	// read all cookies
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(cookie.indexOf("=")+1));
                mbdata = cookieValue.split(",");
                for(var i=mbdata.length-1;i >= 0; --i) {
                	if (isNaN(mbdata[i]) || mbdata[i]=="") {
                		alert("Cleanup: remove "+i+": "+mbdata[i]);
                		mbdata.splice(i,1);
                	}
                }
                break;
            }
        }
    }
    f = $("form#multibuy");
    if (!f.length) alert("Form not found");
    else {
	    //f.append($('<input type="hidden"></input>').attr('id','mbaktion').val(id));
	    //f.append($('<input type="hidden"></input>').attr('id','mbname').val(name));
	    //f.append($('<input type="hidden"></input>').attr('id','mbprice').val(price));
		//f.append($('<input type="hidden"></input>').attr('id','mbcount').val(count));
    }
    mbupdate();
}

function mbfind(id) {
	for(var i=0; i < mbdata.length; i++) {
		if (id == mbdata[i]) return i;
	}
	return -1;
}
function mbchange(o) {
	c = $(this).attr('checked');
	id= $(this).val();
	idx = mbfind(id);
	if (c) {
		if (idx < 0) {
			mbdata[mbdata.length] = id;
		}
	} else {
		if (idx >= 0) {
			mbdata.splice(idx, 1);
		}
	}
	$.cookie($("#mbname").val(), mbdata.join(","));
	//alert("Multibuy = "+mbdata.join(","));
	mbupdate();
}

var mbstatus;

function mbupdate() {
	$('input[type=checkbox].mbcb').each(function(index, el) {
		id=$(el).val();
		if (mbfind(id) >= 0) {
			$(el).attr('checked', 'checked');
		} else {
			$(el).attr('checked', '');
		}
	});
	mbvalid = 0;
	var selected = mbdata.length;
	mbstatus = selected+" Artikel ausgewählt";
	var needcount = $("input#mbcount").val();
	
	if (selected == needcount) {
		$("#mbfooter a.mbsubmit").removeClass('mbsoff').addClass('mbson');
		mbvalid = 1;
	} else {
		$("#mbfooter a.mbsubmit").removeClass('mbson').addClass('mbsoff');
		if (selected > needcount) {
			mbstatus += " - Bitte entfernen Sie "+(selected-needcount)+" Artikel aus Ihrer Auswahl";
		} else {
			mbstatus += " - noch "+(needcount-selected)+" benötigt";
		}
	}
	$("#mbfooter span.mbinfo").html(mbstatus);
}


function mbsubmit() {
	var aktion = $("input#mbaktion").val();
	$.cookie($("#mbname").val(), null);
	href = location.protocol+"//"+location.hostname;
	if (location.port > 0) href += ":"+location.port;
	href += '/shop/InDenWarenkorb?product='+encodeURIComponent(mbdata.join(","))+'&where='+encodeURIComponent($("input#returnurl").val())+'&aktion='+encodeURIComponent(aktion);
	if (!mbvalid) return false;
	
	window.location = href;
}


function qsQuery(query, qsResponse) {
	alert("query="+query.term);
}
function qsResponse(data) {
	alert("Response: "+data);
}
function tree_toggle(o) {
	var li = $(o).closest("LI");
	if (li.hasClass("tree_menu")) {
		li.toggleClass("tree_closed");
		li.toggleClass("tree_expanded");
	}
}


/*
 * floater
 * [0] = object the visible size is calculated from
 * [1] = UL object
 * [2] = single item width
 * [3] = display offset (items)
 * [4] = items in list
 */
var floaters = new Array();
/**
 * Event handler for List Floater
 */
function resizeList() {
	// Iterate through all registered floaters
	for(l=0; l < floaters.length; l++) {
		// Calc max number of visible elements
		//alert("Floater "+l+": width="+floaters[l][0].offsetWidth);
		var w = floaters[l][0].offsetWidth;
		if (w == 0) {
			var b = $('body')[0];
			w = $('body')[0].clientWidth - 242;
		}
		nc = Math.floor(w / floaters[l][2]);
		off = floaters[l][3];
		num = floaters[l][4];
		prev= floaters[l][5];
		next= floaters[l][6];
		tags = floaters[l][1].getElementsByTagName('LI');
		for(i=0;i < tags.length && nc; i++) {
			// Set max size in %
			tags[i].style.width = (100/nc)+'%';
			//tags[i].className = 'box'+nc;

			// Control visibility
			if (i >= off && (i-off)<nc) {
				tags[i].style.display = 'block';
			} else {
				tags[i].style.display = 'none';
			}
		}
		if (off <= 0) prev.fadeTo(0,0); else prev.fadeTo(0,100);
		if (num-nc-off <= 0) next.fadeTo(0,0); else next.fadeTo(0,100);
	}
}

function floaterScroll(fullId, dir) {
	// Find floater
	for(i=0; i < floaters.length; i++) {
		if (floaters[i][0].id == fullId) {
			nc = Math.floor(floaters[i][0].clientWidth / floaters[i][2]);
			off = floaters[i][3];
			num = floaters[i][4];
			//console.log("Scroll(): found list  off="+off+" nc="+nc+" items="+num);
			if (dir < 0 && floaters[i][3] > 0) {
				floaters[i][3]--;
			}
			if (dir > 0 && (num-nc-off) > 0) {
				floaters[i][3]++;
			}
			resizeList();
			return;
		}
	}
	//console.log("Scroll(): floater not found");
}

function floaterRegister(fullId,listId,width) {
	if (!floaters.length) {
		/* First floater: register event handlers */
		$(window).bind('resize', null, resizeList);
		$(document).bind('load', null, resizeList);
		$(document).bind('ready', null, resizeList);
	}
	items = $('LI', '#'+listId).length;
	table = $('#'+fullId).closest('table');
	prevImg = table.find('img.prev');
	nextImg = table.find('img.next');
	//console.log("Registered floater "+fullId+" with "+items+" items");
	floaters[floaters.length] = new Array(document.getElementById(fullId), document.getElementById(listId), width, 0, items, prevImg, nextImg);
}
/* /variable column floater */



/* open/close movie man */

function mmOpenClose(imgId, divId, state, imgClosed, imgChanging, imgOpen, slider) {
	this.imgId = imgId;
	this.divId = divId;
	if (state == undefined)
		this.state = 0;
	if (imgClosed == undefined)
		this.imgClosed = "/ci/expand.png";
	if (imgChanging == undefined)
		this.imgChanging = "/ci/expanding.png";
	if (imgOpen == undefined)
		this.imgOpen = "/ci/expanded.png";
}
var areas = new Array();
var that;
function expandArea(img, thediv) {
	if (!areas[img]) {
		areas[img] = new mmOpenClose(img, thediv);
		that = areas[img];
		that.slider = new Fx.Slide($(that.divId));
	}
	if (that.state) {
		$(that.imgId).src = that.imgChanging;
		$(that.divId).addEvent('complete', function() {
			$(img).src = areas[img].imgClosed;
			areas[img].state = 0;
		});
		that.slider.slideOut();
		that.state = 0;
	} else {
		$(that.imgId).src = that.imgChanging;
		$(that.divId).addEvent('complete', function() {
			$(that.imgId).src = areas[img].imgOpen;
			areas[img].state = 1;
		});
		that.slider.slideIn();
		that.state = 1;
	}
}


