/**
 * Opel eMagazine javascript library: core
 * 
 * @projectDescription	Provides core extension functionalities
 * @namespace			opel
 * 
 * @author 				Heimann
 * @version				2011.03.01
 * @copyright			ACHTGRAU GmbH, 2010-2011
 */

/**
 * stop default event behaviour (mainly to stop processing links targets)
 * @param {DOM event} e - event object  
 */
opel.emag.lib.stopEvent = function(e) {
	e.preventDefault();
	e.stopPropagation();
};


/**
 * open a new window
 * @param {String} url - url to display in new window  
 */
opel.emag.lib.openWindow = function(url) {
	var win = window.open(url, 'opelemag');
	win.focus();
};


/**
 * call a mailto: location and prefill mail subject and body
 * @param {String} text - text to display in the mail subject  
 */
opel.emag.lib.sendMail = function(text) {
    var subject = document.title + " " + text;
    var body = document.title + " / " + $('meta[http-equiv=description]').attr('content') + " / <" + document.location.href + ">";

    document.location.href = "mailto:?subject=" + subject + "&body=" + body;
};


/**
 * replace placeholder in social bookmark url
 * @param {String} url - url to modify  
 */
opel.emag.lib.getSocialBookmark = function(url) {
    // get location and encode it
    var docLoc = document.location;
    var encLoc = encodeURIComponent(docLoc);

    // get document title and encode it
    var docTitle = document.title;
    var encTitle = encodeURIComponent(docTitle);

	url = url.replace(/%URL%/gi, encLoc);
	url = url.replace(/%TITLE%/gi, encTitle);
	
	return url;
};
/**
 * component: links
 * @description: methods to process different link characteristics on the page 
 */
(function(){
	
	var links = opel.emag.lib.addComponent('links', false, {
		
		/**
		 * init object
		 */
		init: function(){
			this.processExternalLinks();
		},
		
		/**
		 * @param {jQuery Object} elm
		 */
		processExternalLinks: function(elm) {
			var rootElm = elm || $(document.body);

			rootElm.find('a[rel="external"]').live({
				click: function(e) {
					opel.emag.lib.stopEvent(e);
					opel.emag.lib.openWindow($(this).attr('href'));
				},
				keydown: function(e) {
					// enter or space
					if (e.keyCode == 13 || e.keyCode == 32) {
						opel.emag.lib.stopEvent(e);
						opel.emag.lib.openWindow($(this).attr('href'));
					}					
				}
			});
		}
	});

	$(links.init());

})();
/**
 * component: twitter
 * @description: displays last tweet in head of the page
 */

(function(){
	
	var head_twitter = opel.emag.lib.addComponent('head_twitter', false, {
		
		/**
		 * init object
		 */
		init: function() {

			// get sharing config
			var config = opel.emag.lib.getComponent('head_twitter', true);

            // try to find username from link, if no username is present
            if(!config.username && config.link) {
                try { // split http://twitter.com/username
                    config.username = config.link.split('/')[3];
                }
                catch (e) { }
            }
			var username = config.username ? config.username : 'OPEL';
            var link = config.link ? config.link : 'http://twitter.com/' + username + '/';
			var format='json';
			var url='http://api.twitter.com/1/statuses/user_timeline/'+username+'.'+format+'?callback=?'; 
				$.getJSON(url,function(tweet){ // get the tweets
//					$("#last-tweet").html(tweet[0].text); // get the first tweet in the response and place it inside the div
				
					$('#last-tweet').html(function() {
					  	//var lnk = tweet[0].id;
						var text = tweet[0].text;
					  	return '<a href="'+link+'">' + text + '</a>';
					});
				});
			}
	});
	$(head_twitter.init());
})();
/**
 * component: stage
 * @description: displays aanother stage-container on click
 */

(function(){
	
	var stage = opel.emag.lib.addComponent('stage', false, {
		
		// auto rotation interval array
		interval: [],
  		
		/**
		 * init object
		 */
		init: function() {
			
			$('.stage').each(function(index) {
				
				var stg = $(this);
				var stageContainer = stg.find('.stagecnt');

				if (stageContainer.length > 1) {
					
					// hide all but the first container
					stageContainer.not(':eq(0)').hide().removeClass('hd');
		
					// mark the first list item
					stg.find('ul.switch li:eq(0)').addClass('current');
		
					// add click listener to all links
					stg.find('ul.switch li a').bind('click', function(event) {
						event.preventDefault();
	
						// clear auto rotation
						var currentStage = $(this).closest('.stage');
						window.clearInterval(stage.interval[stage.getCurrentStageId(currentStage)]);
		
						var li = $(this).parent();
						var newIndex = li.index();
						var currentIndex = stage.getCurrentIndex(currentStage);
						
						// only act, if current stage is not already visible
						if (!li.hasClass('current')) {
							stage.switchStage(currentStage, currentIndex, newIndex);
						}
					});
	
					var config = opel.emag.lib.getComponent('stage', true);
					var duration = 5000; // fallback
					var stageId;
		
					if (!$.isEmptyObject(config)) {
						
						for (var i in config) {
							if (stage.getCurrentStageId(stg) == i) {
								stageId = i;
								duration = config[i].duration;
							}
						}
					}

					// don't start autorotation, if duration is set to 0
					if (stageId != null && duration > 0) {
						stage.interval[stageId] = window.setInterval(function(){

							var curentStage = $('#' + stageId).closest('.stage');
							var currentIndex = stage.getCurrentIndex(curentStage);
							var newIndex = (currentIndex + 1) >= curentStage.find('ul.switch li').length ? 0 : currentIndex + 1;  
		
							stage.switchStage(curentStage, currentIndex, newIndex);
						}, duration);
					}
	
				}
	
				var globalConfig = opel.emag.lib.getComponent('global', true);

				if (!$.isEmptyObject(globalConfig) && !globalConfig.isAuthorMode) {
				
					// add click listener to stage container or to "more" link, if stage navigation is not present
					stageContainer.each(function(index){
						var url;
						
						// check if rotation list or "more"-link are present
						if (stg.find('ul.switch').length > 0) {
							url = stg.find('ul.switch li').eq(index).find('a').attr('href');
						}
						else 
							if (stageContainer.find('.cap .ic').length > 0) {
								url = stageContainer.find('.cap .ic').attr('href');
							}
						
						if (url) {
							$(this).click(function(){
								document.location.href = url;
							});
						}
					});
				}
			});

		},

		/**
		 * get index of list item marked as current
		 * @param {Object} stg - current stage object
		 * @return {Int} - index of current list item
		 */ 
		getCurrentIndex: function(stg) {
			return currentIndex = stg.find('ul.switch li.current').index();
		},

		/**
		 * get id of given stage object
		 * @param {Object} stg - current stage object
		 * @return {String} - id of stage
		 */ 
		getCurrentStageId: function(stg) {
			return stg.find('ul.switch').attr('id');
		},

		/**
		 * switch the stage content
		 * @param {Object} stg - current stage object
		 * @param {Int} currentIndex - index of list item marked as current
		 * @param {Int} newIndex - list item to be shown
		 */
		switchStage: function(stg, currentIndex, newIndex) {
			/* hide current stage */
			stg.find('.stagecnt').eq(currentIndex).stop(true, true).fadeOut('fast', function() {
				var list = stg.find('ul.switch li');
				// unmark current list-item
				list.eq(currentIndex).removeClass('current');
	
				// mark new current list item
				list.eq(newIndex).addClass('current');
	
				// show current stage
				stg.find('.stagecnt').eq(newIndex).fadeIn('slow');
			});
		}

	});

	$(stage.init());
})();
/**
 * component: video
 * @description: integrates the JWPlayer
 */

(function(){
	
	var video = opel.emag.lib.addComponent('video', false, {
		
		/**
		 * init object
		 */
		init: function() {
			// get sharing config
			var config = opel.emag.lib.getComponent('video', true);

			if (!$.isEmptyObject(config)) {

				$('body').append('<script type="text/javascript" src="' + config.script + '"></script>');

			    if (jwplayer) {
					for (var i in config) {
						if (i != 'script') {
							jwplayer(i).setup(config[i]);
						}
					}
				}
			}
		}
	});

	$(video.init());
})();
/**
 * component: toolbarnav
 * @description: toolbar navigation
 */

(function(){
	
	var toolbarnav = opel.emag.lib.addComponent('toolbarnav', false, {
		
		/**
		 * init object
		 */
		init: function() {
			// mail link
			toolbarnav.addMailEvent();

			// print document
			$('.toolbar-nav a.print-link').click(function(e) {
				opel.emag.lib.stopEvent(e);

			  	window.print();
			});

			// add facebook like button
			var config = opel.emag.lib.getComponent('toolbarnav', true);

			if (!$.isEmptyObject(config)) {

				var href = location.href.split(";")[0];
				var encHref = encodeURIComponent(href);

				var html = '<iframe ';
				var params = '?href=' + encHref;
				
				for (var i in config.params) {
					params += '&amp;' + i + '=' + config.params[i];
				}

				for (var j in config) {
					if (j == 'src') {
						config[j] += params;
					}
					
					if (j != 'params') {
						html += j + '="' + config[j] + '" ';
					}
				}
				
				html += '></iframe>';

				$('#tb-facebook').append(html);
			}

		},
		
		/**
		 * add a send mail event to link
		 */
		addMailEvent: function() {
			$('.toolbar-nav a.email-link').click(function(e) {
				opel.emag.lib.stopEvent(e);

				var config = opel.emag.lib.getComponent('global', true);
				var text = !$.isEmptyObject(config) ? config.mail.subject : ''; 

				opel.emag.lib.sendMail(text);
			});
		}

	});
	
	$(toolbarnav.init());

})();
/**
 * component: textimage
 * @description: image with lightbox functionality
 */

(function(){
	
	var textimage = opel.emag.lib.addComponent('textimage', false, {
		
		/**
		 * init object
		 */
		init: function() {
			$(".textimage .image-with-caption a").each(function() {
				var link = $(this);
				link.attr('rel', new Date().getDay()).colorbox();
				link.append('<span class="zoom"></span>');
			});
		}
		
	});
	
	$(textimage.init());

})();
/**
 * component: sharing
 * @description: social bookmarking services
 */

(function(){
	
	var sharing = opel.emag.lib.addComponent('sharing', false, {
		
		/**
		 * init object
		 */
		init: function() {
			// get sharing config
			var config = opel.emag.lib.getComponent('sharing', true);

			if (!$.isEmptyObject(config) && config.services) {

				var ul = document.createElement('ul');
				ul.className = 'h-nav';
			
				for (var i in config.services) {
					var service = config.services[i]; 
	
					var li = document.createElement('li');
					
					// create link
					var link = document.createElement('a');
					link.title = (config.bookmarkTitle ? config.bookmarkTitle : '') + ' ' + service.name;
					link.rel = 'external';
					link.href = opel.emag.lib.getSocialBookmark(service.url);

					// create img
					var img = document.createElement('img');
					img.src = service.img;
					img.alt = service.name;

					// concat the "DOM pieces" 
					link.appendChild(img);
					li.appendChild(link);
					ul.appendChild(li);
	
				}

				// add pretext to list, if available
				if (config.pretext) {
					$('.sharing').append('<p>' +  config.pretext + '</p>');
				}
				

				// add list to DOM
				$('.sharing').append(ul);
			}
		}
		
	});
	
	$(sharing.init());

})();
/**
 * component: teaser-rubric
 * @description: teaser for rubric page
 */

(function(){
	
	var teaserrubric = opel.emag.lib.addComponent('teaserrubric', false, {
		
		/**
		 * init object
		 */
		init: function() {
			// make complete taaser clickable
			$('.teaser-rubric').click(function() {
				document.location.href = $(this).find('.more a').attr('href');
			});

			// prevent double click, when clicking on a link inside the teaser
			$('.teaser-rubric .container-right .more a').click(function(e) {
				e.stopPropagation();
			});
		}
		
	});
	
	$(teaserrubric.init());

})();
/**
 * component: gallery
 * @description: displays a gallery in the body of the page
 */

(function(){
	
	var gallery = opel.emag.lib.addComponent('gallery', false, {
		
		/**
		 * init object
		 */
		init: function() {
			// get sharing config
			var config = opel.emag.lib.getComponent('gallery', true);

			if (!$.isEmptyObject(config)) {

				$('body').append('<script type="text/javascript" src="' + config.script + '"></script>');
				
				// Load the classic theme
			    Galleria.loadTheme(config.theme);
	
			    // Initialize Galleria
			    $('.gallery').galleria({
					width: 655,
					height: 350,
					transition: 'fade',
					showInfo: true,
					dataConfig: function(img) {
				        return {
	//						title: $(img).attr('alt'),
				           	description: $(img).siblings('.desc').html() // tell Galleria to grab the content from the .desc div as caption
				        };
				    }
				});	
			}
		}
	});
	$(gallery.init());
})();
/**
 * component: map
 * @description: Google Maps
 */
(function(){

	var map = opel.emag.lib.addComponent('map', false, {

		/**
		 * init object
		 */
		init: function() {
			if (typeof google != 'undefined' && google.maps) {
                
				// get googlemaps configs
				var config = opel.emag.lib.getComponent('map', true);
				
				if (!$.isEmptyObject(config)) {
					
					for (var i in config) {
						var gm = config[i];

						var latlng = new google.maps.LatLng(gm.mapcenter.latitude, gm.mapcenter.longitude);
		
						// set map options
						var options = {
							zoom: gm.zoom,
							center: latlng,
							mapTypeId: google.maps.MapTypeId[ gm.maptype ]
						};
	
						opel.emag.lib.extend(options, gm.controls);
	
						// create map
						var gmap = new google.maps.Map(document.getElementById(i), options);
						
						// show markers
						map.setMarkers(gmap, gm);
					}
				}
			}
		},

		/**
		 * add markers to the map
		 * @param {Object} map - google map
		 * @param {Object} config - google maps and marker config
		 */
		setMarkers: function(map, config) {
			for (var i = 0; i < config.markers.length; i++) {
				var markers = config.markers[i];

				var marker = new google.maps.Marker({
					position: new google.maps.LatLng(markers[1], markers[2]),
					map: map,
					title: markers[0],
					zIndex: markers[3]
				});
			}
		}
	});

	$(map.init());

})();
/**
 * component: news-teaser
 * @description: add a sliding mechanism to news-teaser
 */

(function(){
	
	var newsTeaser = opel.emag.lib.addComponent('newsTeaser', false, {
		
		/**
		 * init object
		 */
		init: function() {
			$('.sidebar .news-teaser').each(function() {
				var currentTeaser = $(this);

				if (currentTeaser.find('.teaser').length > 1) {
					newsTeaser.generateMarkup(currentTeaser);
					newsTeaser.addEvents(currentTeaser);
				}
			});
		},

		/**
		 * genaret DOM for news teaser rotation
		 * @param {Object} currentTeaser - news teaser to operate on
		 */
		generateMarkup: function(currentTeaser) {
			// prev/next links */
			currentTeaser.find('.box-inner').append('<span class="prev"></span><span class="next"></span>');

			// mark first teaser
			currentTeaser.find('.teaser').eq(0).addClass('current');
		},

		/**
		 * add click events to slide the teaser to the left/right
		 * @param {Object} currentTeaser - news teaser to operate on
		 */
		addEvents: function(currentTeaser) {
			currentTeaser.find('.prev').click(function() {
				var obj = currentTeaser.find('.teaser-container');
				var current = currentTeaser.find('.current');

				newsTeaser.rotateTeaserToBeginning(currentTeaser);

				current.removeClass('current').prev().addClass('current');

				obj.stop(true, true).animate({
					'left': parseInt(obj.css('left')) + current.width() + 'px'
				}, function() {
					newsTeaser.clearEnd(currentTeaser);
				});
			});

			currentTeaser.find('.next').click(function() {
				var obj = currentTeaser.find('.teaser-container');
				var current = currentTeaser.find('.current');

				newsTeaser.rotateTeaserToEnd(currentTeaser);

				current.removeClass('current').next().addClass('current');

				obj.stop(true, true).animate({
					'left': parseInt(obj.css('left')) - current.width() + 'px'
				}, function() {
					newsTeaser.clearBeginning(currentTeaser);
				});
			});
		},

		/**
		 * clone the last teaser and append it to the beginning of the teaser container
		 */
		rotateTeaserToBeginning: function(currentTeaser) {
			var clonedTeaser = currentTeaser.find('.teaser:last-child').clone(true);
			var container = currentTeaser.find('.teaser-container');
			container.prepend(clonedTeaser).css('left', parseInt(container.css('left')) - clonedTeaser.width() + 'px');			
		},

		/**
		 * clone the first teaser and append it to the end of the teaser container
		 */
		rotateTeaserToEnd: function(currentTeaser) {
			var clonedTeaser = currentTeaser.find('.teaser:first-child').clone(true).removeClass('current');
			currentTeaser.find('.teaser-container').append(clonedTeaser);
		},

		/**
		 * clear cloned teaser at the beginning
		 */
		clearBeginning: function(currentTeaser) {
			currentTeaser.find('.teaser:first-child').remove();
			currentTeaser.find('.teaser-container').css('left', '0');			
		},

		/**
		 * clear cloned teaser at the end
		 */
		clearEnd: function(currentTeaser) {
			currentTeaser.find('.teaser:last-child').remove();
		}

	});

	$(newsTeaser.init());
})();
/**
 * component: service-nav
 * @description: service navigation nested list
 */

(function(){
	
	var servicenav = opel.emag.lib.addComponent('servicenav', false, {
		
		/**
		 * init object
		 */
		init: function() {
			
			// add hover functionality
			$('.service-nav > ul > li').hover(
				function() {
					var menu = $(this).children('div');
					var width = menu.width();
					var top = Math.round((menu.outerHeight() - $(this).outerHeight()) / 2) * -1;
					menu.css('top', top + 'px').fadeOut(0).removeClass('hd').fadeIn(500);
				},
				function() {
					$(this).children('div').addClass('hd');
				}
			);
			
			// add sharing links
			servicenav.addMailEvent();

			var config = opel.emag.lib.getComponent('servicenav', true);

			if (!$.isEmptyObject(config)) {
				
				for (var i in config.services) {
					var service = config.services[i];

					$(service.selector).attr('href', opel.emag.lib.getSocialBookmark(service.url));
				}
			}
		},
		
		
		/**
		 * add a send mail event to link
		 */
		addMailEvent: function() {
			$('.service-nav a.email-link').click(function(e) {
				opel.emag.lib.stopEvent(e);

				var config = opel.emag.lib.getComponent('global', true);
				var text = !$.isEmptyObject(config) ? config.mail.subject : ''; 

				opel.emag.lib.sendMail(text);
			});
		}

	});
	
	$(servicenav.init());

})();

