var www = "http://fahrradkurier-leipzig.de";

var resource = "http://fahrradkurier-leipzig.de/ajax/";

/* config */

function request(prequest, element, postdata) {

    new Ajax.Request(

    resource + prequest,
    {

        method: 'post',
        postBody: postdata,
        evalScripts: true,
        onComplete: function(response) {
            $(element).update(response.responseText);
        }

    }

    );

    return true;

}

function spinner(element) {

    $(element).update('<img src="http://fahrradkurier-leipzig.de/style/spinner.gif" alt="loading..." class="spinner" />');

    return true;

}

function blackspinner(element) {

    $(element).update('<img src="http://fahrradkurier-leipzig.de/style/black-spinner.gif" alt="loading..." class="spinner" />');

    return true;

}

function urequest(prequest, element, postdata) {

    new Ajax.Request(

    resource + prequest,
    {

        method: 'post',
        postBody: postdata,
        evalScripts: true,
        onComplete: function(response) {
            $(element).update(response.responseText);
        }

    }

    );

    return true;

}

function rrequest(prequest, element, postdata) {

    new Ajax.Request(

    resource + prequest,
    {

        method: 'post',
        postBody: postdata,
        evalScripts: true,
        onComplete: function(response) {
            $(element).replace(response.responseText);
        }

    }

    );

    return true;

}

var zwischenhalte = 0;

function add_zwischenhalt() {

    zwischenhalte++;

    postdata = "zw=" + zwischenhalte;

    rrequest("add_zwischenhalt", "zwischenhalt", postdata);

}

function zwischenhalt() {

    zwischenhalte++;

    postdata = "zwischenhalt=" + zwischenhalte;

    rrequest("zwischenhalt", "zwischenhalt", postdata);

}

function kunde_wp_add() {

    zwischenhalte++;

    postdata = "zw=" + zwischenhalte;

    rrequest("kunde_wp_add", "zwischenhalt", postdata);

}

function public_wp_add() {

    zwischenhalte++;

    postdata = "zw=" + zwischenhalte + "&wpmode=public";

    rrequest("kunde_wp_add", "zwischenhalt", postdata);

}

function admin_wp_add(kunde) {

    zwischenhalte++;

    postdata = "zw=" + zwischenhalte + "&kunde_id=" + kunde;

    rrequest("admin_wp_add", "zwischenhalt", postdata);

}

function zwischenhalt_entfernen(id) {

    $('zwischenhalt' + id).replace('');

}

// '{kunde_addr}','{kunde_stadt}','{kunde_firma}','{kunde_name}',{kunde_fon})
function stammdaten(item, addr, stadt, firma, name, fon) {

    $(item + '_str').value = addr;
    $(item + '_stadt').value = stadt;
    $(item + '_firma').value = firma;
    $(item + '_ansprechpartner').value = name;
    $(item + '_telefon').value = fon;

}

function checkgeo(item) {

    postdata = "strasse=" + $F('auftrag_' + item + '_str') + "&stadt=" + $F('auftrag_' + item + '_stadt');

    request("checkgeo", "result" + item, postdata);

}

function setextra(id, km) {

    postdata = "tarif=" + id + "&km=" + km;

    request("extra_zweiterversuch", "extra_zweiterversuch", postdata);
    request("extra_naechstertag", "extra_naechstertag", postdata);
    request("extra_retour", "extra_retour", postdata);

}

function setid(text, li) {

    $('kunde_id').value = li.id;

}

function kunde_status_details(id) {

    postdata = "auftrag=" + id;

    rrequest("auftragdetails", "details", postdata);

}

function cal_update(datum) {

    postdata = "datum=" + datum;

    rrequest("cal", "cal", postdata);

}

function newkp() {

    postdata = '';

    rrequest("newkp", "additem", postdata);

}

function log_update() {

    postdata = "since=" + $('since').value + "&row=" + $('row').value;

    // alert(postdata);
    rrequest("readlog", "updater", postdata);

}

function tabselect(mother, active) {

    $$('#' + mother + ' a.active').invoke('removeClassName', 'active');
    $(active).addClassName('active');

    return true;

}

function toggleall(mother, child) {

    $$('#' + mother + ' span').invoke('hide');
    $(child).show();

    return true;

}

function wp_search(wp) {

    if ($F('wp_' + wp + '_mode') == "complete") {

        if ($F('wp_' + wp + '_str') == '') {

            alert('Straße eingeben!');
            $('wp_' + wp + '_str').focus();

        } else {

            urequest('kunde_wp_search', 'wp_' + wp, 'wp=' + wp + '&action=query&mode=complete&street=' + escape($F('wp_' + wp + '_str')) + '&number=' + escape($F('wp_' + wp + '_nr')) + '&postcode=' + escape($F('wp_' + wp + '_postcode')) + '&city=' + escape($F('wp_' + wp + '_stadt')) + '&country=' + escape($F('wp_' + wp + '_land')));

        }

    } else {

        if ($F('wp_' + wp + '_str') != '') {

            urequest('kunde_wp_search', 'wp_' + wp, 'wp=' + wp + '&action=query&mode=fast&street=' + escape($F('wp_' + wp + '_str')) + '&city=' + escape($F('wp_' + wp + '_stadt')));

        } else {

            alert('Straße eingeben!');
            $('wp_' + wp + '_str').focus();

        }

    }

}

function checkfull() {

    var check_ok = true;
    var dobreak = false;

    $$('input.notready').each(function(s) {
        if (dobreak) {
            return;
        }
        check_ok = false;
        wp = s.getValue();
        str = $('wp_' + wp + '_str').getValue();
        if (str == "") {
            alert("Bitte geben Sie eine Straße ein.");
            dobreak = true;
            $('wp_' + wp + '_str').activate();
        } else {
            wp_search(wp);
        }
    });

    if (check_ok) {

        $$('input.checkfull').each(function(s) {
            if (dobreak) {
                return;
            }
            if (s.getValue() == "" || s.getValue().replace(/^\s+/, '').replace(/\s+$/, '') == "") {
                alert("Sie haben das Feld Name/Firma nicht gefüllt.");
                dobreak = true;
                s.activate();
                check_ok = false;
            }
        });

    }

    return check_ok;

}

function onenter(e) {

    var characterCode;

    if (e && e.which) {
        characterCode = e.which;
    } else {
        characterCode = e.keyCode;
    }

    if (characterCode == 13) {

        return true;

    } else {

        return false;

    }

}

function intercept_update() {

    var dater = new Date();

    postdata = 'since=' + parseInt(dater.getTime() / 1000, 10);

    new Ajax.Request(

    resource + 'interceptions',
    {

        method: 'post',
        postBody: postdata,
        evalScripts: true,
        onComplete: function(response) {
            if (response.responseText == "<show />") {
                $('interception').removeClassName('inactive');
                $('interception').addClassName('active');
            }
            if (response.responseText == "<alert />") {
                $('interception').removeClassName('inactive');
                $('interception').addClassName('active');
                $('interception_sound').update('<embed src="' + www + '/style/alert.wav" hidden="true" autostart="true" loop="false"></embed>');
            }
            if (response.responseText == "<nothing />") {
                $('interception').removeClassName('active');
                $('interception').addClassName('inactive');
            }
        }

    }

    );

    return true;

}

var popovernum = 0;

function popover(element, content) {

    popovernum++;

    var id = 'popover' + popovernum;

    // popover(this, \''+content+'\');
    $(element).writeAttribute('onclick', '$(\'' + id + '\').replace(\'\');this.writeAttribute(\'onclick\',\'popover(this, \\\'' + content + '\\\');\');');

    var e_x = element.cumulativeOffset()[0];
    var e_y = element.cumulativeOffset()[1];
    var e_w = element.getWidth();
    var e_h = element.getHeight();

    var x = (e_x + (e_w / 2)) - 80;

    var y = (e_y + e_h);

    $(document.body).insert({
        bottom: new Element('div', {
            'id': id,
				'class': 'popover'
        })
    });

    $(id).update(content);

    $(id).setStyle({
        position: 'absolute',
        display: 'none',
        width: '140px',
        zIndex: 100,
        MozBorderRadius: '10px',
        MozBoxShadow: '0 0 15px #eee',
        backgroundColor: '#111',
        fontSize: '.9em',
        color: '#fff',
        padding: '10px',
        textAlign: 'center'
    });

    $(id).setStyle({
        top: y + 'px',
        left: x + 'px'
    });

    Effect.Appear(id, {
        duration: 0.5
    });

    return $(id);

}

function upopover(element, prequest, data) {

    popovernum++;

    var id = 'popover' + popovernum;

    $(element).writeAttribute('onclick', '$(\'' + id + '\').replace(\'\');this.writeAttribute(\'onclick\',\'upopover(this, \\\'' + prequest + '\\\', \\\'' + data + '\\\');\');');

    var e_x = element.cumulativeOffset()[0];
    var e_y = element.cumulativeOffset()[1];
    var e_w = element.getWidth();
    var e_h = element.getHeight();

    var x = (e_x + (e_w / 2)) - 80;

    var y = (e_y + e_h + 5);

    $(document.body).insert({
        bottom: new Element('div', {
            'id': id,
				'class': 'popover'
        })
    });

    $(id).setStyle({
        position: 'absolute',
        display: 'none',
        width: '158px',
        zIndex: 100,
        MozBorderRadius: '10px',
        MozBoxShadow: '0 0 15px #eee',
        backgroundColor: '#111',
        fontSize: '.9em',
        color: '#fff',
        padding: '10px 1px',
        opacity: '.8'
    });

    $(id).setStyle({
        top: y + 'px',
        left: x + 'px'
    });

    blackspinner($(id));

	if (data.length == 0) {
		
		data = 'popoverid='+id;
		
	} else {
		
		data = data+'&popoverid='+id;
		
	}

	urequest(prequest, $(id), data);

	Effect.Appear(id, {
		duration: 0.5
	});

	return $(id);

}

var notification = 0;

function showMessage(str, type) {
	
	notification++;
	
	var element = 'notification'+notification;
	
   $(document.body).insert({
		bottom: new Element('div', {
			'id': element
		})
	});
	
	$(element).update(str);
	
	if (type == 'warn') {
	
		$(element).setStyle({
			display: 'none',
			position: 'fixed',
			MozBorderRadius: '10px',
			MozBoxShadow: '0 0 15px #eee',
			backgroundColor: '#c00',
			border: '1px solid #900',
			fontSize: '1.6em',
			color: '#fff',
			padding: '20px',
			textAlign: 'center'
		});
		
	} else {
		
		$(element).setStyle({
			display: 'none',
			position: 'fixed',
			MozBorderRadius: '10px',
			MozBoxShadow: '0 0 15px #eee',
			backgroundColor: '#111',
			border: '1px solid #111',
			fontSize: '1.6em',
			color: '#fff',
			padding: '20px',
			textAlign: 'center'
		});
		
	}
			
   var browser_width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
   var browser_height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
  
	var dims = $(element).getDimensions();

	var y = (browser_height - dims.height) / 2;
	var x = (browser_width - dims.width) / 2;
	
	// var offset = document.viewport.getScrollOffsets();
	
	$(element).setStyle({
		position : 'fixed',
		top : y + 'px',
		left : x + 'px' 
	});	

	Effect.Appear(element, { duration: 0.5 });
	
	window.setTimeout('Effect.Fade(\''+element+'\', { duration: 0.5 });', 2500);
	window.setTimeout('$(\''+element+'\').replace(\'\');', 3000);
		
}

function warn(str) {
	
	showMessage(str, 'warn');
	
}

function info(str) {
	
	showMessage(str, 'info');
	
}
