/**
 * @class ep.local
 * 
 */

/**
 * Fix broken dojo gadgets with jQuery.
 * 
 * The `ep.local.dojoGadetFix` property is a stack of handles which fix broken dojo API methods.
 * 
 * In ePages StoreFront gadgets with hard-coded scripts are included that use nor the dojo API.
 * The `de_epages.externalcontent.dojoGadgetFix` module prevents these gadgets cause errors while simultaneously
 * providing the functionality using the jQuery API.
 * 
 * ### Dependencies
 * 
 *  + `jQuery.tmpl`
 *  + `jQuery.i18n`
 *  + `ep`
 *  + `ep.dict`
 *  + `de_epages.presentation.rss`
 * 
 * @method dojoGadetFix
 * @static 
 * @member ep.local
 * 
 * @since 6.11.2
 */

(function (root, factory, backwardapi) {

	define("de_epages/externalcontent/dojogadgetfix", [
		"jquery",
		"ep",
		"util/scope",
		"util/json",
		"util/base64",
		"util/string"
	], backwardapi.call(root) ? factory : {});

}(this, function ($, ep, scope, JSON, base64, str) {

	/*
	 * @dictionary		de_epages.externalcontent.dojoGadgetFix
	 *
	 * @translation		{WikiDescr}
	 *					{Search}
	 *					{fulltextbutton}
	 *					{gobutton}
	 */

	var callbackPath = "ep.local.dojoGadetFix",

		callbackScope = ep.local.dojoGadetFix = {},

		// Gadgets Rebuild
		classMap = {
			// RSS Gadget
			'epages.cartridges.de_epages.externalcontent.RSSReader': function( elem, o ){
				// lenght must be integer
				o.length = parseInt(o.length,10);
				o.textlength = parseInt(o.textlength,10);
				o.storeRoot = ep.config.storeRoot;
				o.onlyheadlines = o.onlyheadlines ? true : false;
				o.showlogo = o.showlogo ? true : false;
				o.stripimages = o.stripimages ? true : false;
				// fix if not pressed "update" in MBO
				if(o.formData){
					o.length = parseInt(o.formData.RSSReaderEntrys,10);
					o.textlength = parseInt(o.formData.RSSReaderLengthEntrys,10);
					o.onlyheadlines = o.formData.RSSReaderOnlyHeadlines == 'on' ? true : false;
					o.style = o.formData.RSSReaderSelectStyle;
					o.showlogo = o.formData.RSSReaderShowLogo == 'on' ? true : false;
					o.stripimages = o.formData.RSSReaderStripImages == 'on' ? true : false;
					if( !o.url && o.formData.RSSReaderFeedUrl ){
						o.url = unescape(o.formData.RSSReaderFeedUrl);
					}
				}
				// get required plugins and template

				require([
					"de_epages/presentation/rss",
					"$tmpl!de_epages/externalcontent/dojogadgetfix-rss-" + o.style,

					"jquery/i18n"
				], function (de_epages, tmplRss) {
					// load rss and get data of the feed
					new de_epages.presentation.Rss( o.url, function( feedData ){
						// set length to feed items
						if( feedData.items.length > o.length ){
							feedData.items.length = o.length;
						}
						feedData.o = o;
						// adjust feedData for tmpl using
						var rssBoxELem = elem.children('[id^=RSSFeed]'),
							rssFeedElems = tmplRss([ feedData ], {
								formatDate: function( date ){
									return $.i18n.formatDate( date, 'F' );
								},
								scrunchText: function( text ){
									return o.textlength>1 ? str.shrink( str.stripTags(text), o.textlength ) : text;
								}
							});
						// bind refresh handle
						rssFeedElems
							.find('img.LinkImage:first')
							.on('click',function(){
								classMap['epages.cartridges.de_epages.externalcontent.RSSReader']( elem, o );
							});
						// remove images
						if( o.stripimages ){
							rssFeedElems
								.find('.PostText img')
								.remove();
						}
						// add to page
						rssBoxELem
							.html('')
							.append( rssFeedElems );
					});
				});
			},
			// BingMap Gadget
			'epages.cartridges.de_epages.externalcontent.BingMap': function( elem, o ){
				var mapBoxElem = elem.children('[id^=map]'),
					id = mapBoxElem.attr('id').replace(/^map/,''),
					callbackId = 'bingMap_'+id,
					blockMap = function(){ return true; },
					mapObj,
					pushpin;
				// define bing map callback
				callbackScope[callbackId] = function(){
					mapBoxElem.css({ width:	o.width+'px', height:	o.heigth+'px' });
					mapObj = new VEMap('map'+id);

					// set an interval to ensure that the attachEvent method exists
					var interval = setInterval(function(){
						if((typeof VEMap !== undefined) && (document.getElementById("map"+id).attachEvent != undefined)){
							clearInterval(interval);
							mapObj.LoadMap( new VELatLong( o.centerLat, o.centerLng), (o.zoom.replace!==undefined ? parseInt(o.zoom, 10) : o.zoom), o.type );
							if( o.controls!==undefined ? o.controls==='true' : true ){
								mapObj.ShowDashboard();
							}
							if( o.mapFixed==='true' ){
								mapObj.AttachEvent( 'onmousedown',  blockMap );
								mapObj.AttachEvent( 'onmousewheel', blockMap );
							}
							if( o.markerText ){
								pushpin = new VEShape( VEShapeType.Pushpin, new VELatLong( o.markerLat, o.markerLng ) );
								pushpin.SetTitle(o.markerDesc);
								pushpin.SetDescription(o.markerText);
								mapObj.AddShape(pushpin);
							}
						}
					}, 10);
				};

				if( window.VEMap ){
					callbackScope[callbackId]();
				}
				else{
					// load bing map api script
					$('<'+'script type="text/javascript" src="'+location.protocol+'//ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2'+(location.protocol==='https:'?'&s=1':'')+'&onscriptload='+callbackPath+'.'+callbackId+'"></script>')
						.appendTo('head');
				}
			},
			// GoogleMap Gadget
			'epages.cartridges.de_epages.externalcontent.GoogleMap': function( elem, o ){
				var mapBoxElem = elem.children('[id]:first').html(''),
					id = mapBoxElem.attr('id'),
					callbackId = 'googleMap_'+id,
					mapObj;
				// define google map callback
				callbackScope[callbackId] = function(){
					mapBoxElem.css({ width:	o.width+'px', height:	o.heigth+'px' });
					mapObj = new google.maps.Map( mapBoxElem[0], {
						zoom:					parseInt(o.zoom,10),
						center:					new google.maps.LatLng(o.centerLat, o.centerLng),
						mapTypeId:				o.type || 'roadmap',
						navigationControl:		o.controls,
						mapTypeControl:			o.controls,
						draggable:				o.controls,
						disableDoubleClickZoom:	!o.controls,
						keyboardShortcuts:		o.controls,
						scrollwheel:			o.controls
					});
					$.each( o.markersPlain || [], function( i, marker ){
						var markObj = new google.maps.Marker({
								map:		mapObj,
								title:		marker.title,
								draggable:	false,
								position:	new google.maps.LatLng(marker.lat, marker.lng)
							}),
							markInfo = new google.maps.InfoWindow({
								content:	marker.infoText,
								size:		new google.maps.Size(50,50)
							});
						google.maps.event.addListener( markObj, "click", function(){
							markInfo.open( mapObj, markObj );
						});
					});
				};
				if( window.google && google.maps && google.maps.Map ){
					callbackScope[callbackId]();
				}
				else{
					// overwrite the already defined callback
					window.googleMapsCallback = function(){
						callbackScope[callbackId]();
					};
				}
			},
			// GoogleMap Gadget
			'epages.cartridges.de_epages.externalcontent.GoogleTranslate': function( elem, o ){
				var translateBoxElem = elem.children('[id^=google_translate_element]'),
					id = translateBoxElem.attr('id').replace(/^google_translate_element/,''),
					callbackId = 'googleTranslate_'+id;
				// define google map callback
				callbackScope[callbackId] = function(){
					new google.translate.TranslateElement({pageLanguage: ep.config.language}, translateBoxElem[0]);
				};
				if( window.google && google.translate && google.translate.TranslateElement ){
					callbackScope[callbackId]();
				}
				else{
					window['cb'+id] = function(){
						callbackScope[callbackId]();
					};
				}
			},
			// Wikipedia Gadget
			'epages.cartridges.de_epages.externalcontent.WikipediaDe': function( elem, o ){
				var translateBoxElem = elem.children('[id^=div]');

				require([
					"$dict!de_epages/externalcontent/dictionary"
				], function (gadgetFixDict) {
					// Prevent fail of dictionay test case:
					// gadgetFixDict.translate('Gadget')
					translateBoxElem.html( gadgetFixDict.parse( translateBoxElem.html() ) );
				});
			}
		},

		dataExp = /ep_info:([^ ]+)/;

	// Find Gadgets to run
	$(function(){
		$('.epItemContent')
			.each(function(){
				var elem = $(this),
					data = dataExp.exec( elem.attr('class') );

				if( data ){
					// can not use json encode by base64, because the encoded string maybe has line breaks
					data = data[1];
					data = base64.decode(data, true);
					data = (data)
						.replace(/\r/g, '\\r')
						.replace(/\n/g, '\\n');
					data = JSON.parse(data);

					if( classMap[ data.contentClass ] ){
						classMap[ data.contentClass ]( elem, data );
					}
				}
			});
	});

	return {};

}, function () {

	//
	// Reimplement old API dummies to prevent fails by old gadgets
	//

	var topDojo,
		topEpages,
		isDojo = false,
		isEpages = false,

		noop = function () {},
		proto = {prototype:{LOAD:noop}};

	//check if we can access a top property to avoid permission denied error
	try {
		topDojo = top.dojo;
	}
	catch (e) {
	}

	if (!this.dojo && !topDojo) {
		// dojo object
		this.dojo = {
			query: function(){
				return [];
			}
		};

		// dojo empty calls
		dojo.addClass
			= dojo.removeClass
			= dojo.hitch
			= dojo.trim
			= dojo.extend
			= dojo.mixin
			= dojo.create
			= dojo.addOnLoad
			= dojo.require
			= dojo.moduleUrl
			= noop;

		// prevent overwrite jQuery alias $
		if (typeof jQuery !== "undefined") {
			jQuery.noConflict();
		}

		this.$ = dojo.byId = document.getElementById;
	}
	else {
		isDojo = true;
	}

	//check if we can access a top property to avoid permission denied error
	try {
		topEpages = top.epages;
	}
	catch (e) {
	}

	if (!this.epages && !topEpages) {
		// epages object
		this.epages = {
			cartridges: {
				de_epages: {
					externalcontent: {
						GoogleMap:		proto,
						GoogleTranslate:proto,
						BingMap:		proto
					}
				}
			},
			io: {
				Translation: function () {
					return {
						replaceLanguageTags: function (str) {
							return str;
						}
					};
				}
			},
			vars: {
				Locale: {
					language: epConfig.language
				}
			}
		};
	}
	else {
		isEpages = true;
	}

	// prevent double build of gadgets (dojo and jQuery)
	return !(isDojo && isEpages);

}));

/*

// RSS START Example
	if(RSSReader == undefined)
		var RSSReader = {};
	dojo.addOnLoad(function () {
		if(document.getElementById("RSSFeed1297948721086")){
			dojo["require"]("epages.cartridges.de_epages.externalcontent.rssreader");
			RSSReader[1297948721086] = new epages.cartridges.de_epages.externalcontent.RSSReader();
			RSSReader[1297948721086].getData("http%3A%2F%2Fwww.faz.net%2Fs%2FRub%2FTpl~Epartner~SRss_.xml",50);
			document.getElementById("RSSFeed1297948721086").innerHTML = RSSReader[1297948721086].showData("classic",50,1,"on","","","1297948721086");
		}
	});
// RSS END

// BING-MAP START Example
	var SSLTail = location.protocol === "https:" ? "&s=1" : "";
	var scriptSrc = location.protocol + "//ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2" + SSLTail;
	dojo.create("script", { "type" : "text/javascript", "src" : scriptSrc},dojo.query("head")[0]);
	dojo.addOnLoad(function () {
	dojo["require"]("epages.cartridges.de_epages.externalcontent.bingmap");
		epages.cartridges.de_epages.externalcontent.BingMap.prototype.LOAD($('map1298035616385'), 'eyJ3aWR0aCI6IjMwMCIsImhlaWdodCI6IjMwMCIsImNvbnRlbnRDbGFzcyI6ImVwYWdlcy5jYXJ0cmlkZ2VzLmRlX2VwYWdlcy5leHRlcm5hbGNvbnRlbnQuQmluZ01hcCIsIm5hdkVsZW1lbnRJZCI6Ijc1NzEiLCJmb3JtRGF0YSI6eyJjaGVja01hcEZpeCI6WyIiXSwiY2hlY2tTaG93Q29udHJvbHMiOlsib24iXSwibWFwc2l6ZSI6WyIzMDA6MzAwIl0sImFkcmVzc2UiOlsiamVuYSBsZXV0cmFncmFiZW4iXSwiIjpbIlNlYXJjaCIsIkFwcGx5IiwiIl0sIm1hcmtlcnRleHQiOlsidGVzdCBvayBlcnJvciJdfSwicHJldmlldyI6Ii9XZWJSb290L1N0b3JlVHlwZXMvNi4xMS4xL1N0b3JlL0JPL2ljb25zL25hdmVsZW1lbnRfYmluZ21hcC5wbmciLCJ0aXRsZSI6ImJpbmdtYXAiLCJncm91cCI6IkdhZGdldCIsImF1dG9zdGFydCI6IiIsImxvb3AiOiIiLCJjZW50ZXJMYXQiOiI1MC45Mjg0NjU5NTMxNjAzMiIsImNlbnRlckxuZyI6IjExLjU4MzUzODA1NTQxOTkxNSIsImNvbnRyb2xzIjoidHJ1ZSIsInR5cGUiOiJyIiwiem9vbSI6IjE0IiwibWFya2VyTG5nIjoiMTEuNTgzNTE5IiwibWFya2VyTGF0IjoiNTAuOTI4NDUzIiwibWFya2VyRGVzYyI6ImplbmEgbGV1dHJhZ3JhYmVuIiwibWFya2VyVGV4dCI6InRlc3Qgb2sgZXJyb3IiLCJtYXBGaXhlZCI6ImZhbHNlIn0=');
	});
// BING-MAP END

// GOOGLE-MAP START Example
	dojo["require"]("epages.cartridges.de_epages.externalcontent.googlemap");
	window.googleMapsCallback = function(){
		epages.cartridges.de_epages.externalcontent.GoogleMap.prototype.LOAD($('1298044754766'), 'eyJ3aWR0aCI6IjQwMHB4IiwiaGVpZ2h0IjoiMzAwcHgiLCJjb250ZW50Q2xhc3MiOiJlcGFnZXMuY2FydHJpZGdlcy5kZV9lcGFnZXMuZXh0ZXJuYWxjb250ZW50Lkdvb2dsZU1hcCIsIm5hdkVsZW1lbnRJZCI6Ijc1NzAiLCJmb3JtRGF0YSI6eyJfZGF0YSI6eyJfZGF0YSI6eyJjb250cm9sc0NoZWNrQm94SGlkZGVuIjpbIiJdLCJjb250cm9sc0NoZWNrQm94IjpbIm9uIl0sIm1hcHNpemUiOlsiNDAwIHggMzAwIl0sImdvb2dsZW1hcHM6YWRkcmVzczowIjpbImplbmEsIGxldXRyYWdyYWJlbiJdLCJnb29nbGVtYXBzOnRleHQ6MCI6WyJoZWxsb1xuIl0sIiI6WyJBcHBseSIsIiIsIiIsIm9uIl19fX0sInByZXZpZXciOiIvV2ViUm9vdC9TdG9yZVR5cGVzLzYuMTEuMS9TdG9yZS9CTy9pY29ucy9uYXZlbGVtZW50X2dvb2dsZW1hcC5wbmciLCJ0aXRsZSI6Imdvb2dsZW1hcHMiLCJncm91cCI6IkdhZGdldCIsImF1dG9zdGFydCI6IiIsImxvb3AiOiIiLCJjZW50ZXJMYXQiOjUzLjA1Mzg3ODc3Mzk3Mzc4LCJjZW50ZXJMbmciOjEyLjYwODU5ODMxMjUwMDAwNywidHlwZSI6InJvYWRtYXAiLCJ6b29tIjo1LCJtYXJrZXJzUGxhaW4iOlt7ImluZm9Jc09wZW4iOmZhbHNlLCJsbmciOjExLjU4MzUzMDgwMDAwMDA2MiwibGF0Ijo1MC45MjgxMjc5LCJ0aXRsZSI6ImplbmEsIGxldXRyYWdyYWJlbiIsImluZm9UZXh0IjoiaGVsbG88YnIvPiJ9XSwiY29udHJvbHMiOnRydWV9');
	};
// GOOGLE-MAP END

// GOOGLE-TRANSLATE START Example
	window.cb1298297163916 = function(){
		dojo["require"]("epages.cartridges.de_epages.externalcontent.googletranslate");
		epages.cartridges.de_epages.externalcontent.GoogleTranslate.prototype.LOAD("1298297163916");
	};
// GOOGLE-TRANSLATE END

// WIKIPEDIA START Example
	dojo.require("epages.io.translation");
	var translation = new epages.io.Translation(dojo.moduleUrl("epages.cartridges.de_epages.externalcontent", "templates/wikipediade"), "auto");
	var sourceNode = document.getElementById("div1298298776787");
	// sourceNode.innerHTML = translation.replaceLanguageTags(sourceNode.innerHTML);
	function searchwikipediaSelection(){
		var selected;
		var localeCode = window.epages.vars.Locale.language;
		if (window.getSelection){
			selected = window.getSelection();
		}
		else if (document.getSelection){
			selected = document.getSelection();
		}
		else if (document.selection){
			selected = document.selection.createRange().text;
		}
		var link = "http://"+localeCode+".wikipedia.org/w/index.php?go=Go&search="+selected;
		var newwindow = window.open(link,"Wikipedia");
		newwindow.focus();
	}
// WIKIPEDIA END

*/