var calendars		= new Array();
var myAjaxReq       = new Array();
var pathSifr        = "hoshApp/jslib/sifr/fonts/";

// Checks if a call is in progress
function _isCallInProgress (ajaxRequest) {
    switch (ajaxRequest.readyState) {
        case 1: 
        case 2: 
        case 3:
            return true;
            break;
        default:
            return false;
            break;
    }
}

// Timeout message
function _showTimeoutMessage() {
    alert('Zeitüberschreitung!\n\nDer Server reagiert auf die Anfrage nicht.');
}

// Append responders for aborting previous calls and timeout
if (typeof(Ajax) == 'object') {
    Ajax.Responders.register( 
    {
        onCreate:       function (request) {
                            // Abort all previous ajax calls
                            for (i = 0; i < myAjaxReq.length; i++) {
                                if (_isCallInProgress(myAjaxReq[i].transport)) {
                                    myAjaxReq[i].transport.abort();
                                }
                            }
                            // Set timeout for this call
                            request['timeoutId'] = window.setTimeout(
                                                        function() {
                                                            if (_isCallInProgress(request.transport)) {
                                                                request.transport.abort();
                                                                _showTimeoutMessage();
                                                                if (request.options['onFailure']) {
                                                                    request.options['onFailure'](request.transport, request.json);
                                                                }
                                                            }
                                                        },
                                                        10000
                                                    );
                        },
        onComplete:     function (request) {
                            window.clearTimeout(request['timeoutId']);
                            Behaviour.apply();
                            initLightbox();
                        }
    }
    );
}

function base64decode (encStr)
{
    var base64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

    var bits;
    var decOut = '';
    var i = 0;
 
    for (; i < encStr.length; i += 4) {
        bits = (base64s.indexOf(encStr.charAt(i))    & 0xff) <<18 |
               (base64s.indexOf(encStr.charAt(i +1)) & 0xff) <<12 |
               (base64s.indexOf(encStr.charAt(i +2)) & 0xff) << 6 |
                base64s.indexOf(encStr.charAt(i +3)) & 0xff;
  
        decOut += String.fromCharCode((bits & 0xff0000) >>16, (bits & 0xff00) >>8, bits & 0xff);
    }
    
    if (encStr.charCodeAt(i -2) == 61) {
        return (decOut.substring(0, decOut.length -2));
    } else if(encStr.charCodeAt(i -1) == 61) {
        return (decOut.substring(0, decOut.length -1));
    } else {
        return(decOut);
    }
}

// Displays and hides the loading box
function displayLoadingBox (newState)
{
    if (newState === true) {
        // calculate 
        var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		Element.setLeft('loadingBox', (arrayPageSize[0] - 300) / 2);
		Element.setTop('loadingBox', ((arrayPageSize[3] - 100) / 2) - 20);
		Element.setTop('loadingOverlay', arrayPageScroll[1]);
        // stretch overlay to fill page and fade in
	    //new Effect.Appear('loadingOverlay', { duration: 0.2, from: 0.0, to: 0.8 });
	    Element.show('loadingOverlay');
	} else {
	    //new Effect.Fade('loadingOverlay', { duration: 0.5});
	    Element.hide('loadingOverlay');
	}
	
    // Display it
    elements = document.getElementsByClassName('loadingScreen');
    for (i = 0; i < elements.length; i++) {
        $(elements[i]).style.display = (newState) ? 'block' : 'none';
    }
}

function getCoordsForCenterWindow (width, height)
{
    coords      = new Array();
    coords[0]   = new Object();
    
    if (width > screen.width)
        width = screen.width;
    if (height > screen.height)
        height = screen.height;
    
    leftCord    = (screen.width - width) / 2;
    topCord     = (screen.height - height) / 2 - 30;
    
    coords[0]['width']  = width;
    coords[0]['height'] = height;
    coords[0]['left']   = leftCord;
    coords[0]['top']    = topCord;            
    
    return coords[0];
}

// AJAX: Load content with ajax (wrapper function)
function loadContent (elmId, url) 
{
    displayLoadingBox(true);

    url += '&renderContent=1';

    window.setTimeout('_loadContent(\'' + elmId + '\', \'' + url + '\')', 0);
}

// AJAX: Load content with ajax
function _loadContent (elmId, url)
{
    myAjaxReq.push(new Ajax.Updater(
                        elmId,
                        url,
                        {
                            method:'get',
                            onComplete:function() { 
                                displayLoadingBox(false);
                            },
                            onSuccess:_loadContentSuccess,
                            onFailure:_loadContentError
                        }
                  )
    );
}

// AJAX: Error function of "_loadContent"
function _loadContentError (response)
{
    displayLoadingBox(false);    
    
    alert('Es ist ein Fehler beim Laden der Seite aufgetreten. Bitte laden Sie die Seite erneut.\n\nError: ' + response.status + '\n' + response.statusText);
}

// AJAX: Success function of "_loadContent"
function _loadContentSuccess (response)
{
}

function MM_preloadImages() 
{
    var d = document; 
    
    if(d.images) { 
        if(!d.MM_p) 
            d.MM_p=new Array();
            
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; 
        
        for(i = 0; i < a.length; i++) {
            if (a[i].indexOf("#") != 0) { 
                d.MM_p[j] = new Image; 
                d.MM_p[j++].src=a[i];
            }
        }
    }
}

function openCleanWindow (url, width, height, left, top, scroll)
{
    window.open(url, 'myWindow', 'height=' + height + ',width=' + width + ',left=' + left + ',top=' + top + ',location=no,menubar=no,status=no,toolbar=no,scrollbars=' + scroll);
}

function openCenteredPopup (url, width, height)
{
    coords = getCoordsForCenterWindow(width, height);

    return openCleanWindow(url, coords['width'], coords['height'], coords['left'], coords['top'], 'yes');
}

function zoomImage (file, imgId, width, height)
{
    file    = base64decode(file);
    imgId   = base64decode(imgId);
    
    width   += 20;
    height  += 30;
    
    if (width > screen.width)
        width = screen.width;
    if (height > screen.height)
        height = screen.height;
    
    left    = (screen.width - width) / 2;
    top     = (screen.height - height) / 2 - 30;   
    
    if (!isNaN(imgId)) {
        openCleanWindow(file + '?core=displayImage&objId=' + imgId, width, height, left, top, 'yes');
    }
}

/*
    BEHAVIOUR
*/
var appRules = {
    // Delete icon
    'img.act:del' : function (element) {
        element.onclick = function () {
            return confirm('Möchten Sie das Objekt wirklich löschen?');
        }
    },
	// Calendar Date Select
	'img.act:cal' : function (element) {
		element.onmouseover = function () {
			this.style.cursor = 'pointer';
		},
		element.onclick = function () {
			parts = this.id.split('#');
			if (calendars[parts[1]]) {
				if (!calendars[parts[1]].closed) {
					calendars[parts[1]].close();
					return;
				}
			}
			
			// Get custom options from the id-field
			custom_options = new Hash();
			parts[2].substr(1, parts[2].length - 2).split(',').each(function(item) {
				item_parts = item.split(':');
				custom_options[item_parts[0]] = item_parts[1];
			});
			// Merge custom options with standard options
			// options = $H({
			// 	time: false,
			// 	year_range: 5,
			// 	close_on_click: true,
			// 	minute_interval: 5,
			// 		    }).merge(custom_options || {});
			options = custom_options;
			
			calendars[parts[1]] = new CalendarDateSelect($(parts[1]), options);
		}
	},
	// Highlight for language flags
    'img.act:lang' : function (element) {
        element.onmouseover = function () {
            element.src = element.src.replace(/_bw.gif/, '.gif');
        },
        element.onmouseout = function () {
            element.src = element.src.replace(/.gif/, '_bw.gif');
        }
    },
    // Every image on site 
    'img.act:vk_close' : function (element) {
        element.onclick = function () {
            // Get id from div and out of this the id of input field
            divId = element.parentNode.parentNode.parentNode.parentNode.parentNode.id;
            Element.hide(divId);
        },
        element.onmouseover = function () {
            this.style.cursor = 'pointer';
        }
    },
    'img.act:vk_open' : function (element) {
        element.onclick = function () {
            // Get raw id
            rawId = this.id.substr(5, (this.id.length - 5));
            // Hide all (without clicked) divs
            elements = document.getElementsByClassName('virtualKeyboard');
            for (i = 0; i < elements.length; i++) {
                if (elements[i].id != 'vk_' + rawId) {
                    Element.hide(elements[i]);
                }
            }
           	divId = 'vk_' + rawId;
            // Toggle clicked one
			if ($(divId).style.display == 'none')
				$(divId).style.display = 'block';
			else {
            	Element.toggle(divId);
			}
        },
        element.onmouseover = function () {
            this.style.cursor = 'pointer';
        }
    },
    // Hover effekt for virtual keyboard
    'td.vkLetter' : function (element) {
        element.onclick = function () {
            // Get id from div and out of this the id of input field
            divId = element.parentNode.parentNode.parentNode.parentNode.id;
            inputId = divId.substr(3, (divId.length - 3));
            // Add letter, focus and highlight
            $(inputId).value += this.innerHTML;
            Field.focus(inputId);
            new Effect.Highlight(inputId, { duration: 1.0 });
        },
        element.onmouseover = function () {
            Element.removeClassName(this, 'vkLetter');
            Element.addClassName(this, 'vkLetterHover');
            this.style.cursor = 'pointer';
        },
        element.onmouseout = function () {
            Element.removeClassName(this, 'vkLetterHover');
            Element.addClassName(this, 'vkLetter');
        }
    },
    // Hover effect for elements
    '.highlightOnHover' : function (element) {
        element.onmouseover = function () {
           	Element.addClassName(element, 'highlightRecord');
        },
        element.onmouseout = function () {
            Element.removeClassName(element, 'highlightRecord');
        }
    }
};

Behaviour.register(appRules);

Behaviour.addLoadEvent(
    function () { 
		alert('foo');
        // Select first form element in forms
        // if ($('formHighlight')) {
        //     Form.focusFirstElement('formHighlight');
        //     new Effect.Highlight(Form.findFirstElement('formHighlight'), {duration:1.5});
        // }
    }
);
