google.load('search', '1');
google.load("language", "1");
//google.load("feeds", "1");

var fdcUtils = new function() {

	// clickhandler an die Ãœbersetzungslinks attachen
	function initialiseTranslationClickHandlers () {
		
		jQuery("a.translate").click( function(event) {

				var article = jQuery(this).parent().parent().parent().parent().parent();

				var articleBody = article.find(".article-body");

				var anchor = articleBody.find("a[name]").attr("name");

				var dropdown = article.find(".csd");

				var translate_into = jQuery(this).attr("lang");

				if ( articleBody.length > 0 ) {
					fdcUtils.translateArticle(articleBody, translate_into, anchor, function(html){
						dropdown.replaceWith(html);
						articleBody.find("i.headline-en").hide();
					});
					
				}
		 	}
		);

	}

	function showPicasaSlideshow( feedURL, containerID ) {
	  var feed  = feedURL;
	  var options = {
	    displayTime:2000,
	    transistionTime:600,
	    scaleImages:true,
	    fullControlPanel : true
	  };
	  var ss = new GFslideShow(feed, containerID , options);
	}

	function showFeeds(feedURL, title, containerID) {
		// Create a feed control
	  	var feedControl = new google.feeds.FeedControl();
		feedControl.addFeed( feedURL , title );
		feedControl.draw(document.getElementById( containerID ));
	}

	// list sorting
	function sortListByRelevance () {
	    jQuery('ol.article-list>li').tsort('span.relevance', {order:"desc"});
		adjustZindex();
	}
	// list sorting
	function sortListByDate () {
		jQuery('ol.article-list>li').tsort('span.date', {order:"desc"});
		adjustZindex();
	}


	// Google site search einbauen
	function initialiseSiteSearch () {

		var searchControl = new google.search.SearchControl();

		// create a draw options object so that we
		// can position the search form root
		var options = new google.search.DrawOptions();
		options.setSearchFormRoot(document.getElementById("searchForm"));
		options.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);

		// Add in a WebSearch
		var webSearch = new google.search.WebSearch();
		webSearch.setUserDefinedLabel("freiheit.com - Suchergebnisse");
		// Restrict our search to pages from freiheit.com
		webSearch.setSiteRestriction('www.freiheit.com');

		// Add the searcher to the SearchControl
		searchControl.addSearcher(webSearch);

		// Set a callback so that whenever a search is started we will call searchStart
  		searchControl.setSearchStartingCallback(this, searchStart);

		//searchControl.setNoResultsString.NO_RESULTS_DEFAULT_STRING ;
		// tell the searcher to draw itself and tell it where to attach
		searchControl.draw(document.getElementById("searchResults"), options);

	}

	// Google site search einbauen
	function searchStart (searchControl, searcher, query) {
		searchControl.setNoResultsString("keine Ergebnisse fŸr <strong>\"" + query + "<strong>\"");
	}

	// unfolded translation options should not be overlaped by the following translation dropdown
	function adjustZindex () {
		var zIndex = 1000;
		jQuery('ul.csd').each(function (){
				$(this).css('z-index', zIndex);
				--zIndex;
			}
		);
	}


	// initialise Elements with JS-Functionality
	function initialiseJsInteractionElements () {
		jQuery('.csd').each(function (){
				$(this).css('display', 'block');
			}
		);
		
		jQuery('.sort>form').css('display', 'inline');

		jQuery('#searchForm').css('display', 'block');
	}
	
	// make translation boxes visible and enable it for IE
	function initialiseTranslationBoxDropdowns () {
		$('li.headlink').hover(
		function() {
				$('ul', this).css('display', 'block');
			},
		function() {
				$('ul', this).css('display', 'none');
			}
		);
	}

    // translate a given article into a specified language
    function translateArticle( articleBody, translate_into, anchor, callback ){

		var originalText = new Array();

		jQuery.each(articleBody.nodesContainingText(), function(){
				originalText.push($(this).text());
			}
		);

		

		var html = "<div class='csd'>Translation<br />"
		            	+ "<div style='vertical-align: middle; font-family: arial,sans-serif; font-size: 11px;'>"
							+ "powered by <img src='../img/google-small-logo.png' style='padding-left: 1px; vertical-align: middle;'/>"
						+ "</div>"
						+ "<div><a href='#"+ anchor +"' onClick='fdcUtils.resetTranslation();'>reset translation</a></div>"
					+ "</div>";

		translateArray(originalText, translate_into, function(translation) {
			var fill_in_counter = translation.length;
			jQuery.each( articleBody.nodesContainingText(), function(i, val){
					$(this).text(translation[i]);
					fill_in_counter--;
				}
			);
			if (fill_in_counter == 0) {
				window.location.hash="#"+anchor;
				callback(html);
			}

		});
    }
	
	function resetTranslation (anchor) {
			location.reload();
	}

	function translateArray( originalTextArray, translate_into, callback ) {

		var translatedTextArray = new Array();
		var translate_counter = originalTextArray.length;

		jQuery.each(originalTextArray, function (i, val){
			//console.log(val);
			google.language.translate(val, 'de', translate_into, function(result) {
			    if (result.translation) {
			        translatedTextArray[i] = result.translation;
					translate_counter--;
			    }
				if(translate_counter == 0){
					callback(translatedTextArray);
				}
			  });
		    }
		);
	}

	function initialiseTinyMCE() {
            $('textarea.tinymce').tinymce({
		    // Location of TinyMCE script
		    script_url : '/js/tiny_mce/tiny_mce.js',

			theme : "advanced",
			forced_root_block : false,
    		        relative_urls : false,

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontsizeselect,|,outdent,indent,blockquote,|,forecolor,backcolor",
			theme_advanced_buttons2 : "bullist,numlist,|,charmap,advhr,link,unlink,fdc_image,|,cut,copy,paste,pastetext,|,|,search,replace,|,undo,redo,|,styleprops,code",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",

			plugins : "safari,style,advhr,inlinepopups,media,searchreplace,contextmenu,paste,noneditable,xhtmlxtras,fdc_image"})
	}

	function initialiseDatePicker() {
	    $.extend(DateInput.DEFAULT_OPTS, {
		    stringToDate: function(string) {
			var matches;
			if (matches = string.match(/^(\d{2,2}).(\d{2,2}).(\d{4,4}).*$/)) {
			    return new Date(matches[3], matches[2] - 1, matches[1]);
			} else {
			    return null;
			};
		    },

			dateToString: function(date) {
			var month = (date.getMonth() + 1).toString();
			var dom = date.getDate().toString();
			if (month.length == 1) month = "0" + month;
			if (dom.length == 1) dom = "0" + dom;
			return dom + "." + month + "." + date.getFullYear() + " 8:00";
		    }
		});

	    $($.date_input.initialize);
	}

	function initPage () {
	    initialiseJsInteractionElements();

	    sortListByRelevance();

	    initialiseTranslationClickHandlers();

	    initialiseTranslationBoxDropdowns();

	    initialiseSiteSearch();


	    // Import feeds from hackers-with-attitude and put them in div#feeds
	    // showFeeds("http://hackers-with-attitude.blogspot.com/feeds/posts/default", "Blog: Hackers with Attitude", "feeds");
	    // Import image feeds from picasa and display them in div#picasaSlideshow
	    // showPicasaSlideShow("http://dlc0421.googlepages.com/gfss.rss", "picasaSlideshow");
	}

	function initBackoffice() {
	    initialiseTinyMCE();
	    initialiseDatePicker();
	}

	// Erreichbar von Aussen
	this.translateArticle = translateArticle;
	//this.showPicasaSlideshow = showPicasaSlideshow;
	this.translateArray = translateArray;
	this.resetTranslation = resetTranslation;
	this.adjustZindex = adjustZindex;
	this.searchStart = searchStart;
	this.sortListByDate = sortListByDate;
	this.sortListByRelevance = sortListByRelevance;

	this.initBackoffice = initBackoffice;
	this.initPage = initPage;
    }();

jQuery.fn.replaceWith = function(html){
	return this.after(html).remove();
}

jQuery(fdcUtils.initPage);


