/**
 * Prevent enter from submitting a form.
 * Usage: onkeypress='return noEnter((event)?(event):(window.event));'
 */
function noEnter(event)
{
	if (!event)
			event = window.event;
  	if(event.keyCode == 13)
  	{
		event.cancelBubble = true;	// stop bubbling (non-w3c)
		if (event.stopPropagation) event.stopPropagation(); // stop bubbling (w3c)
  		return false;
  	}
  	return true;
}

// new popup popping up code
var lastPopup = null;
var lastPopupContainer = null;
var lastPopupVisitTime = 0;
var lastVisitedX = 0;
var lastVisitedY = 0;
var popupHandler_chain_nextFunction = null;

// drag popups
/*
var dragElem = null;
var dragPrevX = 0;
var dragPrevY = 0;
var dragOrigX = 0;
var dragOrigY = 0;

function moveDragged(event)
{
	if (dragElem == null)
	{
		return true;
	}

	pos = getEventPos(event);
	
	oldLeft = parseInt(dragElem.style.left);
	if (isNaN(oldLeft))
	{	alert("foo");
		oldLeft = 0;
	}
	
	oldTop = parseInt(dragElem.style.top);
	if (isNaN(oldTop))
	{
		oldTop = 0;
	}

	dragElem.style.left = oldLeft + pos[0] - dragPrevX + 'px';
	dragElem.style.top =  oldTop + pos[1] - dragPrevY + 'px';
	
	dragPrevX = pos[0];
	dragPrevY = pos[1];
	
	return false;
}

function startDrag(elem, event)
{
	dragElem = elem;

	pos = getEventPos(event);

	elem.style.position = 'absolute';

	origPos = getPosition(elem);

	dragElem.style.left = origPos.x + 'px';
	dragElem.style.top = origPos.y + 'px';

	dragPrevX = pos[0];
	dragPrevY = pos[1];
}

function stopDrag()
{
	dragElem = null;
}
*/
function handleMousemove(event)
{
	// [quirksmode.org]
	if (!event) var event = window.event;
	event.cancelBubble = true;	// stop bubbling (non-w3c)
	if (event.stopPropagation) event.stopPropagation(); // stop bubbling (w3c)
	// [/quirksmode.org]

	
	var target = (event.target == undefined) ? event.srcElement : event.target;

	if (inPopup(target))
	{
		var pos = getEventPos(event);
		lastVisitedX = pos[0];
		lastVisitedY = pos[1];
		lastPopupVisitTime = new Date().getTime();
	} else {
		passivize(lastPopup, event);
	}
	
//	return moveDragged(event);
	
	if (popupHandler_chain_nextFunction != null)
	{
		// call the next interested handler (tooltip?)
		return popupHandler_chain_nextFunction(event);
	}
	return false;
}

function activize(popupElem, containerElem)
{
	_doPassivize(lastPopup);
	popupElem.className = "active";
	lastPopup = popupElem;
	lastPopupContainer = containerElem;
}

// [quirksmode.org]
function getEventPos(e)
{
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	} else if (e.clientX || e.clientY) {
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	return [posx, posy];
} // [/quirksmode.org]

function passivize(elem, event)
{
	var pos = getEventPos(event);
	var dxs = Math.pow(pos[0] - lastVisitedX, 2);
	var dys = Math.pow(pos[1] - lastVisitedY, 2);
	if ( (Math.sqrt(dxs + dys) > 75)
		&& (new Date().getTime() - lastPopupVisitTime) > 400)
	{
		_doPassivize(elem);
	}
}

function _doPassivize(elem)
{
	if (elem != null)
		elem.className = "passive";
	lastPopup = null;
	lastPopupContainer = null;
	lastPopupVisitTime = 0;
	lastVisitedX = 0;
	lastVisitedY = 0;
}

function inPopup(elem)
{
	if (elem == undefined || lastPopupContainer == undefined)
		return false;
		
	if (elem.id == lastPopupContainer.id)
		return true;
	else
		return inPopup(elem.parentNode);
}

function initPopup()
{
	if (document.onmousemove != null)
	{
		popupHandler_chain_nextFunction = document.onmousemove;
	}
	document.onmousemove = handleMousemove;
}
// end new popup popping up code


// Olettaa headista tulevan seuraavat vakiot:
//
// CELLCOUNT
// THISFILE
// CAL_VISIBLE_DAYS
// GAME_ID
// PROVIDER_ID (jos on)

var agent = navigator.userAgent.toLowerCase();
var confid;
var isMouseDown = false;
var currentColumn = -1;
var lastCell  = -1;
var startTemp = -1;
var startCell = -1;
var endCell   = -1;
var currentActives = new Array();
var hideBlock = false;
var hideCounter = null;
var mouseMoves = 0;
var cellsPoppedUpOnce = Array(CELLCOUNT);

for (i = 0; i < CELLCOUNT; i++)
{
// 	if (document.getElementById('selCell-' + i).className.indexOf("reservation") > -1)
// 	{
		cellsPoppedUpOnce[i] = 0;
// 	}
}

function selGetColumn(cellId)
{
    return (selGetCellNumber(cellId) % CAL_VISIBLE_DAYS);
}

function selGetCellNumber(id)
{
    cellId = id.toString().split("-");
    return parseInt(cellId[1]);
}

function clearHighlight()
{  
    if ((agent.indexOf("opera") + 1) || (agent.indexOf("safari") + 1))
    {
        return;
    }
    if (document.selection != undefined) // ie
    {
        document.selection.empty();
    }
    
    if (window.getSelection == undefined)
    {
    	// konqueror
    	return;
    }
    
    else if (window.getSelection() != undefined)
    { 
        obj = window.getSelection();
        obj.removeAllRanges();
    }
    return;
}    

function selIsValidNextCell(prv, cur)
{
    prv = selGetCellNumber(prv);
    cur = selGetCellNumber(cur);
    if (cur < prv - CAL_VISIBLE_DAYS)
    {
        //alert(0);
        return false;
    }
    if (cur > prv + CAL_VISIBLE_DAYS)
    {
        //alert(0);
        return false;
    }
    //alert(1);
    return true;
}

var selClearSelection_wait = false;

function selClearSelection()
{
	var cellClass = 'emptyCell';
	if (selClearSelection_wait)
	{
		cellClass = 'ajaxWaitCell';
		selClearSelection_wait = false;
	}
    changeCellRange(startTemp, lastCell, cellClass);
    isMouseDown = false;
    preventSelection = false;
    return;
}

function selActivate(id)
{
    selClearSelection(); // number of cells in table
    isMouseDown = true;
    startTemp   = id;
    startCell   = id;
    endCell     = -1;
    currentColumn = selGetColumn(id);
    lastCell = id;
    if (document.getElementById(id) != undefined)
    {
        document.getElementById(id).className = 'emptyCellHover';
    }
    return;
}

function selDeactivate(id)
{
    lastCell = id;
    if (endCell == -1)
    {
        endCell = startTemp;
    }
    currentColumn = selGetColumn(id);
    isMouseDown = false;
    preventSelection = false;
    clearHighlight();
    if (selGetCellNumber(startCell) > selGetCellNumber(endCell))
    {
        tmp = startCell;
        startCell = endCell;
        endCell = tmp;
    }
    /*
	var REDIRECT_URI = "?action=create_event&sCell=" + selGetCellNumber(startCell) + "&eCell=" + selGetCellNumber(endCell) + "&game=" + GAME_ID;

	if (PROVIDER_ID != undefined) {
		REDIRECT_URI += "&providerId=" + PROVIDER_ID;
	}
    params = REDIRECT_URI;
    refresh(params);
    */
    selClearSelection_wait = true;
    xajax_runAction("CreateHourEventAjaxAction", 
    				selGetCellNumber(startCell),
    				selGetCellNumber(endCell),
    				PROVIDER_ID,
    				GAME_ID);
	
    
    return;
}


function eventDataFieldRunXajax(type, callback, eventId)
{
	field = document.getElementById(type + "_value_" + eventId);
	xajax_runAction(callback,
					eventId,
					field.value);
    field.disabled = true;
    field.blur();
	return false;
}



function refresh(paramStr)
{   
    sURL = THISFILE;
    window.location.href = sURL + paramStr;
}

function changeCellRange(s, e, cName)
{ 
    if (s == -1 || e == -1 || cName == "")
    {
        return;
    }
    start = selGetCellNumber(s);
    end   = selGetCellNumber(e);
    if (end < start)
    {
        for (i = start; i >= end; i -= CAL_VISIBLE_DAYS)
        {
            if (document.getElementById("selCell-" + i) != undefined)
            {
                if (document.getElementById("selCell-" + i).className.indexOf('emptyCell') < 0
                    && document.getElementById("selCell-" + i).className != 'emptyCellHover')
                { 
                    //endCell = "selCell-" + i;
                    break;
                }
                document.getElementById("selCell-" + i).className = cName;
                endCell = "selCell-" + i;
            }
        }
    } else {
        startCell = "selCell-"+start;
        for (i = start; i <= end; i += CAL_VISIBLE_DAYS)
        {
            if (document.getElementById("selCell-" + i) != undefined)
            {
                if (document.getElementById("selCell-" + i).className.indexOf('emptyCell') < 0
                    && document.getElementById("selCell-" + i).className != 'emptyCellHover')
                { 
                    //endCell = "selCell-" + i;
                    break;
                }
                document.getElementById("selCell-" + i).className = cName;
                endCell = "selCell-" + i;
            }
        }
    }
    return;
}


function selTrySelect(id)
{
    clearHighlight();
    if (!isMouseDown
        || selGetColumn(id) != currentColumn
        || selGetCellNumber(id) == undefined)
    {
        // nappi ei oo pohjassa tai jotain hämäryyksiä...
        return;
    }
    if (document.getElementById(id) != undefined)
    {
        changeCellRange(startTemp, lastCell, 'emptyCell');
        changeCellRange(startTemp, id, 'emptyCellHover');
        lastCell = id;
    }
    clearHighlight();
    return;
}

/*
// Hide cell
function makePassive()
{
    if (currentActives.length == 0)
    {   
        return;
    }
    hideBlock   = true;
    hideCounter = new Date().getTime();
    //alert(mouseMoves);
    return;
}*/
/*
function _doPassive()
{
    mouseMoves++;
    if (hideBlock 
        && new Date().getTime() - hideCounter > 200
        && mouseMoves > 40)
    {
        _panicClear();
    }
    return;
}
*/
function _panicClear()
{
    for (i = 0; i < currentActives.length; i++)
    {
        if (document.getElementById(currentActives[i]) != undefined)
        {   //alert(i)
            document.getElementById(currentActives[i]).className = 'passive';
        }
    }
    currentActives = [];
    hideBlock = false;
    hideCounter = null;
}

function changeClass(id, cName)
{
    _panicClear();
    
    if (cName == 'active')
    { 
        if (hideBlock)
        {
            if (id == currentActives[currentActives.length - 1])
            {
                hideBlock = false;
            }
        }
        
        if (document.getElementById(id) != undefined)
        { 
			//alert(0);
            document.getElementById(id).className = cName;
//			alert(1);
			//alert(currentActives);
            currentActives[currentActives.length] = id;
//			alert(2);
            mouseMoves = 0;
        } else alert("UNDEF: "+id);
    } else { 
        if (document.getElementById(id) != undefined)
        {   
            document.getElementById(id).className = cName;
            
        }
    }
}

function activatePopupOnce(target, id)
{ 
// 	alert(document.getElementById(target).className);
    if (cellsPoppedUpOnce[id] == 0)
    {
        cellsPoppedUpOnce[id] = 1;
        _panicClear();
        if (hideBlock)
        {
            if (target == currentActives[currentActives.length - 1])
            {
                hideBlock = false;
            }
        }
        if (document.getElementById(target) != null && document.getElementById(target) != undefined)
        {
            document.getElementById(target).className = 'active';
//            currentActives.push(target);
            currentActives[currentActives.length] = target;
            mouseMoves = 0;
        }
    }
}

// not actually needed anymore
function changeBorderStyle(target, val)
{
    target.style.border = val;
}

function chConfig(id)
{
    confid = id;
}

function showEditWindow()
{
    window.open('settingseditor?confid=' + confid, 'editor');
}


function changeAnyStyle(id, className)
{
    if (document.getElementById(id) != undefined)
    {
        document.getElementById(id).className = className;
    }
    return;
}

// not actually needed anymore.
function centre()
{
    d = new Date();
    window.location.href = "index?startTime=" + Math.round(d.getTime()/1000);
}

function sendSubmit(formid)
{
	// Tähän tulee http requestilla kirjotettu submitti myöhemmin.
	// SAmalla vois laitaa index.php:n kuolemaan kaikkien javascriptillä tehtyjen pyyntöjen jälkeen
	// jotta ei turhaan siirrellä kalenterin dataa.
	if ( document.getElementById(formid) == null )
	{
		//alert('not found form id: ' + formid);
		return true;
	}
	document.getElementById(formid).submit();
	return false;
}

function checkChange(selectElement)
{
	//alert(selectElement);
	return false;
}

function copyPriceField(formId, 
                        targetFormId)
{
        form1 = null;
        form2 = null;
        if ((form1 = document.getElementById(formId)) == undefined
                || (form2 = document.getElementById(targetFormId)) == undefined)
        {
                return false;
        }

        form1.price.value = form2.price.value;
}

/** Shamelessly abusing xajax object.
 */
function poll_xajax(poll_uri,
					timeout,
					xajax_method,
					xajax_args)
{
	if (!xajaxLoaded)
		return false;
	r = xajax.getRequestObject();
	if (!r)
		return false;


	/* In IE, if the open method is called after setting the onreadystatechange 
	   callback, there will be a problem when trying to reuse the XHR object. 
	   To be able to reuse the XHR object properly, use the open method first 
	   and set onreadystatechange later. This happens because IE resets the 
	   object implicitly in the open method if the status is 'completed'.
	   
	   -- http://en.wikipedia.org/wiki/XMLHttpRequest
    */
	r.open("GET", poll_uri, true);
	
	r.onreadystatechange = function()
	{
		if (r.readyState != 4)
		{
			return;
		}
		if (r.status == 200)
		{
//		alert(r.responseText);
			if (r.responseText == 1)
			{
//				alert("Calling");
				xajax.call(xajax_method, xajax_args, 1);
				return;
			}
		}
		delete r;
		r = null;
//		alert('poll_xajax("' + poll_uri + '", ' + timeout + ', "' + xajax_method + '", ["' + xajax_args.join('", "') + '"])');
		setTimeout('poll_xajax("'
					+ poll_uri
					+ '", '
					+ timeout
					+ ', "'
					+ xajax_method
					+ '", ["'
					+ xajax_args.join('", "')
					+ '"])', timeout);
	}
	r.send(null);
}
/**
 * Copy to Clipboard script from dynamic-tools.net
 * Note! Modify also to matchIndexSuccess.php
 */
copyToClipboard = function(s)
{
    if( window.clipboardData && clipboardData.setData )
    {
        clipboardData.setData("Text", s);
    }
    else
    {
		//TODO sign the code to make it to work on Firefox
		return;
        // You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
		try {
	        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		} catch (e) {
			alert("To enable IP copy to clipboard, allow javascript for this site from Tools->Security->Allow Site");
        	return;
		}
        
        var clip = Components.classes["@mozilla.org/widget/clipboard;[[[[1]]]]"].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;

        // create a transferable
        var trans = Components.classes["@mozilla.org/widget/transferable;[[[[1]]]]"].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;

        // specify the data we wish to handle. Plaintext in this case.
        trans.addDataFlavor("text/unicode");

        // To get the data from the transferable we need two new objects
        var str = new Object();
        var len = new Object();

        var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

        var copytext=meintext;

        str.data=copytext;

        trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

        var clipid=Components.interfaces.nsIClipboard;

        if (!clip) return false;

        clip.setData(trans,null,clipid.kGlobalClipboard);      
    }
}
