var curH = 0;
var h = 0;
var change = 0;

var dropDiv = null;
var interval = null;

var currentSlideDrop = null;
var currentSlideDropInner = null;

function slideDrop(dropId, dropInnerId)
{
	dropDiv = document.getElementById(dropId);
	dropInnerDiv = document.getElementById(dropInnerId);
	if(dropDiv.style.visibility == "visible")
	{
		var slider = new Slider();
		slider.slideOut(dropDiv, dropInnerDiv);
		currentSlideDrop = null;
		currentSlideDropInner = null;
	}
	else
	{
		if(currentSlideDrop != null)
		{
			var slider = new Slider();
			slider.slideOut(currentSlideDrop, currentSlideDropInner);
		}
		var slider = new Slider();
		slider.slideIn(dropDiv, dropInnerDiv);
		currentSlideDrop = dropDiv;
		currentSlideDropInner = dropInnerDiv;
	}
}

function closeDrop(dropId, dropInnerId)
{
	dropDiv = document.getElementById(dropId);
	dropInnerDiv = document.getElementById(dropInnerId);
	if(dropDiv)
	{
		dropDiv.style.visibility = "hidden";
	}
}

function fadeDrop(dropId)
{
	dropDiv = document.getElementById(dropId);
	if(dropDiv.style.visibility == "visible")
	{
		var fader = new Fader();
		fader.fadeOut(dropDiv);
	}
	else
	{
		var fader = new Fader();
		fader.fadeIn(dropDiv);
	}
}


function doPopOpen()
{
	if(h >= 10)
	{
		window.clearInterval(interval);
		dropDiv.style.height = "auto";
		var height = dropDiv.clientHeight;
		
		return;
	}
	h++;
	var inc = h;
	dropDiv.style.height = curH + inc + "px";
	curH = curH + inc;
}


function showErrorFieldInfo(fieldId)
{
	if(document.getElementById(fieldId))
	{
		document.getElementById(fieldId).style.display = "block";
	}
}

function hideErrorFieldInfo(fieldId)
{
	if(document.getElementById(fieldId))
	{
		document.getElementById(fieldId).style.display = "none";
	}
}

/**
 * Opens the article price info dialog.
 *
 */
function openArticleWindow(_evt, _eventSource, _articleNum, _url)
{
	if(!document.getElementById('articleWindow'))
	{
		PopupWindow.open(_evt, 'loginWindow', _eventSource);
		return false;
	}
	
	var log = LogFactory.getLog('OPO');
	
	// set to loading
	articleDataLoading();
	
	log.info("Opening windows; event source: " + _eventSource);
	
	// move element to body, to can move the layer over the sidebar etc.
	var articlewindow = document.getElementById('articleWindow');
	articlewindow.parentNode.removeChild(articlewindow);
	document.body.appendChild(articlewindow); 
	
	// move element to body, to can move the layer over the sidebar etc.
	var consignmentWindow = document.getElementById('consignmentWindow');
	consignmentWindow.parentNode.removeChild(consignmentWindow);
	document.body.appendChild(consignmentWindow); 
	
	// move element to body, to can move the layer over the sidebar etc.
	var basketWindow = document.getElementById('basketWindow');
	basketWindow.parentNode.removeChild(basketWindow);
	document.body.appendChild(basketWindow); 
	
	PopupWindow.open(_evt, 'articleWindow', null, 185, 300);
	PopupWindow.positionRightOf('consignmentWindow', 'articleWindow');
	PopupWindow.positionRightOf('basketWindow', 'articleWindow');
	
	// new handling of ajax calls without dojo.
	log.info("Prepare request; " + _url);
	
	var url = _url;
	var callback = function() { articleLoadingComplete(); };
	var get = submitURL(url, "articleData", callback);
	
	log.info("Result of async request: " + get);
	return get;
	
	/*
	document.getElementById("salesItemNo").value = _articleNum;
	document.getElementById("salesItemQuantity").value = "";

	// connect dojo postloading to set focus on quantity input field
	dojo.event.connect("around", tapestry, "loadContent", this, "articleLoadingComplete");
	
	tapestry.form.submitAsync("salesItemForm", null, null, true);
	return false;
	*/
}

/**
 * Shows "loading indicator" / hides data container
 */
function articleDataLoading()
{
	var loading = document.getElementById("salesItemDataLoading");
	document.getElementById("articleData").innerHTML = loading.innerHTML;
	// loading.style.display = "block";
}

/**
 * Shows "loading indicator" / hides data container
 */
function conditionsDataLoading()
{
	var loading = document.getElementById("conditionsDataLoading");
	document.getElementById("conditionsData").innerHTML = loading.innerHTML;
}


// registered pos quantity field id
var positionQuantityFieldId = null;

/**
 * Open price info dialog from basket
 */
function openPositionWindow(_evt, _eventSource, _artNum, _artNumFieldId, _quantityFieldId, _top, _left)
{
	// set to loading
	articleDataLoading();

	// calculate top and left.
	PopupWindow.open(_evt, 'positionWindow', null, _top, _left);
	
	// set article num if provided
	if(_artNum == null)
	{
		_artNum = FormUtil.getFieldValue(_artNumFieldId);
	}
	
	var quantity = FormUtil.getFieldValue(_quantityFieldId);
	
	// store field id
	positionQuantityFieldId = _quantityFieldId;
	
	// new handling of ajax calls without dojo.
	var url = _eventSource.href + "?number=" + _artNum + "&quantity=" + quantity + "&simpleMode=true";
	var callback = function() { articleLoadingComplete(); };
	return submitURL(url, "articleData", callback);

	/*
	document.getElementById("salesItemNo").value = _artNum;
	document.getElementById("salesItemQuantity").value = quantity;
	
	
	// connect dojo postloading to set focus on quantity input field
	dojo.event.connect("around", tapestry, "loadContent", this, "articleLoadingComplete");

	tapestry.form.submitAsync("salesItemForm", null, null, true);
	return false;
	*/
}

/**
 * Open conditions info dialog from basket
 */
function openConditionsWindow(_evt, _eventSource, _top, _left)
{
	// set to loading
	conditionsDataLoading();

	PopupWindow.open(_evt, 'conditionsWindow', null, _top, _left);
	
	// new handling of ajax calls without dojo.
	var url = _eventSource.href;
	var callback = function() { conditionsLoadingComplete(); };
	return submitURL(url, "conditionsData", callback);

}

/**
 * Close the price info dialog in basket and apply quantity
 */
function applyPositionQuantity()
{
	var inputField = document.getElementById("salesItemQuantity");
	var inputValue = inputField.value;
	var posField = document.getElementById(positionQuantityFieldId);
	posField.value = inputValue;
	closePositionWindow();
}

/**
 *
 */
function closePositionWindow()
{
	// close window
	PopupWindow.close('positionWindow');
	// clear article data contents
	document.getElementById("articleData").innerHTML = "";
	
	// document.getElementById("salesItemNo").value = "";
	// tapestry.form.submitAsync("salesItemForm", null, null, false);
}

/**
* Close the conditions info popup
*/
function closeConditionsWindow()
{
	// close window
	PopupWindow.close('conditionsWindow');
	// clear conditions data contents
	document.getElementById("conditionsData").innerHTML = "";
}

/**
* Close the message info popup
*/
function closeMessageWindow()
{
	// close window
	PopupWindow.close('messageWindow');
	// clear message data contents
	document.getElementById("messageDataContainer").innerHTML = "";
}

/**
 * Update.
 * 
 * @return
 */
function updateArticleData(_form, _eventSource)
{
	FormUtil.disableControls('salesItemForm');
	var callback = function() { articleLoadingComplete(); };
	return submitForm(_form, 'articleData', _eventSource, callback);
}

/**
 * Article loading complete
 */
function articleLoadingComplete()
{
	var elems = document.getElementById("salesItemForm").elements;
	if(elems["salesItemQuantity"])
	{
		elems["salesItemQuantity"].focus();
		// funny simple workaround - call select() twice; IE ignores first call
		elems["salesItemQuantity"].focus();
	}
}

/**
 * Conditions loading complete
 */
function conditionsLoadingComplete()
{
	var cond = document.getElementById("paymentCond1");
	if(cond)
	{
		//do nothing
	}
}

/**
 * Close article window
 */
function closeArticleWindow()
{
	document.getElementById("articleData").innerHTML = "";
	// document.getElementById("salesItemNo").value = "";
	FormUtil.enableControls("salesItemForm");
	// tapestry.form.submitAsync("salesItemForm", null, null, false);
	PopupWindow.close('basketWindow');
	PopupWindow.close('consignmentWindow');
	PopupWindow.close('articleWindow');
}

PopupWindow.positionRightOf = function(_windowId, _refWindowId)
{
	var popup = document.getElementById(_windowId);
	var refwin = document.getElementById(_refWindowId);
	// only continue when both windows exist
	if(popup && refwin)
	{
		var cleft = refwin.offsetLeft;
		var ctop = refwin.offsetTop;
		var cwidth = refwin.clientWidth;
		popup.style.left = (cleft + cwidth + 1) + "px";
		popup.style.top = ctop + "px";
	}
}

/**
 * Handles closing of article window when "commit" is selected.
 */
function handleArticleWindowCommit()
{
	// check if can close (new consignment/no input wont validate)
	var cbConsNew = document.getElementById("checkCreateConsignment");
	if(cbConsNew.checked)
	{
		var tfConsName = document.getElementById("tfConsignmentName");
		var consName = tfConsName.value;
		if(consName && consName.length > 0)
		{
			PopupWindow.close("articleWindow");
		}
		// can't close.
	}
	else
	{
		// no new consignment; allways close
		// PopupWindow.close("articleWindow");
	}
}

function handleArticleFormCommit(_form, _submit)
{
	
	
	// no new consignment; always close
	var submitResult = submitForm(_form, 'funcbarBasketBox', _submit);
	var cbConsNew = document.getElementById("checkCreateConsignment");
	if(cbConsNew.checked)
	{
		var tfConsName = document.getElementById("tfConsignmentName");
		var consName = tfConsName.value;
		if(!consName || consName.length == 0)
		{
			return submitForm(_form, 'articleData', _submit);
		}
	}
	
	if(submitResult == false)
	{
		document.getElementById('articleData').innerHTML = "";
		PopupWindow.close("articleWindow");
	}
		
	if (typeof(_serviceName) == "undefined" || null == _serviceName || _serviceName != 'leavescatalog')
	{
		
	}
	else
	{
		if(_serviceName == 'leavescatalog')
		{
			self.close();
		}
	}
	
	return submitResult;
	
}


function openConsignmentWindow(_evt, _eventSource)
{
	FormUtil.disableControls("salesItemForm");
	if(!document.getElementById('consignmentWindow'))
	{
		return false;
	}
	PopupWindow.positionRightOf('consignmentWindow', 'articleWindow');
	PopupWindow.open(_evt, 'consignmentWindow', null);
	PopupWindow.close('basketWindow');
	return false;
}

function closeConsignmentWindow()
{
	PopupWindow.close('consignmentWindow');
	FormUtil.enableControls("salesItemForm");
	tapestry.form.submitAsync("salesItemForm", null, null, false);
	tapestry.form.submitAsync("resetConsignmentDataForm", null, null, false);
}

function openBasketWindow(_evt, _eventSource)
{
	FormUtil.disableControls("salesItemForm");
	if(!document.getElementById('basketWindow'))
	{
		return false;
	}
	PopupWindow.positionRightOf('basketWindow', 'articleWindow');
	PopupWindow.open(_evt, 'basketWindow', null);
	PopupWindow.close('consignmentWindow');
	return false;
}


function closeBasketWindow()
{
	PopupWindow.close('basketWindow');
	FormUtil.enableControls("salesItemForm");
	tapestry.form.submitAsync("salesItemForm", null, null, false);
	tapestry.form.submitAsync("resetBasketDataForm", null, null, false);
}


function addCatalogReference(_evt)
{
	tapestry.form.submitAsync("catalogRefForm", null, null, false);
	/* PopupWindow.open(_evt, 'messageWindow');*/
}

function toggleAddressOverride(_cb)
{
	var defAddress = document.getElementById("defaultDeliveryAddress");
	var ovrAddress = document.getElementById("overrideDeliveryAddress");
	if(_cb.checked)
	{
		defAddress.style.display = "none";
		ovrAddress.style.display = "block";
	}
	else
	{
		defAddress.style.display = "block";
		ovrAddress.style.display = "none";
		var custNrField = document.getElementById("addressId");
		custNrField.value="";
	}
}

/**
 * Toggles between selection of managed consignments and input field for new
 * consignment creation
 */
function toggleConsignmentSelect(_cb)
{
	var csSelect = document.getElementById("selectConsignment");
	var csSelectDropdown = document.getElementById("PropertySelection");
	var csCreate = document.getElementById("createConsignment");
	var csCreateTextField = document.getElementById("tfConsignmentName");
	if(_cb.checked)
	{
		csSelect.style.display = "none";
		csSelectDropdown.disabled = true;
		csCreate.style.display = "inline";
		csCreateTextField.disabled = false;
		
		csCreateTextField.focus();
	}
	else
	{
		csSelect.style.display = "inline";
		csSelectDropdown.disabled = false;
		csCreate.style.display = "none";
		csCreateTextField.disabled = true;
	}
	
	
}

/**
 * Toggles between selection of managed consignments and input field for new
 * consignment creation
 */
function toggleConsignmentSelect2(_cb)
{
	var condId = _cb.id;
	var csSelect = document.getElementById(condId.replace(/cb/, "ps"));
	var csCreate = document.getElementById(condId.replace(/cb/, "tx"));
	var csCreateTextField = document.getElementById(condId.replace(/cb/, "tf"));
	var orderSubmit = document.getElementById("orderSubmit");
	
	
	if(_cb.checked)
	{
		csSelect.style.display = "none";
		csSelect.disabled = true;
		csSelect.value=" ";
		csCreate.style.display = "inline";
		csCreateTextField.disabled = false;
		orderSubmit.style.display = "none";
		
		csCreateTextField.focus();
	}
	else
	{
		csSelect.style.display = "inline";
		csSelect.disabled = false;
		csCreate.style.display = "none";
		csCreateTextField.disabled = true;
		orderSubmit.style.display = "inline";
	}
}

// MIC: Does'n work in leavescatalog (Blaetterkatalog)
//function close()
//{
//}

function toggleDisplay(_elementId)
{
	var element = document.getElementById(_elementId);
	if(element.style.display == "none")
	{
		element.style.display = "block";
	}
	else
	{
		element.style.display = "none";
	}
}

function labelsSelectAll(cbMark)
{
	var frmElems = cbMark.form.elements;
	var markAll = cbMark.checked;
	for(var i = 0; i < frmElems.length; i++)
	{
		var elem = frmElems[i];
		if(elem.type == 'checkbox' && elem.id.substring(0,6) == 'cbItem')
		{
			elem.checked = markAll;
		}
	}
	
}

function FormUtil()
{
}

FormUtil.enableControls = function(formId)
{
	FormUtil.toggleControls(formId, false);
}

FormUtil.disableControls = function(formId)
{
	FormUtil.toggleControls(formId, true);
}

FormUtil.toggleControls = function(formId, disable)
{
	var frm = document.getElementById(formId);
	if(frm)
	{
		for(var i = 0; i < frm.elements.length; i++)
		{
			var elem = frm.elements[i];
			elem.disabled = disable;
		}
	}
}

FormUtil.setFieldFocus = function(fieldId)
{
	var field = document.getElementById(fieldId);
	if(field)
	{
		field.focus();
	}
}

FormUtil.getFieldValue = function(fieldId)
{
	var frmElem = document.getElementById(fieldId);
	if(frmElem)
	{
		return frmElem.value;
	}
	return null;
}

/**
 * Toggle to next / previous form field in group of text input fields.
 */
FormUtil.toggleMultiline = function(ev, fieldId, nextFieldId, prevFieldId)
{
	window.status = "keypress";
	var curInput = document.getElementById(fieldId);
	
	if(!ev)
	{
		ev = window.event;
	}
	
	var val = curInput.value;
	window.status = "value: " + val + " [length=" + val.length + "]";
	
	var keyCode = (ev.charCode ? ev.charCode : ev.keyCode);
	
	window.status = "keycode: " + keyCode;

	if(val.length == curInput.getAttribute("maxLength"))
	{
		if(!keyCode || keyCode == 9)
		{
			return;
		}
		if(!nextFieldId)
		{
			return;
		}
		var nextInput = document.getElementById(nextFieldId);
		if(nextInput.value == "")
		{
			if(navigator.userAgent.toLowerCase().indexOf("gecko") > -1)
			{
				nextInput.value = String.fromCharCode(keyCode);
			}
		}
		window.status = "switch to next";
		nextInput.focus();
	}
	if(val.length == 1)
	{
		if(keyCode == 8)
		{
			if(!prevFieldId)
			{
				return;
			}
			var prevInput = document.getElementById(prevFieldId);
			prevInput.focus();
		}
	}
}

/** 
 * Zoom Image Popup open / close 
 */

function ZoomImage()
{
}

// reference to currently opened window
ZoomImage.currentWindow = null;

// open zoom image popup
ZoomImage.open = function(windowUrl, imgUrl, label, page)
{
	ZoomImage.close();
	var re = /\+/g
	imgUrl = imgUrl.replace(re,"%2B");
	label = escape(label);
	var zoomUrl = windowUrl + "?image=" + imgUrl + "&label=" + label + "&pagenr=" + page;
	var zw = window.open(zoomUrl, "zoomImage", "width=497,height=542,menubar=yes,location=yes,resizable=no,scrollbars=no,status=no");
	
	if(zw.innerHeight == 542)
	{
		// innerHeight OK, nothing to do
	} else {
		// innerHeight not OK (probably IE), resizing Window
		zw.resizeBy(0, 50);
	}
	window.onunload = function() { ZoomImage.close(); };
	ZoomImage.currentWindow = zw;
}


// close opened zoom image popup
ZoomImage.close = function()
{
	if(ZoomImage.currentWindow != null)
	{
		ZoomImage.currentWindow.close();
	}
}


/**
 * Product info tabfolders (switch tabs)
 */

function TabFolder()
{
}

TabFolder.showTab = function(tabFolderId, tabId)
{
	// hide / deactivate all
	var tabfolder = document.getElementById("tabfolder.tab:" + tabFolderId);
	var tabs = tabfolder.childNodes;
	for(var i = 0; i < tabs.length; i++)
	{
		if(tabs[i].nodeType == 1)
		{
			tabs[i].className = "";
		}
	}
	
	var tabcontent = document.getElementById("tabfolder.content:" + tabFolderId);
	var contents = tabcontent.childNodes;
	for(var i = 0; i < contents.length; i++)
	{
		if(contents[i].nodeType == 1)
		{
			contents[i].style.display = "none";
		}
	}
	
	var activeTab = document.getElementById("tabfolder.tab:" + tabFolderId + "." + tabId);
	activeTab.className = "active";
	
	var activeContent = document.getElementById("tabfolder.content:" + tabFolderId + "." + tabId);
	activeContent.style.display = "block";
	
}





/**
 * Document / basket functions
 */
function Basket()
{
}

// show / hide basket item reference input field
Basket.showHideItemRef = function(rowId)
{
	var row = document.getElementById(rowId);
	if(row.style.display == 'none')
	{
		row.style.display = '';
	}
	else
	{
		row.style.display = 'none';
	}
}

// avoid resubmit
formClicked = false;
function disableSubmit() {
	if (formClicked == false){
		formClicked = true;
		return true;
	} else {
		return false;
	}
} 



function setdefaultcons(selectField)
{
	var selectConsignment = document.getElementById("PropertySelection");
	
	selectConsignment.selectedIndex = selectField.selectedIndex;
	selectConsignment.options[selectField.selectedIndex].selected = true;

}


/* COOKIES */

var Cookies = {
	init: function () {
		var allCookies = document.cookie.split('; ');
		for (var i=0;i<allCookies.length;i++) {
			var cookiePair = allCookies[i].split('=');
			this[cookiePair[0]] = cookiePair[1];
		}
	},
	create: function (name,value) {
		var date = new Date();
   		date.setTime(date.getTime()+(360*24*60*60*1000)); // 360 days 
   		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/";
		this[name] = value;
	},
	erase: function (name) {
		this.create(name,'',-1);
		this[name] = undefined;
	}
};
Cookies.init();

/**
 * start of [ save login ]
 */
var logincookiename = 'pkloginc';

function initloginname()
{
	var checkbox = document.getElementById("checkloginname");
	var qlUsername = document.getElementById("qlUsername");
	var qlPassword = document.getElementById("qlPassword");
	
	if(Cookies[logincookiename] != '' && Cookies[logincookiename] != null)
	{
		checkbox.checked = true;
		qlUsername.value = Cookies[logincookiename];
		qlPassword.value = '';
	}
}

function saveloginname()
{
	var checkbox = document.getElementById("checkloginname");
	var qlUsername = document.getElementById("qlUsername");
	
	if(checkbox.checked == false)
	{
		Cookies.erase(logincookiename);
	}
	else if(checkbox.checked == true)
	{
		Cookies.create(logincookiename, qlUsername.value);
	}
}
/**
 * end of [ save login ]
 */


function adjustscrollbar()
{
	var scrollDiv = document.getElementById("layout-content-document-items");
	// Doesn't work properly: scrollDiv.scrollTop = 999999;
	scrollDiv.scrollTop = scrollDiv.scrollHeight + 500;
	
}
 
function showStackTrace()
{
	var stb = document.getElementById("stackTraceBox");
	if ( stb.style.visibility == 'hidden' ) stb.style.visibility = 'visible';
	else stb.style.visibility = 'hidden';
}

/**
 * Minimize a consignment in the basket
 */
function minimizeConsignment(tableId)
{
	/*var docItemtable = document.getElementById(tableId);
	docItemtable.style.display = "none";*/
}

function catchEnter(e)
{
	// Catch IE’s window.event if the 'e' variable is null.
    // FireFox and others populate the e variable automagically.

	if (!e) e = window.event; 
       

	// atch the keyCode into a variable. 
    // IE = keyCode, DOM = which.

	var code = (e.keyCode) ? e.keyCode : e.which;

    // If code = 13 (enter) or 3 (return), cancel it out; else keep going and process the key.

    if (code == 13 || code == 3) return false;
    else return true;
}
