// Tässä oletetaan, että kalenterifunktiot on saatu ladattua toisessa .js-tiedostossa.

//var groupPricePoints = [];
/**
 * Teoriassa käytässä olevia palvelinryhmiä voi olla vähemmän kuin hintoja eri
 * palvelinryhmille.
 */
//var serverGroups = [];
//var userServers = [];
var moneySign = "&euro;";
var activePopupHidings = [];


// Inits the day servers customer specific javascripts. 
function dayServersInitPriceActions()
{
    var dayField = document.getElementById("dayField");
    var continueDayField = document.getElementById("continue_dayField");

	if (dayField != undefined)
	{
            if (continueDayField == undefined)
                {
                    continueDayField = null;
                }
		var actionFunction = function() {callDayField(dayField, continueDayField)};
		dayField.onkeyup = actionFunction;
		dayField.onpaste= actionFunction;
	}

	if (continueDayField != undefined)
	{
            if (dayField == undefined)
                {
                    dayField = null;
                }
		var actionFunction = function() {callContinueDayField(continueDayField, dayField)};
		continueDayField.onkeyup = actionFunction;
		continueDayField.onpaste= actionFunction;
	}

	for (var i in serverGroups) {
		var groupId = serverGroups[i];

                if ( dayField != undefined) 
                {       //alert("free"+groupId);
                        var priceField = document.getElementById("priceField_" + groupId);
                        var priceRealmoney = document.getElementById("priceRealmoney_" + groupId);
                        // Koska IE ei osaa setAttributea tuollaisille eventeille, niin tehdään
                        // sitten näin.

                        countPrice(dayField.value, groupId, priceField, priceRealmoney);
		}
	}
	_updateUserServerFields();
}

function _updateUserServerFields()
{
    var continueDayField = document.getElementById("continue_dayField");
    for (var i in userServers)
        {
            id = userServers[i];
			priceField = document.getElementById('continue_priceField_' + id);
			realMoneyField = document.getElementById('continue_priceRealmoney_' + id);
            var hidden_dayField = document.getElementById('continue_dayField_' + id);
			if (priceField == undefined
			    || realMoneyField == undefined)
			{
				continue;
			}
			countPrice(continueDayField.value,
					   id,
					   priceField,
					   realMoneyField);
            if (continueDayField != undefined)
            {
                countPrice(continueDayField.value,
                           id,
                           priceField,
                           realMoneyField);
	            hidden_dayField.value = continueDayField.value;
            } else {
            	hidden_dayField.value = 0;
            }
        }
}

// Calculate new price for all booking continuation fields.
function getPriceCalculationsContinue() {
	for (var i in userServers) {
		var eventId = userServers[i];
		var priceField = null;
	    var realMoneyField = null;
	    var dayField = null;
		dayField = document.getElementById("continue_dayField");
		priceField = document.getElementById('continue_priceField_' + eventId)
		realMoneyField = document.getElementById('continue_priceRealmoney_' + eventId);
                
		countPrice(dayField.value,
				   eventId,
				   priceField,
				   realMoneyField);
	}
}

// Calculate new prices for all fields
function getPriceCalculations(dayField) {
	//var splitted = thisfield.id.split("_");
	//var groupId = splitted[1];

	var priceField = null;
        var realMoneyField = null
	var idName = "";
	for (var i in serverGroups) {		
		id = serverGroups[i];
		priceField = document.getElementById(idName + 'priceField_' + id)
		realMoneyField = document.getElementById(idName + 'priceRealmoney_' + id);
		countPrice(dayField.value,
				   id,
				   priceField,
				   realMoneyField);

                var continueDayField = document.getElementById("continue_dayField");
                if (continueDayField != undefined)
                    {
                        countPrice(continueDayField.value,
                                   id,
                                   priceField,
                                   realMoneyField);
                    }
                
	}
	_updateUserServerFields();
}

function callContinueDayField(dayField, other)
{
    if (other != null)
        {
            other.value = dayField.value;
        }
    getPriceCalculations(dayField);
}
function callDayField(dayField, other)
{
    if (other != null)
        {
            other.value = dayField.value;
        }
    getPriceCalculations(dayField);
}

// Alustaa päiväpalvelimissa käyttäjän omien palvelimien toiminnot.
function dayServersInitUserActions()
{
	serversInitUserActions("userServer_", userServers);
}

function publicServersInitUserActions()
{
	serversInitUserActions("publicServer_", userServers);
}

function serversInitUserActions(idPrefix, idArray)
{
	if (!idArray)
		return;

	for (var i in idArray) 
	{
		var id = idArray[i];
		var userServerField = document.getElementById(idPrefix + id);
		if (userServerField == undefined)
		{
			continue;
		}
		
		userServerField.setAttribute('class', "unselected");

		// Koska IE ei osaa setAttributea tuollaisille eventeille, niin tehdään
		// sitten näin.
		userServerField.onmouseover = function() {userServerOnmouseover(this);};
		userServerField.onmouseout = function() {userServerOnmouseout(this);};
	}
}

function userServerOnmouseover(thisfield)
{
    var splitted = thisfield.id.split("_");
    var eventId = splitted[1];
    
    userServerPopupHideCancel(eventId);
    userServerPopupHidePending();
    
    thisfield.className = "selected";
    changeClass("tab-" + eventId, "active");
    var divmain = document.getElementById("tab-" + eventId);
    // Purkkaviritelmä maksimitabikoon saamiseksi.
    var leftTab = document.getElementById("tab1-" + eventId);
    var rightTab = document.getElementById("tab2-" + eventId);
    var largestTab = leftTab;
    if (rightTab != undefined && leftTab.clientHeight < rightTab.clientHeight)
    {
        largestTab = rightTab;
    }
    var size = getWindowSize();
    var windowSizeY = size[1];
    var scrll = getScrollXY();
    var scrollY = scrll[1];
    var pageBottom = windowSizeY + scrollY;
    var popupTop = divmain.offsetTop;
    var popupBottom = largestTab.clientHeight + largestTab.offsetTop + divmain.offsetTop;
    if (popupBottom > pageBottom)
    {
        // how much away popup is wanted to be away from the screen's bottom.
        var screenPopupBottomDifference = 10; 
        var pushupAmount = popupBottom - pageBottom;
        pushupAmount += screenPopupBottomDifference;
        var newTopPosition = (popupTop - pushupAmount);
        if (newTopPosition < 0)
        {
            newTopPosition = 0;
        }
        divmain.style.top = newTopPosition + 'px';
    }
}

function getWindowSize() {
/*
	Copied from http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=16
*/

  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }

  return new Array(myWidth, myHeight);
}

/**
 * Returns much page has been scrolled.
 *
 * The returned coordinates give the visible area's top left corner's location
 * in the page coordinate system.
 * 
 * @return [scrollX, scrollY]
 */
function getScrollXY() {
/*
	Copied from http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=16
*/
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
	scrOfY = window.pageYOffset;
	scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	//DOM compliant
	scrOfY = document.body.scrollTop;
	scrOfX = document.body.scrollLeft;
	} else if (document.documentElement &&
	( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	//IE6 standards compliant mode
	scrOfY = document.documentElement.scrollTop;
	scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

function userServerOnmouseout(thisfield)
{
	var splitted = thisfield.id.split("_");
	var eventId = splitted[1];
	
	thisfield.className = "unselected";
    activePopupHidings[eventId] = 1;
    setTimeout("userServerPopupHide(" + eventId + ");", 500);
}

/**
 * Immediately hides all popups that are waiting to be hidden.
 *
 */
function userServerPopupHidePending()
{
    for (eventId in activePopupHidings)
    {
        if (activePopupHidings[eventId])
        {
            userServerPopupHide(eventId);
        }
    }
}

function userServerPopupHide(eventId)
{
    if (activePopupHidings[eventId])
    {
        changeClass("tab-" + eventId, "passive");
    }
}

function userServerPopupHideCancel(eventId)
{
    activePopupHidings[eventId] = 0;
}

// Laskee jotenkin hämärästi hinnan palvelimelle.
// These calculations can also be found from the actual server price processors.
function getDailyPrice(days, groupId)
{
	days = parseInt(days);
	groupId = '' + parseInt(groupId);

	if (groupPricePoints[groupId] == undefined) {
		return "NaN";
	}

	var groupPrices = groupPricePoints[groupId];

	var startPoint = groupPrices[0];
	var startDays = startPoint[0];
	var startPrice = startPoint[1];

	var monthPoint = groupPrices[1];
	var monthPrice = monthPoint[1];

	var yearPoint = groupPrices[2];
	var yearPrice = yearPoint[1];

	if (!days
		|| days < startDays) {
		return "NaN";
	}
	
	var price = 0;
	if ( days <= 0 )
	{
	}
	else if ( days < 30 )
	{
		price = Math.round(startPrice*1 + (monthPrice*30 - startPrice*1)/(29)*(days - 1));
	}
	else //if ( days < 365 )
	{
		price = Math.round(monthPrice*30 + (yearPrice*365 - monthPrice*30)/ (365 -30) * (days - 30));
	}
	return price;
}

function countPrice(days, groupId, target, euroTarget)
{
    if (!days
    	|| days == undefined
    	|| parseInt(days) < 0) 
    {
        target.value = '';
	euroTarget.innerHTML = '0.00 ' + moneySign;
        return;
    }

    days += '';
    var price = getDailyPrice(days, groupId);
    if (target == null) return;
//    alert(target);
    target.value = formatMoney(price,'.','.',' ');
//	alert(price);
    price = price * 30 / days / 100;
	if (agent.indexOf('msie 5.0') == -1)
	{
		price = price.toFixed(2);
	}
    euroTarget.innerHTML = formatMoney(price,'.','.',' ', 2) + ' ' + moneySign;
	return;
}

function formatMoney(nStr, inD, outD, sep, decimals)
{
//	if (agent.indexOf('msie 5.0') == -1)
//	{
//		nStr.toFixed(2);
//		alert(nStr);
//	}
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, dpos +1 + decimals);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}

/**
 * Change field values with buttons
 * @author Pharazon
 */
function dayFieldChange(amount)
{
	continueDayField=document.getElementById('dayField');
	continueDayField.value = eval(parseInt(continueDayField.value) + amount);
	//check for negative values
	if (continueDayField.value<=0)
		continueDayField.value=1;
	getPriceCalculations(continueDayField);
	//change also
	dayField=document.getElementById('continue_dayField');
	dayField.value = continueDayField.value;

}
