// This will automatically AJAXify all forms that do not have a specified action
// The target attribute must be set to determine the file used for processing

function ajaxforms(){
    $('form').each(function(index) {
        if (!$(this).attr("action")){
            $(this).submit(function () {
                if (!$(this).attr("target")){
                    alert ('Error: Form has no action or target');
                } else {
                    $('input[type=submit]', this).attr('disabled', 'disabled');
                    var myForm = this;
                    var sendData = $(this).serializeArray();
                    sendData[sendData.length] = {
                        name: "ajaxform",
                        value: $(this).attr('name')
                    };
                    $.post('/?ajaxrequest='+$(this).attr("target"), sendData, function(){
                        $('input[type=submit]', myForm).removeAttr('disabled');
                    }, 'script');
                }
                return false;
            });
        }
    });
}

function reloadPage(redirect){
    if (redirect){
        //alert ('location: '+redirect);
        setTimeout('location.href = \''+redirect+'\';', 1000);
    } else {
        setTimeout('location.reload(true);', 1000);
    }
}

function ajaxupdaterfade(objectid,file,param,evalcode){
    new Ajax.Updater(objectid, '/?ajaxrequest='+file, {
        onSuccess: function(response) {
            new Effect.Opacity(objectid, {
                from: 0,
                to: 1.0,
                duration: 0.5
            });
            setTimeout("prepareInputsForHints();",500);
            if (evalcode){
                setTimeout(unescape(evalcode),500);
            }
        },
        method: 'post',
        parameters: {
            ajaxparams: param,
            ajaxtemplate: template_zone
        }
    });
}

function linker(objectid,file,param,evalcode){
    params = new Array();
    for(key in param)
    {
       params[params.length] = key+':'+param[key];
    }
    params[params.length] = 'template:'+file;
    var fadetime = 500;
    var d = new Date();
    $('#'+objectid).fadeOut(fadetime);
    var waiting = d.getTime();
    $.get('/?ajaxrequest=templateprinter', { ajaxparams: params.toString() }, function(data){
        var dn = new Date();
        var delayshow = dn.getTime() - waiting;
        setTimeout("$('#"+objectid+"').html(unescape('"+escape(data)+"'));$('#"+objectid+"').fadeIn("+fadetime+");initPage();",fadetime-delayshow);

    }, 'html');
}

function dynarequest(objectid,defaultpage,root){
    params = new Array();
    myHash = window.location.hash.substr(1).split('#');
    if (myHash[0] == ''){
        dynarequest = defaultpage;
    } else {
        dynarequest = myHash[0];
    }
    if (myHash[1]!='' && myHash[1]){
        params['data'] = myHash[1];
    }
    linker(objectid,root+dynarequest,params);
}

function logout(redirect){
    var sendData = new Array();
    sendData[0] = {
        name: "doaction",
        value: 'logout'
    };
    if (redirect){
        sendData[1] = {
            name: "redirect",
            value: redirect
        };
    }
    $.post('/?ajaxrequest=login', sendData);
}

function setCookie( name, value, expires, path, domain, secure ){
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/

    if ( expires ){
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function getCookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function hashlink(){
    myHash = str_split('#',window.location.hash.substr(1));

}

function limitChars(textid, limit, infodiv){
    var text = $('#'+textid).val();
    var textlength = text.length;
    if(textlength > limit)
    {
        $('#' + infodiv).html('Max. '+limit+' characters.');
        $('#'+textid).val(text.substr(0,limit));
        return false;
    }
    else
    {
        $('#' + infodiv).html(''+ (limit - textlength) +' characters left.');
        return true;
    }
}

(function(jQuery)
{
	jQuery.extend({
		noticeAdd: function(options)
		{
			var defaults = {
				inEffect: 			{opacity: 'show'},	// in effect
				inEffectDuration: 	600,				// in effect duration in miliseconds
				stayTime: 			3000,				// time in miliseconds before the item has to disappear
				text: 				'',					// content of the item
				stay: 				false,				// should the notice item stay or not?
				type: 				'notice' 			// could also be error, succes
			}

			// declare varaibles
			var options, noticeWrapAll, noticeItemOuter, noticeItemInner, noticeItemClose;

			options 		= jQuery.extend({}, defaults, options);
			noticeWrapAll	= (!jQuery('.notice-wrap').length) ? jQuery('<div></div>').addClass('notice-wrap').appendTo('body') : jQuery('.notice-wrap');
			noticeItemOuter	= jQuery('<div></div>').addClass('notice-item-wrapper');
			noticeItemInner	= jQuery('<div></div>').hide().addClass('notice-item ' + options.type).appendTo(noticeWrapAll).html('<p>'+options.text+'</p>').animate(options.inEffect, options.inEffectDuration).wrap(noticeItemOuter);
			noticeItemClose	= jQuery('<div></div>').addClass('notice-item-close').prependTo(noticeItemInner).html('x').click(function() { jQuery.noticeRemove(noticeItemInner) });

			// hmmmz, zucht
			if(navigator.userAgent.match(/MSIE 6/i))
			{
		    	noticeWrapAll.css({top: document.documentElement.scrollTop});
		    }

			if(!options.stay)
			{
				setTimeout(function()
				{
					jQuery.noticeRemove(noticeItemInner);
				},
				options.stayTime);
			}
		},

		noticeRemove: function(obj)
		{
			obj.animate({opacity: '0'}, 600, function()
			{
				obj.parent().animate({height: '0px'}, 300, function()
				{
					obj.parent().remove();
				});
			});
		}
	});
})(jQuery);


function initPage(){
    ajaxforms();
}

$(document).ready(function(){
    initPage();
});
