/**
 * @class ep
 *
 */

/*
 * @copyright		© Copyright 2006-2010, epages GmbH, All Rights Reserved.
 *
 * @module			ep.openWindow
 */


define("ep/openwindow", [
	"jquery",
	"ep",
	"$dict!ep/dict",
	"$tmpl!ep/openwindow-mobilepreview",

	"ep/uri",
	"ep/ui/dialog",
	"ep/fn/busy"
], function ($, ep, epDict, tmplOpenwindowMobilepreview) {

	var dialogNode,
		iframeNode,
		lastDialog;

/*
 * @dictionary		ep.dict
 *
 * @translation		{Close}
 *								{GeneralSettings}
 *								{TooltipTextForMobileSettings}
 *								{useMobileTextEnabled}
 *								{useMobileTextDisabled}
 */

	ep.extend({ // open new window with predefined features
		/**
		 * Open url in a dialog with an embeded iframe.
		 *
		 * The `ep.destroyWindow()` method destroys the dialog/window instance which was created by `ep.openWindow()` or `ep.openMobileWindow()`.
		 *
		 * ### Dependencies
		 *
		 *  + `ep`
		 *  + `ep.uri`
		 *
		 * @method destroyWindow
		 * @static
		 * @member ep
		 *
		 * @since 6.16.0
		 */
		destroyWindow: function(){
			if(dialogNode){
				ep(dialogNode).uiDialog('destroy');
				dialogNode = undefined;
			}
		},
		/**
		 * Open url in a dialog with an embeded iframe.
		 *
		 * The `ep.openMobileWindow()` method opens a url embeded in an iframe inside a dialog which is styled as a smartphone. Additional to the URL the function can be
		 * called with to optional parameters.
		 * The first one (features) is used to hand over options which can be used to change defaults of the function/plugin,
		 * the second one (additional) to change/extend defaults for the dialog.
		 *
		 * ### Dependencies
		 *
		 *  + `ep`
		 *  + `ep.uri`
		 *
		 * @param {String} url A url to open in a window.
		 * @param {Object} [features] An object to hand over options for the widget.
		 * @param {Object} [additional] An object to hand over options for the dialog.
		 *
		 * @method openMobileWindow
		 * @static
		 * @member ep
		 *
		 * @since 6.16.0
		 */
		openMobileWindow: function(url, features, previewAdds){
			var mFeatures = $.extend({
					//ShopID: #Shop.ID,
					isMobilePreview: true,	// flag for mobile dialog
					showInfo: true,					// flag to decide if an info element should be shown in the mobile dialog
					width: 367,							// width of dialog
					height: 734,						// height of dialog
					iframe: {
						w: 320,								// width for embeded iframe
						h: 480								// height for embeded iframe
					},
					tooltipText: epDict.translate('TooltipTextForMobileSettings'),
					GeneralSettings: epDict.translate('GeneralSettings'),
					useMobileTextDisabled: epDict.translate('useMobileTextDisabled'),
					useMobileTextEnabled: epDict.translate('useMobileTextEnabled'),
					UseMobileSF: true
				}, features),
				mAdditionals = $.extend({
					dialogClass: 'ep-preview-mobile-storefront'
				}, previewAdds);

				ep.openWindow(url, mFeatures, mAdditionals);
		},
		/**
		 * Open url in a dialog with an embeded iframe.
		 *
		 * The `ep.openWindow()` method open a url inside a dialog with an embeded iframe. The behaviour of this function was changed in 6.14.0.
		 * In earlier version the url was opened in a seperate window. In future this function will get more params and features to remove the old
		 * epages function openWindow.
		 *
		 * Now a dialog with the width and height of nearly 99% of the visible area is opened. Inside this dialog the url is opened in an iframe.
		 * If the Url is on the same domain the dialog title is filed with the title of the opened document. This is not posibile with urls from
		 * outside due to the same-origin-policy.
		 *
		 * Another option to invoke this function is
		 *
		 *     ep.openWindow( url, [ features ], [ additional ] )
		 *
		 * Where `additional` is "An object to hand over options for the dialog".
		 *
		 * The `ep.openMobileWindow()` method opens a url embeded in an iframe inside a dialog which is styled as a smartphone. Additional to the URL the function can be
		 * called with to optional parameters.
		 * The first one (features) is used to hand over options which can be used to change defaults of the function/plugin,
		 * the second one (additional) to change/extend defaults for the dialog.
		 *
		 * The `ep.destroyWindow()` method destroys the dialog/window instance which was created by `ep.openWindow()` or `ep.openMobileWindow()`.
		 *
		 * ### Examples
		 * Open two URLs in a standard dialog
		 *
		 * JavaScript:
		 *
		 *     ep.openWindow( '?ViewAction=MyViewAction');
		 *
		 *     ep.openWindow( 'http://www.epages.de' );
		 *
		 * Open an URL in a mobile dialog
		 *
		 * JavaScript:
		 *
		 *     ep.openMobileWindow("http://www.epages.de", {
		 *       ShopID: 12345,
		 *       isMobilePreview: true,  // flag for mobile dialog
		 *       showInfo: true,         // flag to decide if an info element should be shown in the mobile dialog
		 *       width: 330,             // width of dialog
		 *       height: 651,            // height of dialog
		 *       iframe: {
		 *         w: 285,               // width for embeded iframe
		 *         h: 430                // height for embeded iframe
		 *       }
		 *     },{
		 *       dialogClass: 'ep-preview-mobile-storefront'  // additional CSS class for dialog
		 *     });
		 *
		 *
		 * ### Dependencies
		 *
		 *  + `ep`
		 *  + `ep.uri`
		 *
		 * @param {String} url A url to open in a window.
		 * @param {String} [windowName] A name for the window.
		 * @param {String} [features] A string of features for the window or a name of a predefined features.
		 *
		 * @method openWindow
		 * @static
		 * @member ep
		 *
		 * @since 6.11.0
		 */
		openWindow: function( url, features, previewAdds ){
			// if function was called by openMobileWindow
			if(ep.openWindow.caller === ep.openMobileWindow){
				// if already a dialog exists and it isn't a mobile dialog (1)
				if(lastDialog && lastDialog!==1){
					ep.destroyWindow();
				}
				// mark last dialog as mobile dialog
				lastDialog = 1;
			}else{
				// if already a dialog exists and it isn't a standard dialog (2)
				if(lastDialog && lastDialog!==2){
					ep.destroyWindow();
				}
				// mark last dialog as standard dialog
				lastDialog = 2;
			}

			var $win = $(window),
				o = $.extend({
				//iframe: undefined,
				//ShopID: undefined,					// shop id (used to link to general settings)
				//tooltipText: undefined,			// (string) tooltip text to point to mobile settings
				//GeneralSettings: undefined,	// (string) translation for general settings
					isMobilePreview: false,
					width: $win.width()-30,
					height: $win.height()-40,
					externalUrl: false
				}, features),
				additional = {};							// object for additional dialog options

			if(previewAdds !== undefined){
				$.extend(additional, previewAdds);
			}

			if(o.width > $win.width()){
				o.position = 'right';
			}
			else{
				o.position = 'center';
			}

			// get index of hash
			var index = url.lastIndexOf("#"),
				hash = "";

			// if hash exists
			if(index !== -1){
				hash = url.substring(index);
				url = url.substring(0, index);
			}

			if(!dialogNode){
				dialogNode = 	ep('<div>');
				iframeNode = $('<iframe>')
					.appendTo(dialogNode)
					.addClass('epOpenWindowIframe')
					.css({
						border: 'none',
						width: o.isMobilePreview ? (o.iframe.w+'px') : '100%',
						height: o.isMobilePreview ? (o.iframe.h+'px') : '99%'
					});

				// additional contents for storefront preview
				if(o.isMobilePreview){
					var elems = {};

					// initialize template for tooltip/info and close button and fill it with data
					$.extend(
						elems,
						tmplOpenwindowMobilepreview($.extend(o, {Close: epDict.translate( 'Close' )}))
							.appendTo(dialogNode)
							.tmplItem('elements')
					);

					elems.closeButton.on("click", function(){
						dialogNode.uiDialog('close');
					});
				}

				dialogNode
					.uiDialog($.extend({
						preventScroll: true,
						maxWidth: o.width,
						width: o.width,
						height: o.height,
						resizable: false,
						modal:	true,
						position: o.position,
						buttons: [
							{text: epDict.translate( 'Close' ), click: function(){ ep(this).uiDialog('close'); }}
						]
					}, additional ))
					.busy();
				iframeNode.on('load',function(){
					dialogNode.busy('hide');

					if(o.externalUrl){
						dialogNode.uiDialog('option','title',url);
					}else{
						if(iframeNode.length && 	iframeNode[0].contentDocument){
							try{
								var titleText = iframeNode[0].contentDocument.title;
								if(titleText){
									dialogNode.uiDialog('option','title',titleText);
								}
							}
							catch(e){
								console.warn('unable to read title from iframe');
							}
						}
					}
				});
			} else{
				dialogNode
					.busy()
					.uiDialog('open')
					.uiDialog('option',{
						'height': o.height,
						'width': o.width,
						'position': o.position
					});
			}

			// set source attribute of iframe to load URL
			iframeNode.attr('src', url + (/\?/.test(url) ? "&" : "?") + "_=" + $.now() + hash );
		}
	});

	return ep;

});