search_url = "/servlet/Satellite";
compare_url = "/servlet/Satellite?pagename=Wienerberger/SR_Product/ProductCompare10";
bookmark_url = "/servlet/Satellite?pagename=Wienerberger/SR_Product/Util/SetSRProduct2Compare10"


search_params = new Object();

var st_params = $.param(search_params);

compare_params = new Object();
compare_params.action="compare";
compare_params.chkbx="";

var bookmark_params = new Object();

var lock=false;




$(document).ready(readyfunc = function() {

	$.ajaxSetup ({
    cache: false
	});


	var WB = {
    overlay: {
        resize: function() {
            var left = $(window).width() / 2 - 500;
            var top = $(window).height() / 2 - 350;
            $("#ov-compare").css({"left": left, "top": top});
        }
    },

    overviewEffects: {
        init: function() {
            $(".DE-teaserbox").each(function() {
                if ($(this).attr("bigurl")) {
                    //preload image
                    var i = new Image();
                    i.src = $(this).attr("bigurl");

                    $(this).hover(function() {
                        $("#J-img-2").attr("src", $(this).attr("bigurl"));
                        $("#J-img-1").stop().animate({opacity: 0}, 250);
                    }, function() {
                        $("#J-img-1").stop().animate({opacity: 1}, 500);
                    });
                }
            });
			$(".DE-teaserbanner").each(function() {
                if ($(this).attr("bigurl")) {
                    //preload image
                    var i = new Image();
                    i.src = $(this).attr("bigurl");

                    $(this).hover(function() {
                        $("#J-img-2").attr("src", $(this).attr("bigurl"));
                        $("#J-img-1").stop().animate({opacity: 0}, 250);
                    }, function() {
                        $("#J-img-1").stop().animate({opacity: 1}, 500);
                    });
                }
            });
        }
    },



    headers: {
        imgs: false,
        texts: false,
        size: false,
        index: 0,
        init: function() {
            $("#DE-KeyVisualStart").each(function() {
                if ($(this).children(".J-arrow-l").attr("imgs")) {
                    WB.headers.imgs = $(this).children(".J-arrow-l").attr("imgs").split(",");
                    WB.headers.texts = $(this).children(".J-arrow-l").attr("texts").split("||");
					//alert(WB.headers.texts);
                    WB.headers.size = WB.headers.imgs.length;

                    // preload images
                    WB.headers.preload();
                    $(".J-arrow-l, .J-arrow-r").click(WB.headers.show);
                }
            });
        },

        preload: function() {
            var i;
            for (var o in WB.headers.imgs) {
                i = new Image();
                i.src = WB.headers.imgs[o];
            }
        },

        show: function() {
			//alert(WB.headers.index);
            if ($(this).attr("class") == "J-arrow-l") {
                WB.headers.index--;
                if (WB.headers.index < 0) {
                    WB.headers.index = WB.headers.size - 1;
                }
            } else {
                WB.headers.index++;
                if (WB.headers.index > WB.headers.size - 1) {
                    WB.headers.index = 0;
                }
            }

            $("#J-img-2").attr("src", WB.headers.imgs[WB.headers.index]);
            $("#J-text-2").html(WB.headers.texts[WB.headers.index]);
            $("#J-img-1").stop().animate({opacity: 0}, 450, "swing", function() {
                $("#J-img-1").attr("src", WB.headers.imgs[WB.headers.index]).css("opacity", 1);
            });
            $("#J-text-1").stop().animate({opacity: 0}, 450, "swing", function() {
                $("#J-text-1").html(WB.headers.texts[WB.headers.index]).css("opacity", 1);
            });

        }
    },

    dropdowns: {
        isOpen: false,
        init: function() {
            //add helper DIVs, correct height (IE)
            $("body, #WB-main, #DA-header").prepend('<div class="H-inv"></div>');
            $("body .H-inv, #WB-main .H-inv").height($(window).height());

            //add event listeners (show)
            $("#H-lang, #H-corporate-eh").live("mouseover", WB.dropdowns.show);

            //add event listeners (hide)
            $(".H-inv").live("mouseover", WB.dropdowns.hide);
            $("#ML-inv").live("mouseover", WB.dropdowns.hide);

        },

        show: function() {
            if (!WB.dropdowns.isOpen) {
                if (document.all) {
                    $("#ML-container, #H-corporate-drop").hide();
                } else {
                    $("#ML-container, #H-corporate-drop").fadeOut(50);
                }
                if ($(this).attr("id") == "H-lang") {
                    $("#ML-content").removeClass("small");
                    if ($("#C-main").attr("class") != "T-startoverview") {
                        $("#ML-content").addClass("small");
                    }
                    if (document.all) {
                        $("#ML-container").show(1, WB.dropdowns.showInv);
                    } else {
                        $("#ML-container").fadeIn(400, WB.dropdowns.showInv);
                    }
                } else {
                    if (document.all) {
                        $("#H-corporate-drop").show(1, WB.dropdowns.showInv);
                    } else {
                        $("#H-corporate-drop").fadeIn(350, WB.dropdowns.showInv);
                    }
                }
                WB.dropdowns.isOpen = true;
            }
        },

        showInv: function() {
            $(".H-inv").show();
            WB.dropdowns.isOpen = false;
        },

        hide: function() {
            if (document.all) {
                $("#H-corporate-drop, #ML-container").hide();
            } else {
                $("#H-corporate-drop, #ML-container").fadeOut(200);
            }
            $(".H-inv").hide();
        }
    },

    tabs: {
        init: function() {
            $(".cc-tabs").each(function() {
                //hide content, except first
                $(this).children(".cc-tabs-content").hide();

                //display active tab only
                var id;
                $(".tabheaders a").each(function() {
                    if ($(this).hasClass("on")) {
                        id = $(this).attr("id").split("-")[1];
                    }
                });
                $(".tab-" + id).show();

                //listeners
                $(this).find(".tabheaders a").click(WB.tabs.show);
            });
        },

        show: function() {
            var id = $(this).attr("id").split("-")[1];

            $(this).parent().parent().children(".cc-tabs-content").hide();
            $(this).parent().parent().children(".tab-" + id).show();
            $(this).parent().children("a").removeClass("on");
            $(this).addClass("on");

            return false;
        }
    }
}

	function init(){
		j_paging();
		j_compare();
		j_equalHeights();
		WB.tabs.init();
		WB.dropdowns.init();
    	WB.headers.init();
		WB.overviewEffects.init();
		//$.history.init(pageload);
		//j_history();
	}

	function reinit(){
		j_paging();
		j_compare();
		j_equalHeights();
		//WB.tabs.init();
		WB.dropdowns.init();
    	WB.headers.init();
		WB.overviewEffects.init();
	}

	init();

	$(function() {
		// initialize scrollable
		$(".scrollable").scrollable();
		$.ajaxSetup ({
			cache: false
			});

		// initialize productsearch
		try{


			$(".cc-ps-tab input[type!=hidden]").each(function(){
				//search_params[this.name]=this.value;
				this.checked = "checked";

			});
			$("input[name*='_0_typ']").each(function(){
				search_params[this.name]=this.value;
				this.checked = "checked";
			});/**/
			$("input[name*='nrElem']").each(function(){
				search_params[this.name]=this.value;
				this.checked = "checked";
			});/**/

			// nicht mehr alle unckecken, wegen den gebookmarkten
			$(".cc-product-gallery-item input[type=checkbox]").each(function(){
				// this.checked = "";

			});/**/
		}catch(e){}
	});


	compare_params.sl=search_params.sl;
	st_params = $.param(search_params);




	// zentrale Suchfunktion
	function search(paging){
		st_params = $.param(search_params);
		//$("#ov-sresult-debug").html(st_params);
		//alert(st_params);



		// jump to first page after filter search
		//if(!paging) search_params["pn"]='';

		$("#ajaxloader").show();
		var live = $("#ov-sresult-insert").css("opacity", 0.5);
						$.ajax({
							url: search_url,
							data: search_params,
							cache: false,
							success: $.createQueueCallback(live, function(data){
								live.html(data).css("opacity", 1);
								pagingdata=data;
								//readyfunc();
								reinit();


							}),
							error: function(){
								//immer errors handeln
							}
						});
	}




	// zentrale Comparefunktion
	function compare(){

		//$("#ajaxloader").show();
		var live = $("#ov-compare-insert");
		var urlParams = null == search_params.scope ? "" : "&pN=" + search_params.scope;
						$.ajax({
							url: compare_url + urlParams,
							data: compare_params,
							success: $.createQueueCallback(live, function(data){
								live.html(data);
								$("#ov-compare, #ov-compare-bg").show();
								if ($.browser.msie && parseInt($.browser.version) == 6) {
									$("select").hide();
									window.scrollTo(0, 0);
								}
								reinit();
								WB.tabs.init();
							}),
							error: function(XMLHttpRequest, textStatus, errorThrown){
								//alert(textStatus + " ... " + errorThrown + " ... " + XMLHttpRequest.responseText + " ... "  );
								//immer errors handeln
								//reinit();
							}
						});
	}


	// auf nichts auswaehlen gedrueckt
	$(".cc-selector-clear").click(function() {
        $(this).parents(".cc-selector-group").find("input[type!=hidden]").each(function(){
			delete(search_params[this.name]);
			this.checked = "";
		});

        type_elem = $(this).parent().parent().children("input[name*='_0_typ']").eq(0);
		search_params[type_elem.attr("name")+"_all"] = "false";
		search_params[type_elem.attr("name")+"_no"] = "true";

		// jump to first page after filter search
		search_params["pn"]='';

		st_params = $.param(search_params);

     // for browser history
		YAHOO.util.History.navigate("myModule", st_params);

		search();
        return false;
    });




// auf alles auswaehlen gedrueckt
	$(".cc-selector").click(function() {
		$(this).parents(".cc-selector-group").find("input[type!=hidden]").each(function(){
			delete(search_params[this.name]);
			this.checked = "checked";
		});

		type_elem = $(this).parent().parent().children("input[name*='_0_typ']").eq(0);
		search_params[type_elem.attr("name")+"_all"] = "true";
		search_params[type_elem.attr("name")+"_no"] = "false";

		// jump to first page after filter search
		search_params["pn"]='';

		st_params = $.param(search_params);

		// for browser history
		YAHOO.util.History.navigate("myModule", st_params);

		search();
		return false;
	});




	// check if all checkboxes are checked/unchecked
	// if all checked/unchecked then remove whole filter from search
	// else set each checked param
	function checkAllChecked(parentdiv){
		type_elem = parentdiv.children("input[name*='_0_typ']").eq(0);
		all_checked = true;
		all_unchecked = true;

		parentdiv.find("input[type!=hidden]").each(function(){
			if(this.checked){all_unchecked=false;}
			else{all_checked=false;}
		});

		if(all_checked || all_unchecked){
			parentdiv.find("input[type!=hidden]").each(function(){
				delete(search_params[this.name]);
			});
		}
		else {
			parentdiv.find("input[type!=hidden]").each(function(){
				if(this.checked==true) search_params[this.name]=this.value;
				else delete(search_params[this.name]);
			});
			//search_params[type_elem.attr("name")] = type_elem.attr("value");
		}

		if(all_checked) {
			search_params[type_elem.attr("name")+"_all"] = "true";
		}else {
			search_params[type_elem.attr("name")+"_all"] = "false";
		}

		if(all_unchecked) {
			search_params[type_elem.attr("name")+"_no"] = "true";
		}else {
			search_params[type_elem.attr("name")+"_no"] = "false";
		}
		st_params = $.param(search_params);
		//alert(st_params);
	}


	// ein Suchfilter Checkbox gedrueckt
	$(".cc-tabs input").click(function() {


		if(this.checked===true) {
			search_params[this.name]=this.value;
		}
		else{
			delete(search_params[this.name]);
		}

		var parentdiv = $(this).parent().parent().parent();
		checkAllChecked(parentdiv);

		// jump to first page after filter search
		search_params["pn"]='';

		st_params = $.param(search_params);
		//alert(st_params);

		// for browser history
		YAHOO.util.History.navigate("myModule", st_params);

		search();
		//return false;
    });




	// toggle product type filter param
	// check if all checkboxes are checked/unchecked
	// atm not used
	function checkFilterType(parentdiv){
		type_elem = parentdiv.children("input[name*='_0_typ']").eq(0);
		all_checked = true;
		all_unchecked = true;
		//alert(parentdiv.find("input[type!=hidden]").size());

		parentdiv.find("input[type!=hidden]").each(function(){
			if(this.checked){all_unchecked=false;}
			else{all_checked=false;}
		});

		if(all_checked || all_unchecked){
			search_params[type_elem.attr("name")] = '';
		}
		else {
			search_params[type_elem.attr("name")] = type_elem.attr("value");
		}

		st_params = $.param(search_params);
		//alert(st_params);
	};


	// ein Suchfilter Select gedrueckt
	$(".cc-tabs select").change(function() {

		if(this.value!=0) search_params[this.name]=this.value;
		else search_params[this.name]='';

		st_params = $.param(search_params);

		// jump to first page after filter search
		search_params["pn"]='';

		// for browser history
		YAHOO.util.History.navigate("myModule", st_params);

		search();
		return false;
    });




// ein Suchfilter Paging-Link gedrueckt
	function j_paging(){
		$("#ov-sresult-insert .cc-ps-result .cc-paging a").click(function(event) {
			event.preventDefault();
			number = $(this).attr("id").replace("paging_number_","");
			//number = number.replace("paging_number_","")
			search_params["pn"]=number;
			st_params = $.param(search_params);
			//alert(st_params);

			// for browser history
			YAHOO.util.History.navigate("myModule", st_params);

			//search(true);
			return false;
		});
	}






	// auf vergleichen gedrueckt
	function j_compare(){
			$("#act-compare").click(function() {
				//compare_params.chkbx += compare_params.chkbx;
				compare();
				
				return false; //WB-168
			});

	}



		// im Produktdetail Vergleichen checkbox angeklickt
		$("#detail_bookmark").bind($.browser.msie ? 'propertychange': 'change', function(e) {
			if (e.type == "change" || (e.type == "propertychange" && window.event.propertyName == "checked")) { // fix for IE
				var elem = this;
				compare_params.chkbx = compare_params.chkbx+";"+elem.value;
				bookmark_params.ptyp = search_params.scope;
				bookmark_params.sl = search_params.sl;
				bookmark_params.prodid = elem.value;
				bookmark_params.checked = elem.checked;
				$.get(bookmark_url, bookmark_params, function(data) {
				  //$("#ov-sresult-debug").html(data);
				});
				$("#hideout_compareintro").show();
			}
		});


	// Prokat produktfilter
	$("#selectedSerie select").change(function() {


		st_params = $.param(search_params);

		 $.get(search_url, search_params, function(data) {
          	  $("#ov-sresult-insert").html(data);
      		  });




        return false;
    });



    $("#ov-compare-close, #ov-compare-bg").live("click", function() {
        $("select").show();
        $("#ov-compare, #ov-compare-bg").hide();
		tabid = $(".cc-tabs .tabheaders a[class=on]").eq(0).attr("id");
		tabid = "."+tabid.replace('h','');
		$(tabid).eq(0).show();
		//reinit();
    });

    $("#ov-compare").each(function() {
        var left = $(window).width() / 2 - 500;
        var top = $(window).height() / 2 - 350;
		//top = 1;
        $("#ov-compare").css({"left": left, "top": top});
    });

	$(window).resize(function() {
		$("#ov-compare").each(WB.overlay.resize);
	});

    $(".cc-Tile2Acc .cc-arrow-down ").click(function() {
        $(this).parent().find("ul").toggle(500);
    });


	//Klick in das Suchfeld
	var inputtext = $("#procatformbox input[type=text]").val();
	$("#procatformbox input[type=text]").focus(function() {
        if($(this).val()===inputtext) $(this).val("");
    });
	$("#procatformbox input[type=text]").blur(function() {
        if($(this).val()==0) $(this).val(inputtext);
    });


	// Browser History Setup
	try {
		var myModuleBookmarkedState = YAHOO.util.History.getBookmarkedState("myModule");
		if(myModuleBookmarkedState) {
			restoreState(myModuleBookmarkedState);
		}

		// If there is no bookmarked state, assign the default state:
		var myModuleInitialState = myModuleBookmarkedState || $.param(search_params);
		function myModuleStateChangeHandler (state) {
			// Update the UI of your module according to the "state" parameter
			//console.log("myModuleStateChangeHandler: "+state);
			//alert("1"+state);
			//$("#ov-sresult-debug").html(state);
			search_params = unparam(state);
			checkboxes(search_params);
			search(true);

		}
		YAHOO.util.History.register("myModule", myModuleInitialState, myModuleStateChangeHandler);

		YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

	} catch (e) {	}

	function restoreState(myModuleBookmarkedState){
		//console.log("restore");
		//alert("2")
		search_params = unparam(myModuleBookmarkedState);
		checkboxes(search_params);
		search(true);


	}

	function checkboxes(search_params){
		$("input").each(function(){
			if(!search_params[this.name]) {
				this.checked= "";
			}else{
				this.checked= "ckecked";
			}
			if((this.name).indexOf("_typ")>0){

				if(search_params[this.name+"_no"]=="true"){
					$(this).parents(".cc-selector-group").find("input[type!=hidden]").each(function(){
						delete(search_params[this.name]);
						this.checked = "";
					});
				}

				if(search_params[this.name+"_all"]!="false"){
					$(this).parents(".cc-selector-group").find("input[type!=hidden]").each(function(){
						delete(search_params[this.name]);
						this.checked = "checked";
					});
				}
			}

		});
	}

	function unparam(p){
		var params = {};
		var pairs = p.split('&');
		for (var i=0; i<pairs.length; i++) {
			var pair = pairs[i].split('=');
			var accessors = [];
			var name = decodeURIComponent(pair[0]), value = decodeURIComponent(pair[1]);

			var name = name.replace(/\[([^\]]*)\]/g, function(k, acc) { accessors.push(acc); return ""; });
			accessors.unshift(name);
			var o = params;

			for (var j=0; j<accessors.length-1; j++) {
				var acc = accessors[j];
				var nextAcc = accessors[j+1];
				if (!o[acc]) {
					if ((nextAcc == "") || (/^[0-9]+$/.test(nextAcc)))
						o[acc] = [];
					else
						o[acc] = {};
				}
				o = o[acc];
			}
			acc = accessors[accessors.length-1];
			if (acc == "")
				o.push(value);
			else
				o[acc] = value;
		}
		return params;

	}

	// vergleichen-Checkboxen auf eine Höhe
	function j_equalHeights(){$("#ov-sresult-insert .cc-product-gallery .gal-img-titl a").equalHeights();}

	// produkte auf eine Hoehe
	function j_equalHeights(){$("#ov-sresult-insert .cc-product-gallery .cc-product-gallery-item").equalHeights();}

	// Helper fuer die Queue
	$.createQueueCallback = function(jElm, fn, type){
							type = type ||
								'fx';
							return function(){
								var that = this,
									args = arguments;

								jElm = $(jElm);
								jElm.queue(type, function(){
									fn.apply(that, args);
									jElm.dequeue(type);
								});
							};
						};







});


// Helper fuer die Queue
	$.createQueueCallback = function(jElm, fn, type){
							type = type ||
								'fx';
							return function(){
								var that = this,
									args = arguments;

								jElm = $(jElm);
								jElm.queue(type, function(){
									fn.apply(that, args);
									jElm.dequeue(type);
								});
							};
						};

// ein Produkt zum Vergleichen angeklickt
function chk_toggle(elem){
				compare_params.chkbx = compare_params.chkbx+";"+elem.value;
				bookmark_params.ptyp = search_params.scope;
				bookmark_params.sl = search_params.sl;
				bookmark_params.prodid = elem.value;
				bookmark_params.checked = elem.checked;
				$.get(bookmark_url, bookmark_params, function(data) {
				  $("#ov-sresult-debug").html(data);
				});

   	}



// im Produktdetail Vergleichen checkbox angeklickt
	function chk_toggle_detail(elem){
		// not used atm
	}







