/* Global variables */
var categoryName = "";
var xpackStyles = [];
var kalRequestURL = "";
var webRoot = "";

/**
 * layerController
 * Handles communication between ui and data model
 */
var layerController = {
	kalRequest: null,
	currentStyle: null,
	
	// Hook on opening the powerlayer
	onOpen: function(style) {
		layerController.currentStyle = style;
		
		// if style has colors, activate the first one
		if (style.colors.length() > 0) {
			style.activeColor = style.colors.elementAt(0);
			// hack: simulate mouseover and click on first color icon
			highlightMiniColor('mc0', 'mca0', 'on',webRoot);
			var initFirstArticleNo = style.variations[0].SKU.split("-")[0];			
			handleColorChoosing('mc0', 'mca0', style.activeColor, 0, "",initFirstArticleNo, layerController.currentStyle);			
		}
		
		if (layerController.currentStyle.hasKalUpdates) {
			// availability information already up to date
			layerController.updateSizeTable();
		} else {
			// initiate KAL request
			layerController.kalRequest = new KalRequest();
			layerController.kalRequest.initiate(layerController, kalRequestURL, style.toKalRequest());
			jQuery("#viewport").html("<b>Lieferbarkeit wird ermittelt &hellip;</b>");
		}
	},
	
	// Hook on closing the powerlayer
	onClose: function() {
		layerController.kalRequest.cancel();
		layerController.currentStyle = null;
	},
	
	// Event handler for a successful KAL request
	onKalSuccess: function(xml) {
		if (layerController.currentStyle) {
			layerController.currentStyle.hasKalUpdates = true;
			
			if (layerController.currentStyle.variations.length > 0) {
				// update availability for each product variation
				for (var i = 0; i < layerController.currentStyle.variations.length; i++) {
					layerController.currentStyle.variations[i].availability = getDeliveryDesignation(xml, layerController.currentStyle.variations[i].SKU);
				}
			} else {
				// update availability information for style
				layerController.currentStyle.availability = getDeliveryDesignation(xml, layerController.currentStyle.SKU);
			}
			
			layerController.updateSizeTable();
		}
	},
	
	// Error handler for a KAL request
	onKalError: function() {
		// redisplay MMDB information
		layerController.updateSizeTable();
	},
	
	// Redraws the size table
	updateSizeTable: function() {
		var style = layerController.currentStyle;
		if (style.colors.length() > 0) {
			// hack: if a color isn't chosen yet, activeColor will be null
			if (style.activeColor) {
				var sizeTable = new SizeTable();
				sizeTable.initWithVariationList(style.getVariationsByColor(style.activeColor));
				jQuery("#viewport").html(sizeTable.toHTML());
			} else {
				// clear viewport
				jQuery("#viewport").html("");
			}
		} else {
			var sizeTable = new SizeTable();
			sizeTable.initWithVariationList(style.getVariationsByColor(null));
			jQuery("#viewport").html(sizeTable.toHTML());
			jQuery("#textColor").css("display", "none");
		}
	}
};

function goPageKeyEvent(keyEvent, x, aktuell, ende) { 		
	if (keyEvent.keyCode && keyEvent.keyCode==13) {
		goPage(x, aktuell, ende);
	}
}

function closePowerlayer() {
	removeBackgroundIFrame();
	layerController.onClose();
	
	if (document.getElementById("powerlayer"))
		document.getElementById("powerlayer").style.visibility = "hidden";
	
	$(".styleimage").mouseover(activateQuicklook);
}

function openPowerlayer(sku) {

	$(".styleimage").unbind('mouseover');

	var currentpowerLayer = document.getElementById("powerlayer");
	if (currentpowerLayer) {
		
		// Reset variable fields
		$("#viewport").html("");
		$("#colorName").html("");
		
		// initialize power layer with data from styleNo and display it
		var index = getStyleBySKU(sku);
		//alert(sku);
		if(index >= 0){
			//Show Minicolor-Table
			var currentStyle = xpackStyles[index];
			var articleMappingSet = new Set();
			var wbroot = webRoot+"/imagesOnline/xpack/";
			var tempString = "";
			
			
			
			for(var i=0; i< currentStyle.variations.length; i++){				
				if((currentStyle.variations[i].searchColor != null) && (currentStyle.variations[i].color != null)){
					articleMappingSet.add(currentStyle.variations[i].searchColor +"|"+currentStyle.variations[i].color +"|"+currentStyle.getArticleNoByColors(currentStyle.variations[i].color));
				}
			}
			
			
			
			//Article with Colors: 
			if(articleMappingSet.length() != 0){
				tempString += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
				tempString += "<tr><td class=\"quicklooktitle\" valign=\"top\">Farbe ausw&auml;hlen</td></tr>";
				tempString += "<tr><td><img src=\""+webRoot+"/imagesOnline/xpack/colorchoosertop.gif\"></td></tr>";
				tempString += "<tr><td class=\"minicolortd\" align=\"center\">";
				tempString += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr height=\"26\">";
				
				for(var i=0; i< articleMappingSet.length(); i++){
					
					if(articleMappingSet.elementAt(i) != null){
						
						var currentColor 	= (articleMappingSet.elementAt(i).split("|"))[0];						
						var currentColorTitle   = (articleMappingSet.elementAt(i).split("|"))[1];
						var currentArticleNo 	= (articleMappingSet.elementAt(i).split("|"))[2];
						
						
						//ToDo: zu einem Color richtige SKU zuweisen ...
						tempString += "<td width=\"19\"><div class=\"minicolor\" id=\"mc"+i+"\"><img title=\""+currentColorTitle+"\"  class=\"minicolorimg\" src=\""+ wbroot+ getSearchColor(currentColor, "klein")+"\" onclick=\"handleColorChoosing('mc"+i+"', 'mca"+i+"', '"+currentColorTitle+"',"+index+" , '"+wbroot+"', '"+currentArticleNo+"', layerController.currentStyle);\" onmouseover=\"highlightMiniColor('mc"+i+"', 'mca"+i+"', 'on', '"+wbroot+"');\" onmouseout=\"highlightMiniColor('mc"+i+"', 'mca"+i+"', 'off', '"+wbroot+"')\"><img id=\"mca"+i+"\" src=\""+wbroot+"leer.gif\"></div></td>";
						
						if((i==(articleMappingSet.length()-1)) && ((i+1)%5==0)){}
						else if((i+1)%5==0){
							tempString += "</tr><tr height=\"26\">";
						}				
						else{}
						if((i==(articleMappingSet.length()-1)) && ((i+1)%5==1)){
							tempString += "<td width=\"19\"></td><td width=\"19\"></td><td width=\"19\"></td><td width=\"19\"></td>";				
						}
						if((i==(articleMappingSet.length()-1)) && ((i+1)%5==2)){
							tempString += "<td width=\"19\"></td><td width=\"19\"></td><td width=\"19\"></td>";				
						}
						if((i==(articleMappingSet.length()-1)) && ((i+1)%5==3)){
							tempString += "<td width=\"19\"></td><td width=\"19\"></td>";				
						}
						if((i==(articleMappingSet.length()-1)) && ((i+1)%5==4)){
							tempString += "<td width=\"19\"></td>";				
						}
					}
					
					
				}
				tempString += "</tr></table>";				
				tempString += "</td></tr>";
				tempString += "<tr><td><img src=\""+webRoot+"/imagesOnline/xpack/colorchooserbottom.gif\" width=\"111\"></td></tr>";
				tempString += "</table>";
				document.getElementById("textColor").style.display = "block";								
			}
			else{
				//Article without Colors: 
				document.getElementById('orderbutton').style.marginLeft = "0px";
				var sizeTable = new SizeTable();
				sizeTable.initWithVariationList(currentStyle.getVariationsByColor(null));	
				document.getElementById("viewport").innerHTML = sizeTable.toHTML();
				document.getElementById("textColor").style.display = "none";
			}
			document.getElementById("minicolorcell").innerHTML = tempString;			
			
			
			//Show Materials-Table
			if(currentStyle.materialFlags.length() != 0){
				tempString1 = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
				tempString1 += "<tr><td class=\"quicklooktitle\" valign=\"top\" colspan=\"2\">Material</td></tr>";
				for(var i=0; i< currentStyle.materialFlags.length(); i++){
					tempString1 += "<tr><td class=\"materialtd\"><img src=\""+webRoot+"/imagesOnline/detailview/"+getMaterialImageMapping(currentStyle.materialFlags.elementAt(i))+"\"></td><td class=\"materialdiv\">"+getMaterialTextMapping(currentStyle.materialFlags.elementAt(i))+"</td></tr>";
					
				}	
				tempString1 += "</table>";
				document.getElementById("materialcell").innerHTML = tempString1;
				
			}
			else{
				document.getElementById("materialcell").innerHTML = "";
			}
			
			// Create link to detailview
			$("#orderbutton").unbind('click');
			$("#orderbutton").click(function(){ document.location.href =  currentStyle.URL; });
			$("#orderbutton").css("cursor", "pointer");

			
			// adjust position
			var interpolatedTop = findPosY(currentpowerLayer.offsetHeight);
			if (interpolatedTop < 205)
				interpolatedTop = 205;
			currentpowerLayer.style.top = interpolatedTop + "px";
			currentpowerLayer.style.left = positionMapping[index % 3];
			
			//timeScroll = window.setTimeout("setScrollButtonPositions()", 15);
			
			// hook layerController
			layerController.onOpen(currentStyle);
			
			
			
			//BugFix SelectBoxes: display backgroundIFrame for IE6			
			if(typeof currentpowerLayer.style.setAttribute != 'undefined'){
				//IE
				currentpowerLayer.style.setAttribute("height" , "472px", false);
				createBackgroundIFrame(currentpowerLayer.style.top, currentpowerLayer.style.left, currentpowerLayer.offsetWidth, currentpowerLayer.style.height);	
			}
			else{
				//FF
				createBackgroundIFrame(currentpowerLayer.style.top, currentpowerLayer.style.left, currentpowerLayer.offsetWidth, currentpowerLayer.offsetHeight);
			}
			
			
			
			
			// display powerlayer and fire landmark
			currentpowerLayer.style.visibility = "visible";
			setLandmark("page", "&pc=sh_xpack_lieferauskunft_" + categoryName);

		}		
	}
}


function setScrollButtonPositions(){
	
	// adjust scrollbuttons
	var viewportDiv = document.getElementById("viewport");
	var viewportTop = viewportDiv.offsetTop;
	var viewportLeft = viewportDiv.offsetLeft;
	var tempElement = viewportDiv.offsetParent;
	
	//alert(viewportTop);
	
	while (tempElement && tempElement.id != "powerlayer") {
		viewportTop += tempElement.offsetTop;
		viewportLeft += tempElement.offsetLeft;
		tempElement = tempElement.offsetParent;
	}
	
	var scrollupButton = document.getElementById("scrollup");
	scrollupButton.style.top = viewportTop - scrollupButton.offsetHeight + "px";
	scrollupButton.style.left = viewportLeft + (viewportDiv.offsetWidth / 2) - (scrollupButton.offsetWidth / 2) + "px";
	
	var scrolldownButton = document.getElementById("scrolldown");
	scrolldownButton.style.top = viewportTop + viewportDiv.offsetHeight;
	scrolldownButton.style.left = scrollupButton.style.left;
	
	var scrollleftButton = document.getElementById("scrollleft");
	scrollleftButton.style.top = viewportTop + (viewportDiv.offsetHeight / 2) - (scrollleftButton.offsetHeight / 2) + "px";
	scrollleftButton.style.left = viewportLeft - scrollleftButton.offsetWidth + "px";

	var scrollrightButton = document.getElementById("scrollright");
	scrollrightButton.style.top = scrollleftButton.style.top;
	scrollrightButton.style.left = viewportLeft + viewportDiv.offsetWidth + "px";	
}




function getStyleBySKU(sku){
	for(var i=0; i< xpackStyles.length; i++){		
		if(xpackStyles[i].SKU == sku){
			return i;	
		}
	}
	return -1;
}



/* Behaviour */
$(document).ready(function(){
	// Add mouse-over handlers
	$(".styleimage").mouseover(activateQuicklook);
	$(".styleimage").mouseout(deactivateQuicklook);
	$("#quicklook").mouseover(function() {
		$("#quicklook").get(0).src = webRoot + "/imagesOnline/xpack/schnellauskunft_aktiv.gif";
		$("#quicklook").css("visibility", "visible");
	});
	$("#quicklook").mouseout(function() {
		$("#quicklook").get(0).src = webRoot + "/imagesOnline/xpack/schnellauskunft_passiv.gif";
		$("#quicklook").css("visibility", "hidden");
	});
});

/*
 * Activates quicklook
 */
function activateQuicklook(event) {

	$(".styleimage").css("border", "0");
	$("#quicklook").css("visibility", "hidden");

	var position = findPosition(this);
	var xpos = position[0] + this.offsetWidth / 2 - $("#quicklook").width() / 2;
	var ypos = position[1] + this.offsetHeight / 2 - $("#quicklook").height() / 2;
	this.style.border = "1px solid orange";
	var sku = this.parentNode;

	while ((sku.className != "cell") && sku.parentNode) {
		sku = sku.parentNode;
	}
	
	$("#quicklook").css("left", xpos + "px");
	$("#quicklook").css("top", ypos + "px");
	$("#quicklook").unbind('click');
	$("#quicklook").click(function(){ openPowerlayer(sku.id); });
	$("#quicklook").css("visibility", "visible");
}

/*
 * Deactivates quicklook
 */
function deactivateQuicklook(event) {
	//$("#quicklook").css("visibility", "hidden");
}

/*
 * Returns the absolute position of an element
 */
function findPosition(obj) {
	var xpos = obj.offsetLeft;
	var ypos = obj.offsetTop;
	
	while (obj.offsetParent) {
		obj = obj.offsetParent;
		xpos += obj.offsetLeft;
		ypos += obj.offsetTop;
	}
	
	return [xpos, ypos];
}

/**
 * Determine delivery designation by sku from an AJAX XML response
 */
function getDeliveryDesignation(xml, sku) {
		var splitSKU = sku.split("-");
		//var articleNo = splitSKU[0].substr(0, 6);
		var articleNo = splitSKU[0];
		var size = splitSKU[1];
		var allArticles = xml.getElementsByTagName('Article');

		try {
			for (var i = 0; i < allArticles.length; i++) {
				var itemNo = allArticles[i].getElementsByTagName("CompleteCatalogItemNo")[0].childNodes[0].nodeValue;
				var itemSize = allArticles[i].getElementsByTagName("SizeAlphaText")[0].childNodes[0].nodeValue;
				if (articleNo == itemNo && size == itemSize) {
					var designationString = allArticles[i].getElementsByTagName("DeliveryDesignation")[0].childNodes[0].nodeValue;
					return parseInt(designationString);
				}
			}
		} catch (err) {
			return null;
		}
}

/* Look-up table for powerlayer position */
var positionMapping = [];
positionMapping[0] = "436px";
positionMapping[1] = "0px";
positionMapping[2] = "295px";


function createBackgroundIFrame(iframeTop, iframeLeft, iframeWidth, iframeHeight){

	var backgroundIFrame = document.createElement("IFRAME");
	backgroundIFrame.setAttribute("src", "");
	backgroundIFrame.setAttribute( "id", "backgroundIFrame" );
	backgroundIFrame.style.position="absolute";
	backgroundIFrame.style.zIndex="0";
	backgroundIFrame.style.top = iframeTop;
	backgroundIFrame.style.left = iframeLeft;	
	backgroundIFrame.style.width = iframeWidth;
	backgroundIFrame.style.height = iframeHeight;
	backgroundIFrame.style.border = 0;
	
	document.body.appendChild(backgroundIFrame);	

}

function removeBackgroundIFrame(){
	var backgroundIFrame = document.getElementById("backgroundIFrame");
	if(backgroundIFrame){
		document.body.removeChild(backgroundIFrame);
	}

}

var currentVideo = '';
function showVideoLayer(videoName){	
	currentVideo = videoName;
	var videoServer = "http://video.heine.de";
	document.getElementById("imagesVideoLayer").style.zIndex = 600002;	
	if(document.getElementById("videoFlashPlayer")){
		setLandmark("page","&pc=sh_xpack_video"); 
		document.getElementById("imagesVideoLayer").style.visibility = "visible";		
		var videopfad = videoServer+"/shopmovies/einzelvideos/"+videoName;
		var so = new SWFObject("/is-bin/intershop.static/WFS/Heine-HeineDe-Site/-/de_DE/imagesOnline/_storefront/videoContainer.swf", "headline", "320", "430", "8", "", "noscale");
		so.addParam("flashvars", "file="+videopfad+"&originalSizes=false&soundButton=true");
		so.addParam("allowScriptAccess","always");
		so.addParam("wmode", "transparent");
		so.addParam("loop", "false");
		so.write("videoFlashPlayer");
	}
	setVideoLayerPosition();
	document.getElementById("imagesVideoLayer").style.display = 'block';
	document.getElementById("imagesVideoLayer").style.visibility = 'visible';
	
}

function playVideoAgain(){
	showVideoLayer(currentVideo);
}

function setVideoLayerPosition(){
	var x, y;
	var layer_popup = document.getElementById('imagesVideoLayer');
	
	x = findPosX(640) + 'px';
	y = findPosY(550) + 'px';
	
	layer_popup.style.top = y;
	layer_popup.style.left = x;
	layer_popup.style.visibility = 'visible';
	
}
