/* VIEWPORT */

function coreScrollTo(sScrollTo) {
	var oElement_1			= document.getElementsByName(sScrollTo);
	var oElement_2			= document.getElementById(sScrollTo);
	if(oElement_1 && typeof(oElement_1[0]) != 'undefined' && oElement_1[0].offsetTop) {
		window.scrollTo(0, oElement_1[0].offsetTop);
	} else if(oElement_2 && oElement_2.offsetTop) {
		window.scrollTo(0, oElement_2.offsetTop);
	} else {
		// Element nicht gefunden
		window.scrollTo(0, 0);
	}
}

function coreCenter(sContainerId, oOptions, bSkipFirst) {
	$jQuery(sContainerId).hover(
		function(){iCoreLayerAutoCloseable = 0;},
		function(){iCoreLayerAutoCloseable = 1;}
	)
	$jQuery(sContainerId).css('display', 'inline');
	$jQuery(sContainerId).css('position', 'fixed');
	
	if(typeof($jQuery(sContainerId).attr('sCoreLayerResized')) == 'undefined') {
		var iContainerWidth		= $jQuery(sContainerId).innerWidth();
		$jQuery(sContainerId).width((iContainerWidth+20));
	}
	
	$jQuery(sContainerId).css('top', '35%');
	$jQuery(sContainerId).css('left', '50%');
	
	if(typeof($jQuery(sContainerId).attr('sCoreLayerResized')) == 'undefined') {
		var iContainerWidth		= $jQuery(sContainerId).innerWidth();
		var iContainerHeight	= $jQuery(sContainerId).innerHeight();
		$jQuery(sContainerId).css('margin-left', (0-(iContainerWidth/2))+'px');
		$jQuery(sContainerId).css('margin-top', (0-(iContainerHeight/2))+'px');
		$jQuery(sContainerId).attr('sCoreLayerResized', 'true');
	}

	window.setTimeout(function(){coreLayerSetAutoClose(sContainerId);}, 200);
	return;
}

function coreGetViewport() {
    var d = document.documentElement, b = document.body, w = window;
    
    if($jQuery.browser.msie) {
    	var iLeft	= b.scrollLeft || d.scrollLeft;
    	var iTop	= b.scrollTop || d.scrollTop;
    } else {
    	var iLeft	= w.pageXOffset;
    	var iTop	= w.pageYOffset;
    }
    if(w.innerWidth) {
    	var iWidth	= w.innerWidth;
    	var iHeight	= w.innerHeight;
    } else {
    	var iWidth	= d.clientWidth;
    	var iHeight	= w.innerHeight;
    }
    return {left: iLeft, top: iTop, width: iWidth, height: iHeight};
}

function coreCenterViewport(sContainerId, bSkipRenew) {
	$jQuery(sContainerId).css('display', 'inline');
	$jQuery(sContainerId).css('position', 'fixed');
	
	var iContainerWidth		= $jQuery(sContainerId).innerWidth();
	$jQuery(sContainerId).width((iContainerWidth+20));
	
	$jQuery(sContainerId).css('top', '35%');
	$jQuery(sContainerId).css('left', '50%');
		
	var iContainerWidth		= $jQuery(sContainerId).innerWidth();
	var iContainerHeight	= $jQuery(sContainerId).innerHeight();
	$jQuery(sContainerId).css('margin-left', (0-(iContainerWidth/2))+'px');
	$jQuery(sContainerId).css('margin-top', (0-(iContainerHeight/2))+'px');
	
	(sContainerId);
	return;
}

function coreRedirect(sUrl) {
	top.location.href	= sUrl;
}

/* LAYER */
var iCoreLayerAutoCloseable		= 1;
function coreLayerSetAutoClose(jQuerySelector) {
	if(typeof($jQuery(window).on) == 'function') {
		$jQuery(window).on('click', coreShaderClose);
	} else {
		$jQuery(window).click(function(){coreShaderClose()});
	}
}

function coreLayerOpen(jQuerySelector, oOptions) {
	if(typeof(oOptions) == 'undefined')
		var oOptions	= {};
	if(oOptions.modal) coreShaderOpen();
	// coreCenterViewport(jQuerySelector);
	coreCenter(jQuerySelector);
	$jQuery(jQuerySelector).show();
	// coreCenterViewport(jQuerySelector);
	coreCenter(jQuerySelector);
	// window.setTimeout('coreLayerSetAutoClose(\''+jQuerySelector+'\')', 1000);
	return;
}

function coreShaderOpen() {
	$jQuery('#coreLayerShader').show();
}

function coreShaderClose(bForce) {
	if(iCoreLayerAutoCloseable == 0 && typeof(bForce) == 'undefined')
		return false;
	if(typeof($jQuery(window).off) == 'function') {
		$jQuery(window).off('click', coreShaderClose);
	} else {
		$jQuery(window).unbind();
	}
	$jQuery('#coreLayerShader').hide();
	$jQuery('.coreLayerBox').hide();
	return;
}

/* GENERAL */
function coreObject(sIndex) {
	return document.getElementById(sIndex);
}

function coreSubmit(sIndex) {
	if(typeof(sIndex) == "undefined")
		var sIndex = "SubmitData";
	document.getElementById(sIndex).submit();
}

function coreFocus(sIndex) {
	document.getElementById(sIndex).focus();
}

function coreUploadPathById(iId) {
	iId					= String(iId);
	var iStringLength	= iId.length;
	if(iStringLength % 2 > 0)
		iId				= "0" + iId;
	var aSplit			= iId.split("");
	var sReturn			= '';
	for(i=0; i<aSplit.length; i++) {
		if(i > 0 && i % 2 == 0) sReturn		= sReturn + '/';
		sReturn			= sReturn + aSplit[i];
	}
	sReturn			= sReturn + '/' + iId;
	return sReturn;
}

function coreUploadUrlById(iId, iWidth, iHeight, sConnector) {
	if(typeof(sConnector) == 'undefined')
		var sConnector	= '.';
	var sMediaUrl		= sHostMedia+'/'+coreUploadPathById(iId)+'/'+iId+sConnector+iWidth+sConnector+iHeight+'.jpg';
	return sMediaUrl;
}

/* DISPLAY */
function coreDisplay(iId, sDisplay) {
	if(typeof(sDisplay) == "undefined") var sDisplay = 'inline';
	document.getElementById(iId).style.display = sDisplay;
}
function coreDisplayTrsByClass(sClass) {
	var aRows	= document.getElementsByTagName('tr');
	for(i=0; i<aRows.length; i++) {
		var sClassName	= aRows[i].className;
		if(sClassName.indexOf(sClass) > -1) {
			aRows[i].style.display	= 'table-row';
		}
	}
}
function coreToggleTrsByClass(sClass) {
	var aRows	= document.getElementsByTagName('tr');
	for(i=0; i<aRows.length; i++) {
		var sClassName	= aRows[i].className;
		if(sClassName.indexOf(sClass) > -1) {
			if(aRows[i].style.display == 'none')
				aRows[i].style.display	= 'table-row';
			else
				aRows[i].style.display	= 'none';
		}
	}
}
function coreUndisplay(iId) {
	document.getElementById(iId).style.display = 'none';
}
function coreToggleDisplay(sId, sDisplay, bForceReturn) {
	if(typeof(sDisplay) == "undefined") var sDisplay = 'inline';
	if(coreGetStyle(sId, 'display') == 'none') {
		coreSetStyle(sId, 'display', sDisplay);
		if(typeof(bForceReturn) != "undefined" && bForceReturn == true)
			return sDisplay;
	} else {
		coreSetStyle(sId, 'display', 'none');
		if(typeof(bForceReturn) != "undefined" && bForceReturn == true)
			return 'none';
	}
}

function coreToggleStyle(sId, sIndex, aValues) {
	if(coreGetStyle(sId, sIndex) == aValues[0])
		coreSetStyle(sId, sIndex, aValues[1]);
	else
		coreSetStyle(sId, sIndex, aValues[0]);
}

/* SET */
function coreSet(sId, sIndex, mValue) {
	var oObject	= document.getElementById(sId);
	oObject[sIndex] = mValue;
}
function coreSetStyle(sId, sIndex, mValue) {
	if(typeof(sId) == "object") {
		sId.style[sIndex] = mValue;
		return;
	}
	document.getElementById(sId).style[sIndex] = mValue;
}
function coreSetValue(sFieldId, sValue, bSkipIdCheck) {
	if(typeof(bSkipIdCheck) == "undefined") var bSkipIdCheck = false;
	var oObject		= coreObject(sFieldId);
	if(document.getElementById(sValue) && document.getElementById(sValue).type && bSkipIdCheck == false)
		var sValue	= coreGetValue(sValue);

	if(coreGet(sFieldId, 'type') == "select-one") {
		var aOptions	= coreGet(sFieldId, 'options');
		for(i=0;i<aOptions.length;i++) {
			if(oObject.options[i].value == sValue) {
				oObject.selectedIndex		= i;
				oObject.options[i].selected	= true;
				break;
			}
		}
	} else {
		document.getElementById(sFieldId).value = sValue;
	}
}
function coreSetHtml(sId, sHtml) {
	var sHtmlIndex	= "#" + sId;
	$jQuery(sHtmlIndex).text	= sHtml;
}

function coreSetRange(sInputId, selectionStart, selectionEnd) {
   // IE
   if(document.getElementById(sInputId).createTextRange) {
      var range = document.getElementById(sInputId).createTextRange();
      range.collapse(true);
      range.moveEnd('character', selectionEnd);
      range.moveStart('character', selectionStart);
      range.select();
    // real browsers :)
    } else if(document.getElementById(sInputId).setSelectionRange) {
      document.getElementById(sInputId).focus();
      document.getElementById(sInputId).setSelectionRange(selectionStart, selectionEnd);
    }
}

/* GET */
function coreGet(sId, sIndex) {
	if(!document.getElementById(sId)) return false;
	var oObject	= document.getElementById(sId);
	return oObject[sIndex];
}
function coreGetStyle(sId, sIndex) {
	var oObject	= document.getElementById(sId);
	return oObject.style[sIndex];
}
function coreGetValue(sFieldId) {
	var oObject	= coreObject(sFieldId);
	if(!oObject) alert('Core: (not found) '+sFieldId);
	
	if(coreGet(sFieldId, 'type') == "select-one") {
		return oObject.options[oObject.selectedIndex].value;
	} else {
		return oObject.value;
	}
}

/* ADD */
function coreAddSelectOption(sFieldId, sText, mValue, bDefaultSelected, bSelected) {
	var oObject		= document.getElementById(sFieldId);
	if(typeof(bDefaultSelected) == "undefined") bDefaultSelected = false;
	if(typeof(bSelected) == "undefined") bSelected = false;
	oNewOption	= new Option(sText, mValue, bDefaultSelected, bSelected);
	oObject.options[oObject.options.length] = oNewOption;
}

/* REMOVE */
function coreRemoveSelectOption(sFieldId, mValue) {
	var oObject		= coreObject(sFieldId);
	var aOptions	= coreGet(sFieldId, 'options');
	for(i=0;i<aOptions.length;i++) {
		if(oObject.options[i].value == mValue) {
			document.getElementById(sFieldId).removeChild(oObject.options[i]);
		}
	}
}

/* MOVE */
function coreMoveSelectedUp(sFieldId, iSelectedIndex) {
	if(iSelectedIndex < 1) {
		alert('Column already on first position!');
		return false;
	}
	oSelect			= document.getElementById(sFieldId);
	sSelectedValue	= oSelect.options[iSelectedIndex].value;
	sSelectedText	= oSelect.options[iSelectedIndex].text;
	var iTempIndex	= iSelectedIndex - 1;
	sTempValue		= oSelect.options[iTempIndex].value;
	sTempText		= oSelect.options[iTempIndex].text;
	oSelect.options[iTempIndex].value		= sSelectedValue;
	oSelect.options[iTempIndex].text		= sSelectedText;
	oSelect.options[iSelectedIndex].value	= sTempValue;
	oSelect.options[iSelectedIndex].text	= sTempText;
	oSelect.selectedIndex	= iTempIndex;
}
function coreMoveSelectedDown(sFieldId, iSelectedIndex) {
	if(iSelectedIndex >= document.getElementById(sFieldId).options.length - 1) {
		alert('Column already on last position!');
		return false;
	}
	oSelect			= document.getElementById(sFieldId);
	sSelectedValue	= oSelect.options[iSelectedIndex].value;
	sSelectedText	= oSelect.options[iSelectedIndex].text;
	var iTempIndex	= iSelectedIndex + 1;
	sTempValue		= oSelect.options[iTempIndex].value;
	sTempText		= oSelect.options[iTempIndex].text;
	oSelect.options[iTempIndex].value		= sSelectedValue;
	oSelect.options[iTempIndex].text		= sSelectedText;
	oSelect.options[iSelectedIndex].value	= sTempValue;
	oSelect.options[iSelectedIndex].text	= sTempText;
	oSelect.selectedIndex	= iTempIndex;
}

/* CHECK */
function coreCheckAll(sFieldNames, thisForm) {
	try {
		if(typeof(thisForm) == "undefined")		var thisForm		= "SubmitData";
		if(typeof(sFieldNames) == "undefined")	var sFieldNames		= "";
	
		if(isNaN(thisForm)) {
			for(i = 0; i < document.forms.length; i++) {
				if(document.forms[i].name == thisForm) {
					var o = document.forms[i].elements;
					break;
				}
			}
		} else {
			var o = document.forms[thisForm].elements
		}
		if(o) {
			for(i=0; i<o.length; i++) {
				if(sFieldNames != '') {
					if((o[i].type == 'checkbox') && (o[i].name.indexOf(sFieldNames) != -1)) {
						o[i].checked = true;
					}
				} else {
					if(o[i].type == 'checkbox') {
						o[i].checked = true;
					}
				}
			}
		}
	} catch(error) {
		alert(error);
	}
}

function coreCheckNone(sFieldNames, thisForm) {
	try {
		if(typeof(thisForm) == "undefined")		var thisForm		= "SubmitData";
		if(typeof(sFieldNames) == "undefined")	var sFieldNames		= "";
	
		if(isNaN(thisForm)) {
			for(i = 0; i < document.forms.length; i++) {
				if(document.forms[i].name == thisForm) {
					var o = document.forms[i].elements;
					break;
				}
			}
		} else {
			var o = document.forms[thisForm].elements
		}
		if(o) {
			for(i=0; i<o.length; i++) {
				if(sFieldNames != '') {
					if((o[i].type == 'checkbox') && (o[i].name.indexOf(sFieldNames) != -1)) {
						o[i].checked = false;
					}
				} else {
					if(o[i].type == 'checkbox') {
						o[i].checked = false;
					}
				}
			}
		}
	} catch(error) {
		alert(error);
	}
}

/* CALCULATIONS */
function coreFormatInt(zahl, k, sUpdateIndex) {
    if(!k) 
        k = 4;
    if(typeof(fix) == "undefined") var fix = true;
    
    var neu = '';
    // Runden
    var f = Math.pow(10, k);
    zahl = '' + parseInt(zahl * f + (.5 * (zahl > 0 ? 1 : -1))) / f;
    // Komma ermittlen
    var idx = zahl.indexOf('.');
    // fehlende Nullen einfügen
    if (fix) {
        zahl += (idx == -1 ? '.' : '') +
        f.toString().substring(1);
    }

    // Nachkommastellen ermittlen
    idx = zahl.indexOf('.');
    if (idx == -1) 
        idx = zahl.length;
    else 
        neu = '.' + zahl.substr(idx + 1, k);
    // Tausendertrennzeichen
    while (idx > 0) {
        if (idx - 3 > 0) 
           neu = '' + zahl.substring(idx - 3, idx) + neu;
        else 
            neu = zahl.substring(0, idx) + neu;
        idx -= 3;
    }
    if(typeof(sUpdateIndex) != "undefined")
    	coreSetValue(sUpdateIndex, neu);
    return neu;
}

function coreIncreaseTax(iNettoVal, iTax, sUpdateFieldId, sFormatFieldId) {
	if(isNaN(iNettoVal) || iNettoVal == "") iNettoVal = 0.0;
	if(isNaN(iTax) || iTax == "") iTax = 0.0;
	
	var iBruttoVal		= parseFloat(iNettoVal) * (1 + (parseFloat(iTax) / 100));
   	iBruttoVal			= coreFormatInt(iBruttoVal);
   	if(typeof(sUpdateFieldId) == "undefined" || sUpdateFieldId == false) return iBruttoVal;
   	coreSetValue(sUpdateFieldId, iBruttoVal);
   	if(typeof(sFormatFieldId) != "undefined") {
   		var sFormattedValue	= coreFormatInt(coreGetValue(sFormatFieldId));
   		coreSetValue(sFormatFieldId, sFormattedValue);
   	}
}

function coreDecreaseTax(iBruttoVal, iTax, sUpdateFieldId, sFormatFieldId) {
	if(isNaN(iBruttoVal) || iBruttoVal == "") iNettoVal = 0.0;
	if(isNaN(iTax) || iTax == "") iTax = 0.0;
	
	var iNettoVal		= ((parseFloat(iBruttoVal) * 100) / (100 + parseFloat(iTax)));
	iNettoVal			= coreFormatInt(iNettoVal);
	if(typeof(sUpdateFieldId) == "undefined" || sUpdateFieldId == false) return iNettoVal;
   	coreSetValue(sUpdateFieldId, iNettoVal);
   	if(typeof(sFormatFieldId) != "undefined") {
   		var sFormattedValue	= coreFormatInt(coreGetValue(sFormatFieldId));
   		coreSetValue(sFormatFieldId, sFormattedValue);
   	}
}

/* DATE */
function coreGetTimestamp() {
	try {
		var exdate		= new Date();
		var sDate		= exdate.toGMTString();
		return Date.parse(sDate);
	} catch(error) {
		alert(error);
	}
}

/* WINDOW */
function coreWindowResetSize() {
	window.resizeBy(1, 1);
	window.resizeBy(-1, -1);
}

/* SORT ORDER-IDS */
function coreNumsort(a, b) {
  return a - b;
}

function coreSortableActivate(sIndex) {
	if(typeof(sIndex) == "undefined") var sIndex = "DataTable";
	$jQuery('#'+sIndex+'').tableDnD({
		onDrop: function(table, row) {
			coreSetOrderIds($jQuery.tableDnD.serialize(), 'multiSaveOrderId');
		}
	});
}

function coreSetOrderIds(sSerializedString, sOrderFieldId) {
	try {
		var aAvailables	= new Array();
		var iLoop		= 0;
		var iMinIndex	= 0;
		$jQuery("input").each(function(i){
		    if(this.id.indexOf('multiSaveOrderId') > -1) {
		    	aAvailables[iLoop]	= this.value;
		    	iLoop++;
		    }
		});
		aAvailables.sort(coreNumsort);
		var iLoop		= 0;
		$jQuery("input").each(function(i){
		    if(this.id.indexOf('multiSaveOrderId') > -1) {
		    	this.value	= aAvailables[iLoop];
		    	iLoop++;
		    }
		});
		return;
	} catch(error) {
		alert(error);
	}
}

function coreResetOrderIds(sSerializedString, sOrderFieldId) {
	try {
		var iMinIndex	= 0;
		$jQuery("input").each(function(i){
		    if(this.id.indexOf('multiSaveOrderId') > -1) {
		    	if(this.value > 0 && this.value < iMinIndex) iMinIndex	= this.value;
		    }
		});
		$jQuery("input").each(function(i){
		    if(this.id.indexOf('multiSaveOrderId') > -1) {
		    	this.value	= iMinIndex;
		    	iMinIndex++;
		    }
		});
		return;
	} catch(error) {
		alert(error);
	}
}

/* STRINGS */
function coreTrim(sString) {
	for(i=0; i<sString.length; i++) {
		if(sString[0] == " " || sString[0] == "\t" || sString[0] == "\r" || sString[0] == "\n")
			sString	= sString.substr(i);
		else
			break;
	}
	for(i=sString.length; i>0; i--) {
		var iLast	= sString.length;
		if(sString[iLast] == " " || sString[iLast] == "\t" || sString[iLast] == "\r" || sString[iLast] == "\n")
			sString	= sString.substr(0, iLast);
		else
			break;
	}
	return sString;
}

/* FILES */
function coreHumanFilesize(iBytes) {
	if(iBytes < 1048576) return Math.ceil((iBytes/1024)) + "KB";
	if(iBytes < 1073741824) return Math.ceil((iBytes/(1024*1024))) + "MB";
	if(iBytes < 1073741824) return Math.ceil((iBytes/(1024*1024*1024))) + "MB";
	return Math.ceil((iBytes/(1024*1024*1024*1024))) + "TB";
}

/* DOCUMENT */
function coreFrameset(oConfig) {
	oParams		= {
		'frameset':		{
			'cols':			'100,*',
			'rows':			'*',
			'id':			'framesetContainer'
		},
		'noframes': 		'<p>Your browser dows not support frames.</p>',
		'frame_1': 			{
			'frameborder': 	0,
			'id': 			'framesetHidden',
			'src': 			'about:blank',
			'scrolling': 	'no'
		},
		'frame_2': 			{
			'frameborder': 	0,
			'id': 			'framesetHidden',
			'src': 			'about:blank',
			'scrolling': 	'no'
		}
	}
	document.close();
	with (document) {
	    open();
	    write('<frameset');
	    for(sIndex in oParams["frameset"])
	    	write(' '+sIndex+'="'+oParams["frameset"][sIndex]+'"');
	    write('>');
	    write('<frame');
	    for(sIndex in oParams["frame_1"])
	    	write(' '+sIndex+'="'+oParams["frame_1"][sIndex]+'"');
	    write(' />');
	    write('<frame');
	    for(sIndex in oParams["frame_2"])
	    	write(' '+sIndex+'="'+oParams["frame_2"][sIndex]+'"');
	    write(' />');
	    write('<noframes><body>'+oParams["noframes"]+'</body></noframes>');
	    write('</frameset>');
	    close();
	}
}

