/// <reference path="jquery-1.4.1-vsdoc.js" />

jQuery(function () {
	PulldownMenu.init();
	//ProductGallery.init();
	project.init();
	UpdatePopupLinks();
	InitCountryChanger();
	InitAll();
	InitCategoryMouseover();


	/*== Mainmenu Mouseover ==*/
	jQuery(".noflyout #mainnav ul li.hovermenu").addClass("nohi");
	
	jQuery("#mainnav ul li.hovermenu:not(.nohi)").hover(function () {
		jQuery(this).addClass("ho");
		jQuery("div.pnav", this).show();
	}, function () {
		jQuery(this).removeClass("ho");
		jQuery("div.pnav", this).hide();
	}).each(function () {
		var w = jQuery("div.in", this).width();
		var h = jQuery("div.in", this).height();
		if (w > 1) jQuery("div.pnav", this).width(w + 2).hide().css("visibility", "visible");
		jQuery("ul", this).last().addClass("last");
		jQuery("ul", this).each(function () { jQuery(this).css("height", h); })
	});

	jQuery("#mainnav ul li.hovermenu:not(.nohi) ul").each(function () {
		jQuery("li span", this).first().addClass("first");
	});

	//	jQuery(jQuery("#mainnav ul li.hovermenu .pnav").get(3)).remove();
	//	jQuery(jQuery("#mainnav ul li.hovermenu .pnav").get(2)).remove();
	//	jQuery(jQuery("#mainnav ul li.hovermenu .pnav").get(1)).remove();

	//--http://www.appelsiini.net/projects/lazyload
	jQuery("img.lazy").lazyload({ effect: "fadeIn" });

});


jQuery.fn.hoverClass = function (c) {
	return this.each(function () {
		$(this).hover(
			function () { $(this).addClass(c); },
			function () { $(this).removeClass(c); }
		);
	});
};


function InitAll() {

	//--Add Searchbox Submit
	jQuery("#quicksearch .inputtext").bind("keydown", function (e) {
		var key;
		if (window.event)
			key = window.event.keyCode; //IE 
		else
			key = e.which; //firefox

		if (key == 13) {
			jQuery("#quicksearch input.submitsearch").click();
		}
		return (key != 13);
	});

};




function InitCategoryMouseover() {
	jQuery("ul.productlisting li a").each(function (e) {
		jQuery(this).bind("mouseenter", CategoryMouseOver);
		jQuery(this).bind("mouseleave", CategoryMouseOut);
	});
}

function CategoryMouseOver() {

	var imgs = jQuery("img.productimg", this);
	var spans = jQuery("span.productimg2", this);

	if (imgs.length == 1) {

		var w = imgs[0].width; //--Detect ImageSize

		//--Fetch new URL
		var span = spans[0];
		var url = jQuery(span).attr("rel").replace("-160/", "-###/").replace("-220/", "-###/").replace("-###/", "-" + w + "/")

		jQuery(imgs[0]).after("<img src='" + url + "' class='productimg productimg2' alt='' style='display:none' />");

		jQuery("img.productimg2", this).load(function (e) {
			jQuery(this).fadeIn().prev().animate({ opacity: 0.001 });
		});

	} else {
		jQuery("img.productimg2", this).fadeIn().prev().animate({ opacity: 0.001 });
	}


}


function CategoryMouseOut() {
	jQuery("img.productimg2", this).stop(true, true).prev().stop(true, true);
	jQuery("img.productimg2", this).fadeOut().prev().animate({ opacity: 1 });
}






function InitCountryChanger() {

	jQuery("#triggerCountry").click(function () {
		jQuery("#LangSwitch div.langs").toggle();
		return false;
	});

	jQuery("#triggerCountryOut").click(function () {
		jQuery("#LangSwitch div.langs").hide();
		return false;
	});

	jQuery("#LangSwitch div.langs").bind("mouseleave", function () {
		setTimeout(HideCountrySwitchReal, 500);
	});
}

function HideCountrySwitchReal() {
	jQuery("#LangSwitch div.langs").hide();
}



//Alle Links mit lang=p werden zu Popups
function UpdatePopupLinks() {
	jQuery("a[lang='p'],area[lang='p']").each(function () {
		jQuery(this).bind("click", function () {
			var url = jQuery(this).attr("href");

			var dim = jQuery(this).attr("rev");
			var dim2 = jQuery(this).attr("rel");

			if (dim == "") dim = dim2;

			var di = dim.split("|");

			var padding;
			(navigator.appName == "Microsoft Internet Explorer") ? (padding = 5) : (padding = 0);

			var screenw = screen.availWidth;
			var screenh = screen.availHeight;

			var winw = (parseInt(di[0]) + 15 + padding);
			var winh = (parseInt(di[1]) + 15 + padding);

			var posx = (screenw / 2) - (winw / 2);
			var posy = (screenh / 2) - (winh / 2);

			var p = "width=" + winw + ",height=" + winh + ",top=" + posy + ",left=" + posx + ",scrollbars=yes";

			if (jQuery(this).hasClass("PopupWithMenu")) {
				p = p + ",toolbar=yes,menubar=yes";
			}
			var win = window.open(url, "1", p);
			win.focus();

			return false;
		});
	});
}


var project = new function () {
	this.init = function () {
		//override this function in /skin/<Project>/Scripts.js
	};
};


//============================================================================
//	Popup-Window
//============================================================================
var Popup = new function () {
	this.defaultWidth = 750;
	this.defaultHeight = 600;
	this.defaultName = "popup";

	this.init = function () {
		$("a.wrpopup").each(function () { Popup.bind(this); });
	};
	this.bind = function (link) {
		$(link).bind("click", function () {
			var url = this.href;
			var lang = $("html").attr("lang");
			if (url.indexOf("/" + lang + "/") >= 0) {
				var split = url.split("/" + lang + "/");
				url = split[0] + "/popup/" + lang + "/" + split[1];
			}
			return Popup.open(url);
		});
	};
	this.open = function (link, name, width, height) {
		var n = (name ? name : this.defaultName);
		var w = (width ? width : this.defaultWidth);
		var h = (height ? height : this.defaultHeight);
		window.open(link, n, "width=" + w + ",height=" + h + ",location=no,menubar=no,toolbar=no,status=no,scrollbars=yes");
		return false;
	};
};
$(document).ready(function () { Popup.init(); });



//============================================================================
//	Karussel Teaser
//============================================================================
var KarusselLogic = new function () {
	this.slots = new Array();
	this.hasInitialized = false;

	this.init = function () {
		if (!this.hasInitialized) {
			this.hasInitialized = true;
			$(".teaser_karussell").each(function () { KarusselLogic.prepare(this); });
			$(".teaser_imagekarussell").each(function () { KarusselLogic.prepare(this); });
		}
	};

	this.prepare = function (teaser) {
		if (!KarusselLogic.slots[teaser.id]) {
			var id = "";
			if (teaser.id && teaser.id != "") {
				id = teaser.id;
			} else {
				id = "karussel" + Math.round(Math.random() * 10000);
				teaser.id = id;
			}
			this.slots[id] = new KarusselTeaser(id);
		}
	}

	this.back = function (link) {
		var id = $(link).parents(".teaser_karussell").attr("id");
		if (this.slots[id]) { this.slots[id].animateTeaser(1); }
	};

	this.next = function (link) {
		var id = $(link).parents(".teaser_karussell").attr("id");
		if (this.slots[id]) { this.slots[id].animateTeaser(-1); }
	};
};


var KarusselTeaser = function (id) {
	this.id = id;
	this.browser = $("#" + this.id + " .browser");
	this.list = $("#" + this.id + " .browser ul");
	this.entries = $("#" + this.id + " .browser li");
	this.entryWidth = this.entries.width();

	try {
		this.offset = parseInt(this.entries.css("margin-right").replace("px", ""));
	} catch (e) {
		this.offset = 5;
	}

	this.count = this.entries.length;
	this.delta = this.browser.width() - (this.count * (this.entryWidth + this.offset));
	this.step = this.entryWidth + this.offset;


	if (this.delta < 0) {
		this.navtable = $("<table><tr><td class=\"back\"><div style=\"display: none;\">" + Translator["back"] + "</div></td><td class=\"label\">" + Translator["ScollToSeeMore"] + "</td><td class=\"next\"><div>" + Translator["next"] + "</div></td>");
		this.browser.parent().prepend(this.navtable);

		this.backlink = $("#" + this.id + " .back div");
		this.backlink.bind("click", function () { KarusselLogic.back(this); });

		this.nextlink = $("#" + this.id + " .next div");
		this.nextlink.bind("click", function () { KarusselLogic.next(this); });
	}

	this.animateTeaser = function (direction) {
		var pos = this.list.position();
		var nextpos = pos.left + (this.step * direction);
		this.nextlink.show();
		this.backlink.show();
		if (nextpos > 0) {
			nextpos = 0;
			this.backlink.hide();
		} else if (nextpos < this.delta) {
			nextpos = this.delta;
			this.nextlink.hide();
		}
		this.list.animate({ left: nextpos + "px" }, "fast");
	};
};


//================================================================
//	Teaserrotator, animated switch between sibling teaser
//================================================================
var TeaserRotator = new function () {
	this.idprefix = "rotationstep";
	this.groupprefix = "g";
	this.teaserGroupCounter = 0;
	this.teaserSwitchTimeout = 8000;
	this.teaserAnimationTimeout = 300;
	this.Delay = 1000;

	this.init = function () {
		$(".teaserrotation img").bind("load", function () {
			TeaserRotator.syncHeight(this);
		});
		$(".rotcontainer").each(function () {

			var sibl = $(this).children(".teaserrotation");
			var height = 0;
			var width = 0;

			sibl.each(function (i) {
				if (i == 0) {
					TeaserRotator.teaserGroupCounter++;
					$(this).parent().css("position", "relative");
					$(this).show();
				} else {
					$(this).hide();
				}
				$(this).attr("id", TeaserRotator.idprefix + i + TeaserRotator.groupprefix + TeaserRotator.teaserGroupCounter);
				if ($(this).width() > width) { width = $(this).width(); }
				if ($(this).height() > height) { height = $(this).height(); }
				$(this).css("position", "absolute").css("top", "0px").css("left", "0px");
			});

			$(this).css("width", width);
			$(this).css("height", height);

			var firstid = jQuery(this).children()[0].id;
			var time = TeaserRotator.teaserSwitchTimeout + (Math.random() * TeaserRotator.Delay);
			setTimeout("TeaserRotator.cycle('" + firstid + "');", time);

		});
	};

	this.syncHeight = function (teaserimg) {
		var imgheight = jQuery(teaserimg).height();
		var rotator = jQuery(teaserimg).parent().parent();
		if (imgheight > rotator.height()) {
			rotator.css("height", imgheight);
		}
	};

	this.cycle = function (id) {
		var currentStep = (id.substring(12, id.lastIndexOf("g"))) * 1;
		var currentGroup = id.substring(id.lastIndexOf("g") + 1, id.length);
		var nextStep = 1 + currentStep;
		var nextid = "#" + this.idprefix + nextStep + this.groupprefix + currentGroup;
		if ($(nextid).length == 0) { nextStep = 0; }
		this.animate(id, this.idprefix + nextStep + this.groupprefix + currentGroup);
		setTimeout("TeaserRotator.cycle('" + this.idprefix + nextStep + this.groupprefix + currentGroup + "');", this.teaserSwitchTimeout + (Math.random() * TeaserRotator.Delay));
	};

	this.animate = function (currentId, nextId) {
		$("#" + currentId).css("z-index", 1);
		$("#" + nextId).css("z-index", 2).fadeIn(this.teaserAnimationTimeout);
		setTimeout("$('#" + currentId + "').hide()", this.teaserAnimationTimeout + 100);
	};

};




//================================================================
//	Adds "missr" to ParentParent of Validator 
//================================================================
var ErrorRowChecker = new function () {

	this.interval = null;
	this.failed = [];

	this.init = function () {
		if ($(".errormsg").length > 0) {
			this.interval = window.setInterval("ErrorRowChecker.check();", 300);
			ErrorRowChecker.check();
		} else {
			jQuery(".errorrow").hide();
		}
	}


	this.check = function () {

		var missing = $(".errormsg");

		/* Clean all Rows */
		for (var x = 0; x < missing.length; x++) {

			if (!jQuery(missing[x].parentNode).hasClass("missrmust")) {
				jQuery(missing[x].parentNode).removeClass("missr");
			} else {
				jQuery(missing[x].parentNode).addClass("missr");
			}
		}

		/* Find Validators */
		var Makered = new Array();
		for (var x = 0; x < missing.length; x++) {
			var id = jQuery(missing[x]).attr("id")//.replace(/2/g, "");
			if (jQuery(missing[x]).css("display") != "none") {
				if (!Array.contains(Makered, id)) {
					jQuery(missing[x].parentNode).addClass("missr");
					Array.add(Makered, id);
				}
			}
		}

		/* Show Summary */
		if (Makered.length == 0) {
			jQuery(".errorrow").fadeOut();
		} else {
			jQuery(".errorrow").fadeIn(); ;
		}


		/* Disable Handler, if no Validator on this Page */
		if ($(".errormsg").length == 0) {
			clearInterval(this.interval);
		}

	};

}




//================================================================
//	Tooltips
//	auf der Seite: jQuery(function() {ToolTipEngine.init();});
//================================================================

var ToolTipEngine = new function () {
	this.init = function () {

		jQuery(".tt").tooltip({
			position: 'top',
			tip: '#ttip',
			relative: false,
			opacity: 1,
			offset: [0, 50],
			events: {
				def: 'mouseover,mouseout'
			}
		});

		jQuery(".tt2").tooltip({
			position: 'top',
			tip: '#ttip',
			relative: false,
			opacity: 1,
			offset: [0, 150],
			events: {
				def: 'mouseover,mouseout'
			}
		});

	}
};



//============================================================================
//	ShowDialog(Caller, Title,BodyText,Callback function)
//============================================================================

function ShowDialog(Title, Body, OKText, CancelText, OKDelegate) {
	var diag = jQuery("#Dialog").html('<div class="noneu">' + Body + '</div>');

	diag.dialog({
		draggable: false,
		modal: true,
		title: "<strong>" + Title + "</strong>",
		dialogClass: 'ModalPopup Dialog',
		width: 600,
		height: 87,

		buttons: [
			{ text: OKText, click: function () { $(this).dialog("close"); OKDelegate() } },
			{ text: CancelText, click: function () { $(this).dialog("close") } }
		]

	});


}

function ShowDialogLogout(Title, Body, OKText, CancelText, OKDelegate, PostBackID) {
	var diag = jQuery("#Dialog").html('<div class="noneu">' + Body + '</div>');

	diag.dialog({
		draggable: false,
		modal: true,
		title: "<strong>" + Title + "</strong>",
		dialogClass: 'ModalPopup Dialog',
		width: 600,
		height: 87,

		buttons: [
			{ text: OKText, click: function () {
				$(this).dialog("close");
				if (PostBackID != "" && typeof __doPostBack == 'function') {
					__doPostBack(PostBackID, '');
				}
				OKDelegate;
			}
			},
			{ text: CancelText, click: function () { $(this).dialog("close"); } }
		]

	});

	jQuery("#Dialog").parent().appendTo(jQuery("form:first"));


}

function ShowMessage(Title, Body, OKText, OKDelegate, CancelText, CancelDelegate) {
	var $diag = jQuery("#Dialog").html('<div class="noneu">' + Body + '</div>');

	if (OKDelegate == undefined) {
		OKDelegate = function () { }
	}

	$diag.dialog({
		draggable: false,
		modal: true,
		title: "<strong>" + Title + "</strong>",
		dialogClass: 'ModalPopup',
		width: 600,
		height: 87,

		buttons: [{ text: OKText, click: function () { $(this).dialog("close"); if (OKDelegate == undefined) return; OKDelegate(); } }, ]
	});

	if (CancelText != undefined && CancelDelegate != undefined) {

		$diag.dialog({
			buttons: [
			    { text: OKText, click: function () { $(this).dialog("close"); if (OKDelegate == undefined) return; OKDelegate(); } },
                { text: CancelText, click: function () { if (CancelDelegate == undefined) return; CancelDelegate(); } }
		    ]

		});
	}
}



//============================================================================
//	VideoPlayer
//
//	LoadVideo("Video1","#VidroFrame","#VideoPlaceholder",640,380)
//============================================================================
function LoadVideo(Video, Placeholder, VideoContainer, VideoDiv, w, h, bg) {

//	Sys.Debug.trace("~~~~~~~~ LoadVideo ~~~~~~~~");
//	Sys.Debug.trace("Video: " + Video);
//	Sys.Debug.trace("Placeholder: " + Placeholder);
//	Sys.Debug.trace("VideoContainer: " + VideoContainer);
//	Sys.Debug.trace("VideoDiv: " + VideoDiv);
//	Sys.Debug.trace("w: " + w);
//	Sys.Debug.trace("h: " + h);
//	Sys.Debug.trace("~~~~~~~~~~~~~~~~~~~~~~~~~~~");

	jQuery("#" + Placeholder).css("cursor", "pointer").click(function () {

		jQuery("#" + VideoContainer).css("width", w).css("min-height", h).show();
		jQuery(this).hide();
		
		var sb = new Sys.StringBuilder();
		sb.append("<video id='movie5' width='" + w + "' height='" + h  + "' preload controls autoplay>");
		sb.append("<source src='/Stream/" + Video + ".webm' type='video/webm; codecs=\"vp8, vorbis\"' />");
		sb.append("<source src='/Stream/" + Video + ".ogv' type='video/ogg; codecs=\"theora, vorbis\"' />");
		sb.append("<source src='/Stream/" + Video + ".mp4' />");
		sb.append("<object id='fplay' width='" + w + "' height='" + h + "' type='application/x-shockwave-flash' data='/Scripts/flowplayer-3.2.7.swf'> ");
		sb.append("<param name='movie' value='/Scripts/flowplayer-3.2.7.swf' /> ");
		sb.append("<param name='allowfullscreen' value='true' /> ");
		sb.append("<param name='flashvars' value='config={\"clip\": {\"url\": \"/Stream/" + Video + ".mp4\", \"autoPlay\":true, \"autoBuffering\":true}}' /> ");
		sb.append("</object>");
		sb.append("</video>");

		jQuery("#" + VideoDiv).html(sb.toString());
		jQuery("#" + VideoContainer).show();

		jQuery("video").bind("ended", function () {
			jQuery("#" + Placeholder).show();
			jQuery("#" + VideoContainer).hide();
			jQuery("#" + VideoDiv).html("");
			return false;
		});
				
		return false;
	});
}

//--For Silverlight
function VideoEnded(Container, Trigger) {
	jQuery("#" + Trigger).show();
	jQuery("#" + Container).hide();
	jQuery("#" + Container + " div").html("");
}





