/**
 * @author Simon Matt
 * 
 * additions:
 * @author Ludwig Rafelsberger, accxmedia.com
 */

/*
 * Suckerfish Menu
 */
function sfMenu(navID) {
	var sfEls = document.getElementById(navID).getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

function navGallery(direction) {
	
	switch(direction) {
		
		case 'next':
			$('.boxGalleryIMGs ul').queue(function () {
				if (parseInt($('.boxGalleryIMGs ul').css('margin-left')) >= ($('.boxGalleryIMGs ul').width() - 87 * 6) * -1) {
					$(this).animate({
						'margin-left': (parseInt($('.boxGalleryIMGs ul').css('margin-left')) - 87) + 'px'
					});
				}
				if (parseInt($('.boxGalleryIMGs ul').css('margin-left')) == ($('.boxGalleryIMGs ul').width() - 87 * 6) * -1) {
					$('.boxGalleryArrowRight img').attr({
						'src': 'images/arrow_large_right_inactive.png'
					});
				}
				$('.boxGalleryArrowLeft img').attr({
					'src': 'images/arrow_large_left.png'
				});
		        $(this).dequeue();
		      });
			break;
			
		case 'prev':
			$('.boxGalleryIMGs ul').queue(function () {
				if (parseInt($('.boxGalleryIMGs ul').css('margin-left')) <= -87) {
					$(this).animate({
						'margin-left': (parseInt($('.boxGalleryIMGs ul').css('margin-left')) + 87) + 'px'
					});
				}
				if (parseInt($('.boxGalleryIMGs ul').css('margin-left')) == -87) {
					$('.boxGalleryArrowLeft img').attr({
						'src': 'images/arrow_large_left_inactive.png'
					});
				}
				$('.boxGalleryArrowRight img').attr({
					'src': 'images/arrow_large_right.png'
				});
				$(this).dequeue();
		      });
			break;
	}
	
}

var currentPage = 1;
function navLargeGallery(direction) {
	
	switch(direction) {
		
		case 'next':
			$('.boxLargeGalleryIMGs div').queue(function () {
				if (parseInt($('.boxLargeGalleryIMGs div').css('margin-left')) > ($('.boxLargeGalleryIMGs div').width() - 435) * -1) {
					$(this).animate({
						'margin-left': (parseInt($('.boxLargeGalleryIMGs div').css('margin-left')) - 435) + 'px'
					});
					$('#page' + currentPage).attr('src', 'images/page.png');
					$('#page' + ++currentPage).attr('src', 'images/page_selected.png');
				}
		        $(this).dequeue();
		    });
			break;
			
		case 'prev':
			$('.boxLargeGalleryIMGs div').queue(function () {
				if (parseInt($('.boxLargeGalleryIMGs div').css('margin-left')) <= -435) {
					$(this).animate({
						'margin-left': (parseInt($('.boxLargeGalleryIMGs div').css('margin-left')) + 435) + 'px'
					});
					$('#page' + currentPage).attr('src', 'images/page.png');
					$('#page' + --currentPage).attr('src', 'images/page_selected.png');
				}
				$(this).dequeue();
		    });
			break;
			
		default:
			$('.boxLargeGalleryIMGs div').queue(function () {
				$(this).animate({
					'margin-left': (-435 * (direction - 1)) + 'px'
				});
				$('#page' + currentPage).attr('src', 'images/page.png');
				$('#page' + direction).attr('src', 'images/page_selected.png');
				currentPage = direction;
				$(this).dequeue();
		    });
			break;
	}
	
}

function toggleAccordion(id, hdlInactive, hdlActive) {
	
	if($('#img_' + id).attr('src').indexOf("box2_open.png") != -1) {
		$('#img_' + id).attr({'src': 'images/box2_close.png'});
		$('#hdl_' + id).attr({'src': hdlActive});
		$('#li_' + id).toggleClass('opened');
		$('#li_' + id + ' .accordionBox').animate({'height': $('#li_' + id + ' .accordionBox .accordionContent').height() + 21 + 'px'});
	} else {
		$('#img_' + id).attr({'src': 'images/box2_open.png'});
		$('#hdl_' + id).attr({'src': hdlInactive});
		$('#li_' + id).toggleClass('opened');
		$('#li_' + id + ' .accordionBox').animate({'height': '0px'});
	}
}


function insertStellenMap(obj, address, bubble, marker) {
	
	// alte Karte verwerfen
	$("#stellenMap").fadeOut().remove();
	$("#berufsListe ul.active").animate({
		'padding-bottom': '10px'
	}).removeClass('active');
	
	// alle Stellen-Karte ausblenden
	$("#alleStellenMap").animate({
		'height': '0px'
	}, function() {
		$(this).fadeOut();
	});
	
	if (GBrowserIsCompatible() && $(obj).children('img').attr('src').indexOf('btn_closemap.png') == -1) {
		$('img[src$="btn_closemap.png"]').attr('src', 'images/btn_map.png').css('margin-bottom', '0');
		
		var geo = new GClientGeocoder();
		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "http://www.gluecksbringer.cc/images/marker_" + marker + ".png";
		baseIcon.iconSize = GSize(15, 22);
		baseIcon.shadow = '';
		
		geo.getLatLng(address, function(point) {
			if (!point) {
				alert(address + " leider nicht gefunden!");
			} else {
				
				$(obj).parent().parent().addClass('active').animate({
					'padding-bottom': '430px'
				}).after('<div id="stellenMap"></div>');
				$(obj).children('img').css('margin-bottom', '-9px').attr('src', 'images/btn_closemap.png');
				
				var map = new GMap2(document.getElementById("stellenMap"));
				map.setCenter(point, 13);
				map.setUIToDefault();
				
				// Set up our GMarkerOptions object
				markerOptions = {icon:baseIcon};
				
				var marker = new GMarker(point, markerOptions);
				map.addOverlay(marker);
				marker.openInfoWindowHtml(bubble);
			}
		});
	} else {
		$('img[src$="btn_closemap.png"]').attr('src', 'images/btn_map.png').css('margin-bottom', '0');
		$("#alleStellenMap").stop().fadeIn().animate({
			'height': '383px'
		});
	}
}

function addStelle(lat, lng, bubble, marker) {
	
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.image = "http://www.gluecksbringer.cc/images/marker_" + marker + ".png";
	baseIcon.iconSize = GSize(15, 22);
	baseIcon.shadow = '';
	
	// Set up our GMarkerOptions object
	markerOptions = {icon:baseIcon};
	
	var marker = new GMarker(new GPoint(lng, lat), markerOptions);
	mapAlleStellen.addOverlay(marker);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(bubble);
	});
}




/*
 * Jobticker functionality
 * 
 * animated Text, sequential AJAX loading, local storage
 *
 * @author Ludwig Rafelsberger, accxmedia.com
 */
var jobTicker = {
	
	i: 0,
	speedFactor: 18,
	tickerData: new Object(),
	loadTickerCount: 5,
	running: true,
	
	/**
	 * make jobticker move
	 */	
	moveHandler: function(){
		var target = $("div.tickerContainerInner div.tickerEntry").filter(":first").outerWidth(true);
		var distance = Math.round(target + ($("div.tickerContainerInner").position().left - $("div.tickerContainerOuter").position().left));
		if(jobTicker.running) { 
			$("div.tickerContainerInner")
				.animate({left: '-' + target},
				distance * jobTicker.speedFactor,
				"linear",
				function(){ jobTicker.switchHandler(); }
			);
		}
	},

	/**
	 * initial start of the movement
	 */
	moveInit: function() {
		jobTicker.running = true;
		jobTicker.moveHandler();
	}, 
	
	/**
	 * pause animation (for mouseover)
	 */
	pause: function() {
		$("div.tickerContainerInner").stop();
		jobTicker.running = false;
	},
	
	/**
	 * resume animation (for mouseleave)
	 */
	resume: function() {
		jobTicker.running = true;
		jobTicker.moveHandler();
	},
	
	/**
	 * switch to next active job entry
	 * this needs some steps to be done:
	 *   --> save the last entry (if not already in the storage)
	 *   --> remove it, adjust css
	 *   --> "count"
	 *   --> take care of getting new entries (loading via AJAX or locally)
	 *   --> animate next step
	 */
	switchHandler: function() {
		var innerContainer = $("div.tickerContainerInner");
		var firstElem = $(innerContainer).find("div.tickerEntry").filter(":first");

		// save the last entry (if not already in the storage)
		if(jobTicker.tickerData[$.jobTicker.randomOrder[jobTicker.i]] == 'undefined') {
			jobTicker.tickerData[$.jobTicker.randomOrder[jobTicker.i]] = {
				ID: $(firstElem).find("p.jobID").text(),
				company: $(firstElem).find("p.address span.company").text(),
				zip: $(firstElem).find("p.address span.zip").text(),
				city: $(firstElem).find("p.address span.city").text(),
				branch: $(firstElem).find("p span.branch").text()
			};
		}

		// remove it, adjust css
		$(firstElem).remove();
		$(innerContainer).css( {left: 0});
		
		// "count"
		jobTicker.i++;
		if(jobTicker.i >= $.jobTicker.randomOrder.length) 
			jobTicker.i = 0;

		// take care of getting new entries (loading via AJAX or locally)
		if(jobTicker.i % jobTicker.loadTickerCount == 0)
			jobTicker.getNextEntries();

		// animate next step
		if(($(innerContainer).children(".tickerEntry").size() >= 1) && jobTicker.running)
			jobTicker.moveHandler();
	}, 
	
	/**
	 * load next entries, either by AJAX or from local storage
	 */
	getNextEntries: function() {
		var ajaxEntries = [];
		for(i=0; i<jobTicker.loadTickerCount; i++) {
			cur = $.jobTicker.randomOrder[(jobTicker.i + i) % $.jobTicker.randomOrder.length];
			if(typeof(jobTicker.tickerData[cur]) == 'undefined') {
				ajaxEntries.push(cur);
			}
		}
		if(ajaxEntries.length > 0) {
			jobTicker.getAJAX(ajaxEntries, jobTicker.includeNextEntries, jobTicker.i);
		} else {
			jobTicker.includeNextEntries(jobTicker.i);
		}
		
	},

	/**
	 * fetch locally unknown entries from the server
	 */
	getAJAX: function(entries, insertCallback, position) {
		requestString = entries[0];
		for(i=1; i<entries.length; i++)
			requestString += "," + entries[i];
		$.getJSON("../ajaxServer.php", "query=getTickersByNrs&tickers=" + requestString, function(data){jobTicker.getAJAXSuccess(insertCallback, position, data);});
	}, 

	/**
	 * success handler for AJAX fetch
	 */
	getAJAXSuccess: function(insertCallback, position, jsonData) {
		for (i=0; i<jsonData.length; i++){
			jobTicker.tickerData[jsonData[i].position] = {
				ID:jsonData[i].ID,
				company: jsonData[i].company,
				zip: jsonData[i].zip,
				city: jsonData[i].city,
				branch: jsonData[i].branch
			};
		}
		insertCallback(position);
	},

	/**
	 * insert future job entries into the DOM
	 */
	includeNextEntries: function(position) {
		for(i=0; i<jobTicker.loadTickerCount; i++) {
			cur = $.jobTicker.randomOrder[(position + i) % $.jobTicker.randomOrder.length];
			$("div.tickerContainerInner").append(
				'<div class="tickerEntry">' +
				'<a href="/de/deinelehrstelle.html#' + jobTicker.tickerData[cur].ID + '" title="zur Lehrstelle springen">' +
				'<p class="address"><span class="company">' + jobTicker.tickerData[cur].company + '</span><br />' +
				'<span class="zip">' + jobTicker.tickerData[cur].zip +  '</span> <span class="city">' + jobTicker.tickerData[cur].city + '</span></p>' +
				'<p><span class="branch">' + jobTicker.tickerData[cur].branch + '</span></p>' +
				'</a>' + 
				'</div>'
			);
		}
	}
}
