﻿var to;
function waitForIt(funct, time)
{
	clearTimeout(to);
	to = setTimeout(funct + ';', time);
}

function showHide(id, show)
{
    var el = document.getElementById(id);
    if (show)
        el.style.visibility = 'visible';
    else
        el.style.visibility = 'hidden';
}

function toggleHide(id)
{
    var el = document.getElementById(id);
    if (el.style.visibility == 'hidden')
        el.style.visibility = 'visible';
    else
        el.style.visibility = 'hidden';
}

function showHideDisplay(id, show)
{
	var el = document.getElementById(id);
    if (el != null)
	{
		if (show)
			el.style.display = '';
		else
			el.style.display = 'none';
	}
}

function toggleDisplay(id)
{
    var el = document.getElementById(id);
    if (el != null)
    {
        if (el.style.display == 'none')
            el.style.display = '';
        else
            el.style.display = 'none';
    }
}

function getStyle(el, css)
{
    // inline
    if (el.style[css])
    {
        //alert('inline [' + el + ' - ' + el.id + ' - ' + css + ']: ' + el.style[css]);
        return el.style[css];
    }
        
    // stylesheet
    if (el.currentStyle) // IE
    {
        //alert('IE [' + el + ' - ' + el.id + ' - ' + css + ']: ' + el.currentStyle[css]);
        return el.currentStyle[css];
    }

    if (document.defaultView && document.defaultView.getComputedStyle)
    {
        //alert('defaultView [' + el + ' - ' + el.id + ' - ' + css + ']: ' + document.defaultView.getComputedStyle(el, "")[css]);
        return document.defaultView.getComputedStyle(el, "")[css];
    }
}

function setFocus(el)
{
	if (el != null)
	{
	    if (typeof(el.focus) != 'undefined')
		    el.focus();
		if (typeof(el.select) != 'undefined')
			el.select();
	}
}

function enableValidation(el, validate)
{
	if (el != null)
		el.enabled = validate;
}

function formatCurrency(amount)
{
    var i = parseFloat(String(amount).replace('.', '').replace(',', '.'));
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	//return s.replace('.', ',');
	
	s = s.replace('.', ',');
	if (s.length > 6)
	{
	    s = s.split("").reverse().join("");
	    var a = '';
	    for (var x = 0; x < s.length; x++)
        {
            if (x > 3 && (x % 3) == 0)
                a += '.';
            a += s.charAt(x);
        }
        s = a.split("").reverse().join("");
    }
    return s;
}

function formatDateTime(dateToFormat, time)
{
	if (dateToFormat == '')
		return '';
	
	time = time != null ? time : false;
	
	var date = new Date(dateToFormat);
	var day = date.getDate();
	var month = date.getMonth();
	var year = date.getFullYear();
	
	if (isNaN(day) || isNaN(month) || isNaN(year))
		return '';
		
	var returnDate = PadDigits(day, 2) + '-' + PadDigits(++month, 2) + '-' + year;
	
	if (time)
	{
		var sec = date.getSeconds();
		var min = date.getMinutes();
		var hour = date.getHours();
		
		if (!isNaN(sec) && !isNaN(min) && !isNaN(hour))
			returnDate += ' ' + PadDigits(hour, 2) + ':' + PadDigits(min, 2) + ':' + PadDigits(sec, 2);
	}
	
	return returnDate;
}

function PadDigits(n, totalDigits, digit) 
{
	digit = digit != null ? digit : '0';
	
	n = n.toString();
	var pd = '';
	if (totalDigits > n.length)
	{
		for (i = 0; i < (totalDigits-n.length); i++)
		{
			pd += digit;
		}
	}
	return pd + n.toString();
}

function copyValue(orig, copy, overwrite)
{
	overwrite = overwrite == null ? false : overwrite;
	if (copy.value == '' || overwrite)
		copy.value = orig.value;
}

function checkBoxes(arr, check)
{
	for (var i = 0; i < arr.length; i++)
		document.getElementById(arr[i]).checked = check;
}

function checkAllBox(arr, box)
{
	for (var i = 0; i < arr.length; i++)
	{
		if (!document.getElementById(arr[i]).checked)
		{
			box.checked = false;
			return;
		}
	}
	
	box.checked = true;
}

function showHideFullScreenDiv(id, show)
{
	var el = document.getElementById(id);
    if (el != null)
	{
		if (show)
		{
			// TO SHOW FULLSCREEN IN IE...
			document.body.appendChild(el);
			
			var top = ((document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop);
			el.style.top = top + 'px';
			el.style.display = '';
		}
		else
			el.style.display = 'none';
	}
}

var toFloat;
function floatDiv(id)
{
	var el = document.getElementById(id);
    if (el != null)
	{
		var top = ((document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop);
		el.style.top = top + 'px';
	}
	
	toFloat = setTimeout('floatDiv("' + id + '");', 100);
}

function setRadio(id, value)
{
	var radio = new Array();
	var j = 0;
	var input = document.getElementsByTagName('input');
	for (var i = 0; i < input.length; i++)
	{
		if (input[i].type == 'radio' && input[i].id == id)
		{
			radio[j] = input[i];
			j++;
		}
	}
	
	if (radio.length > 0)
	{
		for(var i = 0; i < radio.length; i++)
		{
			radio[i].checked = false;
			if(radio[i].value == value)
				radio[i].checked = true;
		}
	}
}

function isInDocument(el)
{
    var html = document.body.parentNode;
    while (el)
    {
        if (el === html)
            return true;
        
        el = el.parentNode;
    }
    return false;
}


/**********************************************************************/

function fillAccent(text)
{
	var div = document.getElementById('divAccent');
	if (div != null)
		div.innerHTML = text;
}

function FloatDiv()
{
	this.div = null;
	this.offsetLeft = 5;
	this.offsetTop  = 5;
	this.margin = 10;
	this.stable = 5;
	this.swapHorizontal = false;	
	this.swapVertical = false;
	this.timer = null;
	
	this.fixE = function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
	
	this.positionDiv = function(e)
	{
		if (this.div)
		{
			e = this.fixE(e);
			var eX = e.clientX + document.documentElement.scrollLeft;
			var eY = e.clientY + document.documentElement.scrollTop;
			
			if (this.swapHorizontal)
				divX = eX - this.offsetLeft - this.div.offsetWidth;
			else
				divX = eX + this.offsetLeft;
			
			if (this.swapVertical)
				divY = eY - this.offsetTop - this.div.offsetHeight;
			else
				divY = eY + this.offsetTop;
			
			this.div.style.left = divX + 'px';
			this.div.style.top = divY + 'px';
			
			var spaceBottom = document.documentElement.clientHeight - eY - this.div.offsetHeight - this.margin + document.documentElement.scrollTop;
			if (spaceBottom < 0 && !this.swapVertical)
				this.swapVertical = true;
			else if (this.swapVertical && (spaceBottom - this.stable) > 0)
				this.swapVertical = false;
			
			var spaceRight = document.documentElement.clientWidth - eX - this.div.offsetWidth - this.margin + document.documentElement.scrollLeft;
			var spaceLeft = eX - this.div.offsetWidth - this.margin;
			if (spaceRight > this.stable)
				this.swapHorizontal = false;
			else if (spaceLeft > this.stable)
				this.swapHorizontal = true;
			else
				this.swapHorizontal = false;
						
			this.div.style.visibility = 'visible';
			
			if (this.timer)
				clearTimeout(this.timer);
			this.timer = setTimeout("hideDiv();", 10000);
		}
	}
	
	this.showDiv = function(id, e)
	{
		var div = document.getElementById(id);
		document.body.appendChild(div);
		if (div)
		{
			if (this.div)
				this.hideDiv();
			this.div = div;
			document.onmousemove = positionDiv;
			this.positionDiv(e);
		}
	}
	
	this.hideDiv = function ()
	{
		if (this.timer)
			clearTimeout(this.timer);
		this.timer = null;
		document.onmousemove = null;
		if (this.div)
		{
			this.div.style.visibility = 'hidden';
			this.div = null;
		}
	}
}

var floatDiv = new FloatDiv();

function showDiv(id, e)
{
	floatDiv.showDiv(id, e);
}

function hideDiv()
{
	floatDiv.hideDiv();
}

function positionDiv(e)
{
	floatDiv.positionDiv(e);
}

/**********************************************************************/

function blackOut(show)
{
    var black = document.getElementById('greyedOut');
    if (show || (show == null && black.style.display == 'none'))
    {
        black.style.width = document.body.offsetWidth + 'px';
        black.style.height = document.body.offsetHeight + 'px';
        black.style.display = '';
        black.onclick = function() { messageClose(); };
    }
    else
        black.style.display = 'none';
}

var duration;
var messageTimeout;
var messageInterval;
function message(content, error, animationTime, showTime)
{
    if (content && content != null && content != '')
    {
        var div = document.getElementById('message');
        div.className = '';
        if (error != null)
        {
            if (error)
                div.className = 'messageBad';
            else
                div.className = 'messageGood';
        }
        
        // Animation time for opening and closing
        duration = animationTime && animationTime != null ? animationTime : 500;

        // Time to show message before closing starts; -1 = no auto-close
        showTime = showTime && showTime != null ? showTime : 500;
        if (showTime >= 0)
            showTime += duration;
        
        // show background
        blackOut(true);
        
        // Get content div
        var contentDiv = document.getElementById('messageContent');
        if (contentDiv == null)
        {
            contentDiv = document.createElement('div');        
            contentDiv.id = 'messageContent';
            contentDiv.className = 'messageContent';
            div.appendChild(contentDiv);
        }
        
        // Move old content back to it's original parent or remove
        while (contentDiv.hasChildNodes())
        {
            if (contentDiv.firstChild.tagName)
            {
                var id = contentDiv.firstChild.getAttribute('data-parentNode');
                contentDiv.firstChild.removeAttribute('data-parentNode');
                if (id != null && id != '')
                {
                    // Hide
                    contentDiv.firstChild.style.display = 'none';
                    
                    if (id == '__body')
                        document.body.appendChild(contentDiv.firstChild);
                    else
                    {
                        var parent = document.getElementById(id);
                        if (parent != null)
                            parent.appendChild(contentDiv.firstChild);
                    }
                }
                else
                    contentDiv.removeChild(contentDiv.firstChild);
            }
            else
                contentDiv.removeChild(contentDiv.firstChild);
        }
        
        // Set content
        if (content.tagName)
        {
            // Remember original parentNode for later
            var parent = content.parentNode;
            if (parent != null)
            {
                var id = parent.id;
                if (parent === document.body)
                    id = '__body';
                else if (parent.id == null || parent.id == '')
                {
                    id = '__' + new Date().getTime();
                    parent.setAttribute('id', id);
                }
                content.setAttribute('data-parentNode', id);
            }

            contentDiv.appendChild(content);
            content.style.display = '';
        }
        else
            contentDiv.appendChild(document.createTextNode(content));
        
        // Position div
        div.style.top = '-10000px'; // Shove container out of sight
        div.style.left = '-10000px';
        div.style.width = ''; // Reset container width to get correct offsetSize
        div.style.display = ''; // Show containers to get correct offsetSize
        var width = contentDiv.offsetWidth + parseInt(getStyle(contentDiv, 'marginLeft')) + parseInt(getStyle(contentDiv, 'marginRight'));
        var height = contentDiv.offsetHeight + parseInt(getStyle(contentDiv, 'marginTop')) + parseInt(getStyle(contentDiv, 'marginBottom'));
        div.style.width = width + 'px';
        div.style.display = 'none';
        div.style.top = ((document.body.offsetHeight - height) / 2) + 'px';
        div.style.left = ((document.body.offsetWidth - width) / 2) + 'px';

        // Animate
        animate(div, height, duration);
        
        // Auto-close
        if (showTime >= 0)
            messageTimeout = setTimeout(function() { animate(div, height, duration); }, showTime);
    }
}

function messageClose(time)
{
    clearTimeout(messageTimeout);
    var div = document.getElementById('message');
//    if (time == 0)
//    {
//        // Hide
//        div.style.display = 'none';
//        blackOut(false);
//    }
//    else
//    {
        var height = parseInt(div.style.height);
        animate(div, height, time);
//    }
}

var start;
var tick;
var diff;
function animate(div, height, time)
{
    // Animation time for opening and closing
    duration = time && time != null ? time : (duration && duration != null ? duration : 500);
    
    var grow = true;
    if (div.style.display == 'none')
    {
        div.style.height = '0px';
        div.style.display = '';
    }
    else
        grow = false;
    
    function interval(div, grow, height)
    {
        var currentHeight = parseInt(div.style.height);
        
        //var timeDiff = new Date().getTime() - start; // time taken till now
        //var avgTick = timeDiff / currentHeight; // average current time per tick
        //var currentDiff = avgTick * height; // duration for full animation given current average
        //var desiredDiff = duration; //tick * height; // desired duration for full animation
        //diff = currentDiff / desiredDiff; // grow size needed per tick
        //console.log(grow + ' - ' + timeDiff + ' - ' + avgTick + ' - ' + currentDiff + ' - ' + desiredDiff + ' - ' + diff)
        
        // Calculate needed grow size to finish on time
        diff = Math.ceil(((((new Date().getTime() - start) / currentHeight) * height) / duration));
        if (!isFinite(diff) || isNaN(diff))
            diff = 1;

        if (!grow)
            diff = -diff;

        currentHeight += diff;

        if (currentHeight >= height || currentHeight <= 0)
        {
            clearInterval(messageInterval);

            if (currentHeight <= 0)
            {
                clearTimeout(messageTimeout);
                
                // Hide
                div.style.display = 'none';
                blackOut(false);
            }
            else // set desired height
                div.style.height = height + 'px';
        }
        else // set new height
            div.style.height = currentHeight + 'px';
    }

    tick = Math.round(duration / height); // desired time per tick
    start = new Date().getTime(); // start time

    clearInterval(messageInterval);
    messageInterval = setInterval(function() { interval(div, grow, height); }, tick);
}

/**********************************************************************/
