/*
* jquery.downloadhelper.js
* Tchibo Coffee Service
* Plugin zur seitenweiten Ueberwachung von Downloadmanager-Links
* Author: Tim Isenheim
*/
(function($) {

	$.fn.downloadHelper = function(method) {

		var methods = {

			init : function(options) {
				this.downloadHelper.settings = $.extend({}, this.downloadHelper.defaults, options)
				var settings = this.downloadHelper.settings;
				return this.each(function() {
					var $element = $(this), // reference to the jQuery version of the current DOM element
						element = this;      // reference to the actual DOM element
					// Download-Helper init
					// Beim Klicken, Helper-Widget einblenden
					$(this)
						.click( function(event){
							event.preventDefault();
							var target = $(event.target);
							if( target.attr('id') == 'save-as-pdf'){
								helpers.processPDF(element, event, target);
							}
							else{
								helpers.buildActions(this, settings);
								methods.fadeInAt(settings.root, event);
							}
						});

					// Klick ausserhalb des Helper-Widgets > ausblenden
					$("body").click( function(e){
						var t = e.target;
						if( t.id != "download-helper" &&
							t.id != "add-to-downloadmanager" &&
							t.tagName != 'SPAN' &&
							$(t).attr('class') != "downloadmanager-file" &&
							$(t).attr('class') != "downloadmanager-add" &&
							$(t).attr('class') != "name")
						{
							$(settings.root).hide();
						}
					});
				});
			},

			fadeInAt : function(element, pos){
				$('#downloadhelper-results').hide();
				$('#downloadhelper-results p').hide();
				var offset = $(element).show().offsetParent().offset();
				// Ausgleich am Bildschirmrand
				var left = pos.pageX + $(element).width() + 32 + 16;
				var top = pos.pageY + $(element).height() + 32 + 16;
				var fixX = 0;
				var fixY = 0;
				if(left > $(window).width()){ fixX = $(element).width() + 32 + 16; }
				if(top > $(window).height()){ fixY = $(element).height() + 32 + 16; }
				$(element).css({'position': 'absolute', 'top': pos.pageY - offset.top + 16 - fixY , 'left':   pos.pageX - offset.left + 16 - fixX });
			},

			showResponse : function(data, name){
				if(data == 1){
					$('#downloadhelper-results .success #downloadfile-title').html(name);
					$('#downloadhelper-results .success').show();
					$('#downloadhelper-results p.link').show();
					methods.updateFileCount();
					// activate my tcs button
					$('#main-nav .secondary li').addClass('true');
				}
				else{
					$('#downloadhelper-results .error').show();
				}
				$('#downloadhelper-results').show();
				$('#downloadhelper-loading').css('height', '0px');
			},

			// Angezeigte Anzahl der Downloads aktualisieren
			updateFileCount : function(){
				$.ajax({
					url : '/dlm.php?action=getFilesCount',
					success : function(data){
						$('.downloadmanager-filecount').text(data);
						if(data==0){
							$('#download-all').fadeOut('fast');
							$('#nofiles').show();
						}
						else{
							$('#download-all').show();
							$('#nofiles').hide();
						}
					}
				});
			}

		}

		var helpers = {
			// JS-aquivalente Linkziele bauen und zuweisen
			buildActions : function(link, settings){
				var target = $(link).attr('href');
				var name = $(link).attr('title');
				var type = $(link).attr('rel');
				$('#'+settings.directlink).attr('href', target)
					.unbind('click')
					.bind('click', function(){
						// track file download
						wt.sendinfo({linkId: name});
					});
				$('#'+settings.addlink)
					.unbind('click')
					.bind('click', function(event){
						event.preventDefault();
						// Loading Icon-container einblenden
						$('#downloadhelper-loading').css('height', '30px');
						$.ajax({
							url : '/dlm.php?action=add&file=' + target + '&name=' + name + '&type=' + type,
							success : function(data){ methods.showResponse(data, name); }
						});
					});
			},

			// JS-aquivalente Linkziele bauen und zuweisen
			buildPDFDownloadActions : function(file, link, settings){
				var name = $(link).attr('title');
				$('#'+settings.directlink).attr('href', file)
					.unbind('click')
					.bind('click', function(){
						// track file download
						wt.sendinfo({linkId: name});
					});
				$('#'+settings.addlink)
					.unbind('click')
					.bind('click', function(e){
					e.preventDefault();
					// Loading Icon-container einblenden
					$('#downloadhelper-loading').css('height', '30px');
					$.ajax({
						url : '/dlm.php?action=add&file=' + file + '&name=' + name + '&type=page',
						success : function(data){ methods.showResponse(data, name); }
					});
				});
			},

			// Als PDF speichern via Ajax
			processPDF : function(element, e, target){
				$('#downloadhelper-loading').css('height', '30px');
				// Links verstecken
				$('#direct-download,#add-to-downloadmanager, #downloadmanager-help').hide();
				methods.fadeInAt($(element).downloadHelper.settings.root, e);
				//helpers.buildActions(this, settings);
				$.ajax({
					url : target.attr('href'),
					success : function(data){
						// Links mit fertigem PDF belegen
						helpers.buildPDFDownloadActions(data, target, $(element).downloadHelper.settings);
						// Loading GIF ausblenden
						$('#downloadhelper-loading').css('height', '0px');
						// Links erneut einblenden
						$('#direct-download,#add-to-downloadmanager, #downloadmanager-help').show();
						methods.fadeInAt($(element).downloadHelper.settings.root, e);
					}
				});
			}
		}

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error( 'Method "' +  method + '" does not exist in downloadHelper plugin!');
		}

	}

	$.fn.downloadHelper.defaults = {
		root: '#download-helper', // ID des Widgets
		directlink : '',
		addlink : ''
	}

	$.fn.downloadHelper.settings = {}

})(jQuery);
