var baseUri;

function deleteBox( name, url ) {

    Dialog.confirm( lang['deleteQuestion'].gsub('%s', name ),
                   {
                       width:300,
                       okLabel: lang['butOK'],
                       cancelLabel: lang['butCancel'],
                       buttonClass: "dialogButtonClass",
                       ok:function(win) { location.href = url; }
                  });

}


function deleteAjaxBox( uId, name, url ) {
    Dialog.confirm( lang['deleteQuestion'].gsub('%s', name ),
                   {
                       width:300,
                       okLabel: lang['butOK'],
                       cancelLabel: lang['butCancel'],
                       buttonClass: "dialogButtonClass",
                       ok:function(win) { Dialog.closeInfo(); new AjaxResponse ( uId, url ); }
                  });
}

function sentMessageAjaxBox(uId, name) {
    Dialog.confirm( lang['messageQuestion'].gsub('%s', name ),
                   {
                       width:300,
                       okLabel: lang['butSent'],
                       cancelLabel: lang['butCancel'],
                       buttonClass: "dialogButtonClass",
                       ok:function(win) { Dialog.closeInfo(); openSendWindow(uId); }
                  });
}


function alertBox( alertString ) {
    Dialog.alert(alertString,
                 {width:300, height:100, okLabel: lang['butClose'],
                  ok:function(win) {debug("validate alert panel"); return true;}});

}

function changeReferer( id, target, param ) {
    p = param || null

	switch ( $F(id) ) {
		case 'idcodeacc':
			url = "admin/ajax/getCodeAccSelect";
			break;

		case 'idcntpers':
			url = "admin/ajax/getContactPersonSelect";
			break;
			
		default:
			url = "admin/ajax/getEmployeeSelect";
			break;
	}
	var a = new AjaxResponse ( target, url, { parameter:p, onComplete: function() { $('ajaxForm').hide(); } } );
}


function changeRefShortcut() {
    changeReferer("fRefererType", 'referer');
}

function changeEventPrice ( id, priceTarget ) {
    var eId = $F(id);
    $(priceTarget).value = prices[eId];
}

function changeEventTicket( eventid, target) {
    var url = 'admin/ajax/geteventtickets/id/' + $F(eventid);
    
    var a = new AjaxResponse ( target, url, { method: 'post' } );
}


function newEmployee ( target ) {
	var a = new AjaxResponse ( target, 'admin/ajax/getNewEmployeeForm', { onComplete: function() { $('ajaxForm').show(); } } );
}

function saveNewEmployee ( id ) {
    var el = document.getElementsByClassName("employee", id);
    var formParams = Form.serializeElements( el );

    var a = new AjaxResponse ( 'ajaxForm', 'admin/ajax/saveNewEmployee', { method: 'post', postBody: formParams, onComplete: saveNewEmployeeSuccess } );
}

function saveNewEmployeeSuccess(originalRequest) {
    if ( $('saveSuccess') ) {
        window.setTimeout("changeRefShortcut()", 2000);
    }
}

function newCodeAcc ( target ) {
	var a = new AjaxResponse ( target, 'admin/ajax/getNewCodeAccForm', { onComplete: function() { $('ajaxForm').show(); } } );
}

function saveNewCodeAcc ( id ) {
    var el = document.getElementsByClassName("codeacc", id);
    var formParams = Form.serializeElements( el );

    var a = new AjaxResponse ( 'ajaxForm', 'admin/ajax/saveNewCodeAcc', { method: 'post', postBody: formParams, onComplete: saveNewEmployeeSuccess } );
}


function showCodeList ( id, type ) {
    var url = 'admin/ajax/getCodeList';
    var oParam = { 'idevt': id }
    switch (type) {
        case 'all':
            oParam.type = 'all';
            break;

        default:
            oParam.type = 'confirmed';
            break;
    }
    var params = $H( oParam ).toQueryString();

    var a = new AjaxResponse ( 'codeList' + id, url, { method: 'post', parameters: params } );
}


function toggleCodeView( containerId, updateId, options ) {
	var cId = containerId || null;
	var uId = updateId || null;
	var o = options || {};

	var loadingImage = '<img src="/common/images/ajaxloader.gif" border="0" alt="0" />';

	if ( $(cId).visible() == true ) {
		$(uId).update( loadingImage );
		
		if(o.hide == true) {
            $(cId).hide();  
		}
	} else {
		$(cId).show();
		
	}

	new AjaxResponse ( uId,  o.url, o.params );
	
	return false;
}


function changeFormElementsByJSON( url ) {
    var ar = new Ajax.Request( url , {
      method:'get',
      onSuccess: function(transport){
         var result = transport.responseText.evalJSON();
         setDataFromObject( result );

         new AjaxResponse ( "formNav", "admin/ajax/getCompanyFormNav", { onComplete: function() {
             $('formNav').show();
             $('companyFields').removeClassName('companyForm');
             $('companyFields').addClassName('companyFormActive');
             clearSearchResults(); }
         } );

       }
    });
}

function setDataFromObject( o ) {
    var l = o.length;
    var i = 0;
    for ( var key in o ) {
        var e = $(key) || null;
        if ( e != null ) {
            e.value = o[key];

            if (key != 'fIdcntcmp') {
                e.disable();
            }
        }
    }
    clearSearchResults();
}


function newGivenCompany() {
    // set vars
    $('fIdcntcmp').value = "";
    $('fEditCmp').value = "false";

    var e = document.getElementsByClassName('contact', $('companyFields'));
    var eL = e.length;
    for ( var i = 0; i < eL; i++  ) {
        e[i].enable();
    }

    $('companyFields').removeClassName('companyFormActive');
    $('companyFields').addClassName('companyForm');

    $('formNav').update('<li>' + lang['newCompany'] + '</li>');
}


function editGivenCompany() {
    $('fEditCmp').value = "true";

    var e = document.getElementsByClassName('contact', $('companyFields'));
    var eL = e.length;
    for ( var i = 0; i < eL; i++  ) {
        e[i].enable();
    }
    $('companyFields').removeClassName('companyFormActive');
    $('companyFields').addClassName('companyForm');

    $('formNav').update('<li>' + lang['editCompany'] + '</li>');
}

function getEmployeeContacts( target, url, parameters, onComplete ) {

	// get given options
	var p = parameters || {};
	var o = onComplete || function () {};

	// add serialized items
	p.er = $F("fRecipients");
	p.eb = $F("fBcc");

	// generate params
    var params = $H( p ).toQueryString();

    var a = new AjaxResponse ( target, url, { method: 'post', parameters: params, onComplete: o } );
}

function selectAllMessageItems( classname, targetId, checkstatus ) {
	// check for several classes and run each classname
	var c = checkstatus || '';

	// w splits a string on every whitespace to an array
	$w(classname).each(
		function ( cname ) {
			var e = document.getElementsByClassName( cname, $(targetId) );
			for ( var i = 0; i < e.length; i++ ) {
				e[i].checked = c;
			}
		}
	);
}

function moveMarkedItems ( lists ) {
	lists.each(
		function( options ) {

			// get all elements by classname
			var e = document.getElementsByClassName( options.classname, $(options.sourceid) );

			// run through items
			for ( var i = 0; i < e.length; i++ ) {
				var d = e[i].descendants();
				var c = d[1];

				// if checked, move elements
				if ( c.checked == true ) {
					$(options.targetid).appendChild(e[i]);
				}
			}
		}
	);
}


function searchMessagePeople( term, type ) {
	//alert( $F(term) + ', ' + $F(type) );
	getEmployeeContacts( 'employees', 'admin/ajax/getMessageEmployeeList/type/' + $F(type) + '/s/' + $F(term) , false, createSortable);
	getEmployeeContacts( 'contact_persons', 'admin/ajax/getMessageContactPersonList/type/' + $F(type) + '/s/' + $F(term), false, createSortable);
}


var globalLoadContactStatus = 0;
function showAndLoadContacts( id ) {
	if ( $(id).visible() == false ) {
		$(id).show();
		// load contacts
		if ( globalLoadContactStatus == 0 ) {
			getEmployeeContacts( 'contact_persons', 'admin/ajax/getMessageContactPersonList', false, createSortable);
			globalLoadContactStatus = 1;
		}

	} else {
		$(id).hide();
	}
}


function getSentMessageList( ) {
	var idevt = $F('fEvent');

	var a = new AjaxResponse ( 'sentMessageRecipients', 'admin/ajax/getSentMessageList/idevt/' + idevt, { method: 'post' } );
}


/**
 * Ajax Response
 *
 * Handle a Ajax Response
 *
 * @param	string	targetId	html id of target element
 * @param	string	url			url to start ajax request
 * @param	object	params 		arguments for ajax request: method, errorFunction, urlparam
 */
var AjaxResponse = Class.create();
AjaxResponse.prototype = {
	initialize: function ( targetId, url, params ) {
		this.params = params || {};
		this.target = targetId;

		this.url = ( url.startsWith('http://') || url.startsWith('https://') ) ? url : baseUri + url;

		if ( !this.params.method ) {
		    this.params.method = 'get';
		}
		
		this.params.evalScripts = true;

		var ajax = new Ajax.Updater(
			{success: this.target},
			this.url,
			this.params
		);
	}
}
