/**
 * Script baut span Tags z.b. der EventTeaser zu links um
 */
eventHandler.addLoadEvent(function () {
    // veranstaltungen rechte seite verlinken
    var i=0, l, span, link, urlParts,
        events = document.getElementById('eventTeaserBox').getElementsByTagName('div'),
        linksToMarkt = document.getElementById('markt_widget_footer').getElementsByTagName('div');
    l=events.length;
    for (i;i<l;i++) {
        span = events[i].getElementsByTagName('span')[0];
        link = document.createElement('a');
        link.innerHTML = span.innerHTML;
        urlParts = span.className.split(' ');
        link.href='http://'+document.location.host+"/veranstaltung/"+urlParts[1]+'/'+urlParts[2]+'-'+urlParts[3]+'.html';
        link.title = span.title;
        span.parentNode.replaceChild(link, span);
    }
    // links zu markt.de setzen
    l=linksToMarkt.length;
    i=0;
    for (i;i<l;i++) {
        span = linksToMarkt[i].getElementsByTagName('span')[0];
        link = document.createElement('a');
        link.innerHTML = span.innerHTML;
        link.href=decodeURIComponent(span.title);
        link.target = '_blank';
        link.onmousedown=function(){xml_sclk(this);};
        link.title = span.className;
        span.parentNode.replaceChild(link, span);
    }

	// links zur galerie aus den stadtinformations-eintraegen
	if(document.getElementById('galleryThumbs')){
		var i=0, l, span, link, urlParts,
			galeriePics = document.getElementById('galleryThumbs').getElementsByTagName('li');
		l=galeriePics.length;
		for (i;i<l;i++) {
			if(galeriePics[i].getElementsByTagName('span')[0]){
				span = galeriePics[i].getElementsByTagName('span')[0];
				link = document.createElement('a');
				link.innerHTML = span.innerHTML;
				urlParts = span.className.split(' ');
				link.href='http://'+document.location.host+'/galerie-'+urlParts[1]+'.html?cid='+urlParts[2];
				link.title = span.title;
				span.parentNode.replaceChild(link, span);
			}
		}
	}

    var jobs = new Jobs();
    jobs.load('jobteaser.html?region='+encodeURIComponent(jobs.region));

	/*bookmarks im foot*/
	var locHrefUrlEnc = encodeURIComponent(document.location.href);
	var pageTitelUrlEnc = encodeURIComponent(document.title);
    var bkmLinks = {
		'0':'www.webnews.de/einstellen?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'16':'www.oneview.de/quickadd/neu/addBookmark.jsf?URL='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'32':'www.stumbleupon.com/submit?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'48':'linkarena.com/bookmarks/addlink/?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc+'&amp;desc=&amp;tags=',
		'64':'digg.com/submit?phase=2&amp;url='+locHrefUrlEnc+'&amp;bodytext=&amp;tags=&amp;title='+pageTitelUrlEnc,
		'80':'www.favit.de/submit.php?url='+locHrefUrlEnc,
		'96':'www.icio.de/add.php?url='+locHrefUrlEnc,
		'112':'www.mister-wong.de/index.php?action=addurl&amp;bm_url='+locHrefUrlEnc+'&amp;bm_notice=&amp;bm_description='+pageTitelUrlEnc+'&amp;bm_tags=',
		'128':'social-bookmarking.seekxl.de/?add_url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'144':'www.folkd.com/submit/[%locationHrefUrlEnc%]',
		'160':'www.linksilo.de/index.php?area=bookmarks&amp;func=bookmark_new&amp;addurl='+locHrefUrlEnc+'&amp;addtitle='+pageTitelUrlEnc,
		'176':'www.readster.de/submit/?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'192':'yigg.de/neu?exturl='+locHrefUrlEnc,
		'208':'del.icio.us/post?v=2&amp;url='+locHrefUrlEnc+'&amp;notes=&amp;tags=&amp;title='+pageTitelUrlEnc,
		'224':'www.favoriten.de/url-hinzufuegen.html?bm_url='+locHrefUrlEnc+'&amp;bm_title='+pageTitelUrlEnc,
		'240':'reddit.com/submit?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc
	};
	var bookmarks = document.getElementById("socialBookmarks");
	for (var i in bkmLinks) {
		link = document.createElement('a');
		link.href='http://'+ bkmLinks[i];
		link.style.backgroundPosition = '-'+i+'px 0';
		link.className= 'bookmarkSprite';
		link.target='_blank';
		bookmarks.appendChild(link);
	}
});


var Jobs = function () {
    this.init(this.insertResponse.bindTo(this));
};
Jobs.prototype = new HttpRequest();
Jobs.prototype.insertResponse = function (response) {
    var tmp = document.createElement('div'),
        targetNode = document.getElementById('jobTeaserBox'),
        s;
    response = JSON.parse(response);
    if (typeof response.script != 'undefined') {
        s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = response.script;
        document.body.parentNode.getElementsByTagName('head')[0].appendChild(s);
    }
    targetNode.innerHTML = response.content;
};

// lageplan anzeigen oder nicht
function lageplan(bdpLat,bdpLon,address){
    if(document.getElementById('lageplan').style.display == 'none'){
        document.getElementById('lageplan').style.display = 'block';
        if(bdpLat>0){
            setPos(bdpLat, bdpLon);
        }else{
            codeAddress(address);
        }
    }else{
        document.getElementById('lageplan').style.display = 'none';
    }
}


function setPos(bdpLat, bdpLon){
    var map;
    var myOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
    initialLocation = new google.maps.LatLng(bdpLat,bdpLon);
    map.setCenter(initialLocation);
    var marker = new google.maps.Marker({
        map: map,
        position: initialLocation
    });
}

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    var myOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

function calcRoute(end) {
    if(document.getElementById('lageplan').style.display == 'none'){
        document.getElementById('lageplan').style.display = 'block';
    }
    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;

    directionsDisplay = new google.maps.DirectionsRenderer();
    var myOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));

    var start = document.getElementById("fromAddress").value;
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

var PicBox = function (id, file) {
	file=file||'extraBilder';
    this.init(this.checkResponse.bindTo(this));
    this.load(file+'-'+id+'.html');
}

PicBox.prototype=new HttpRequest();

PicBox.prototype.showPics = function () {
    var ws = renderer.getWindowSize(),
		so = libScreen.getScrollOffset(),
        sheet = cssHandler.getSheet('contentCommon.css'),
        rule;
    rule = cssHandler.getRule('.lightBox', sheet);
    this.p = parseInt(rule.style.paddingLeft);
    this.pbw = parseInt(rule.style.borderWidth);
    rule = cssHandler.getRule('.lightBoxButton', sheet);
    this.bh = parseInt(rule.style.height);
    this.bw = parseInt(rule.style.width);

    this.current = 0;
    this.buttonOffset = 5;

    this.pic = renderer.createElement('img', {
        'src':this.response.pics[0].src,
        'className':'lightBox',
        'style':{
            'width':this.response.pics[this.current].width + 'px',
            'height':this.response.pics[this.current].height + 'px',
            'top':so.y+Math.floor((ws.height-this.response.pics[this.current].height)/2) - this.p - this.pbw + 'px',
            'left':so.x+Math.floor((ws.width-this.response.pics[this.current].width)/2) - this.p - this.pbw + 'px'
        }
    });
    this.off = renderer.createElement('div', {
        'className':'lightBoxButton'
    });
	eventHandler.addEvent(this.off, 'mousedown', function (e) {
		e=eventHandler.getEvent(e);
		e.preventDefault();
		this.pic.remove();
		var x = function () {
			if (this.response.pics.length > 1) {
				this.ffwd.remove();
				this.rew.remove();
			}
			this.off.remove();
			libScreen.dim();
		}.call(this)
	}.bindTo(this));
    with(this.off.style) {
        top=parseInt(this.pic.style.top)-this.bh+this.buttonOffset+'px';
        left=parseInt(this.pic.style.left)+this.response.pics[this.current].width+2*(this.p+this.pbw)-this.buttonOffset+'px';
    }
    if (this.response.pics.length > 1) {
        this.ffwd = renderer.createElement('div', {
            'className':'lightBoxButton lightBoxFFWD'
        });
		eventHandler.addEvent(this.ffwd, 'mousedown', function (e) {
			e=eventHandler.getEvent(e);
			e.preventDefault();
			this.getNext(true);
		}.bindTo(this));
        with(this.ffwd.style) {
            top=so.y+Math.floor((ws.height-this.bh)/2) + 'px';
            left=parseInt(this.pic.style.left)+this.response.pics[this.current].width+2*(this.p+this.pbw)+this.buttonOffset+'px';
        }
        this.rew = renderer.createElement('div', {
            'className':'lightBoxButton lightBoxREW'
        });
		eventHandler.addEvent(this.rew, 'mousedown', function (e) {
			e=eventHandler.getEvent(e);
			e.preventDefault();
			this.getNext(false);
		}.bindTo(this));
        with(this.rew.style) {
            top=so.y+Math.floor((ws.height-this.bh)/2) + 'px';
            left=parseInt(this.pic.style.left)-this.bw-this.buttonOffset+'px';
        }
    }
    libScreen.dim(false, 100, function () {
        this.off.renderIn(document.body);
        if (this.response.pics.length > 1) {
            this.ffwd.renderIn(document.body);
            this.rew.renderIn(document.body);
        }
        this.pic.renderIn(document.body);
    }.bindTo(this))
}

PicBox.prototype.getNext = function (ffwd) {
    if (ffwd) {
        if (this.current+1>=this.response.pics.length) {
            this.current = 0;
        } else {
            this.current++;
        }
    } else  {
        if (this.current-1<0) {
            this.current = this.response.pics.length-1;
        } else {
            this.current--;
        }
    }
    this.update();
}

PicBox.prototype.update = function () {
    var ws = renderer.getWindowSize(),
		so = libScreen.getScrollOffset();
    this.pic.onload = function () {
        this.pic.style.width = this.response.pics[this.current].width + 'px';
        this.pic.style.height = this.response.pics[this.current].height + 'px';
        this.pic.style.top=so.y+Math.floor((ws.height-this.response.pics[this.current].height)/2) - this.p - this.pbw + 'px';
        this.pic.style.left=so.x+Math.floor((ws.width-this.response.pics[this.current].width)/2) - this.p - this.pbw + 'px';

        this.off.style.top=Math.floor(parseInt(this.pic.style.top)-this.bh)+this.buttonOffset+'px';
        this.off.style.left=parseInt(this.pic.style.left)+this.response.pics[this.current].width+2*(this.p+this.pbw)-this.buttonOffset+'px';

        if (this.response.pics.length > 1) {
            this.ffwd.style.top=so.y+Math.floor((ws.height-this.bh)/2) + 'px';
            this.ffwd.style.left=parseInt(this.pic.style.left)+this.response.pics[this.current].width+2*(this.p+this.pbw)+this.buttonOffset+'px';

            this.rew.style.top=so.y+Math.floor((ws.height-this.bh)/2) + 'px';
            this.rew.style.left=parseInt(this.pic.style.left)-this.bw-this.buttonOffset+'px';
        }
    }.bindTo(this)
    var d = new Date();
    this.pic.src = this.response.pics[this.current].src+'?'+d.getTime();
}

PicBox.prototype.checkResponse = function (response) {
    try {
        this.response = JSON.parse(response);
        if (typeof this.response == 'object') {
            throw true;
        } else {
            throw false;
        }
    } catch (e) {
        if (e) {
            this.showPics();
        } else {
            alert('Fehler beim laden der Daten!.');
        }
    }
};

/**
 * call2call popup and Handler
 */
var Call2callWin=null;
function openCall2callWin(id) {
	if(Call2callWin && !Call2callWin.closed)
		Call2callWin.close();

	var width=540;
	var height=420;
	var left = (screen.availWidth - width) / 2;
	var top = (screen.availHeight - height) / 2;
	Call2callWin = open('call2call.html?id=' + id + '', '', 'width=' + width +',height=' + height +',left=' + left + ',top=' + top +',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=yes');
}
