function MakeStatic(klass, name){
	 klass[name] = function(){
			 if(!klass.instance){
					 klass.instance = new klass();
			 }
		     klass.instance[name].apply(klass.instance,arguments);
	 }
}

var overlay_zindex = 100;
var iframe_zindex = 900;
var dialog_zindex = 950;
var overlay_id_count = 1;
var iframe_id_count = 1;
var dialog_id_count = 1;
var BrowserVersion = Class.create({
    initialize: function(){
        this.IE6 = navigator.appVersion.include('MSIE 6.0');
		this.IE7 = navigator.appVersion.include('MSIE 7.0');
    }
});


var Dialog = Class.create({
    initialize: function(options, modifyContentDOM) {
        this.options = options;
		!this.options['name'] && (this.options['name']='default');
        this.cookieJar = new CookieJar('dialog' + this.options.name);
        this.browserVersion = new BrowserVersion();
        this.modifyContentDOM = modifyContentDOM;
        this._initializeOverlay();
        this._initializeContent();
        this._maintainState();
    },
    _maintainState: function() {
        if (this.options.stateful && this.options.stateful() && false == this.cookieJar.get('dialogclosed')) this.show();
    },
    _isAjaxDialog: function() {
        return null != this.options.url;
    },
    _initializeOverlay: function() {
        this._body().appendChild(this._background());
        // creating a form and appending display to it as IE fix
        if (!this._isAjaxDialog() && $(this.options.display)) {
            this._createForm();
            this._displayForm().appendChild($(this.options.display).remove());
        }
    },

    _createForm: function() {
       var action = this._action();
        var form = this._form();
        this._body().appendChild(new Element('form', {
            'id': 'displayForm',
            'method': form.method,
            'action': action,
            'enctype': form.enctype,
            'style': 'height:100%'
        }));
    },
    _displayForm: function() {
        return $('displayForm');
    },
    _form: function() {
        return $$('form').first();
    },
    _action: function() {
        return this._form().action.split('?').first();
    },
    _body: function() {
        return $$('body').first();
    },
    _background: function() {
        this.overlayid = 'overlay' + overlay_id_count;
		overlay_id_count++;
        var background = new Element('div', {
                                             'id': this.overlayid, 
                                             'class': 'dialogoverlay',
                                             'style' : 'background-color:#1B1B1B;' +
                                             'opacity:0.9;' +
                                             'display:none;' +
                                             'left:0;' +
                                             'position:absolute;' +
                                             'top:0;' +
                                             'z-index:' + overlay_zindex + ";"
        });
        return background;
    },
    _initializeContent: function() {
        this.dialogContentName = 'dialogcontent' + dialog_id_count;
		dialog_id_count++;
		
        if ($(this.options.display)) {
            this.dialogContentName = $(this.options.display).id + "_" + this.dialogContentName;
		}	
        this._body().appendChild(this._createContent());
		if(this.browserVersion.IE6) {
			this._body().appendChild(this._createIframe());
		}
        if (!this._isAjaxDialog()) {
            $(this.options.display).wrap(this._content());
        }
    },
    _createContent: function(suffix) {
        var position = this.browserVersion.IE7 ? 'absolute;' : 'absolute;';
		dialog_zindex += 5;
        var content = new Element('div', {
            'id': this.dialogContentName,
			'class': 'dialogcontent',
            'style':  'display:none;' +
					  'height:350px;' +
					  'position: absolute;' +
					  'width:350px;' +
					  'z-index:' + dialog_zindex + ";"
        });
		this._setCustomDimensions(content);
        return content;
    },
	_createIframe: function(suffix) {
		this.iframename = 'iframe_' + iframe_id_count;
		iframe_id_count++;
		
		iframe_zindex += 5;
		iframe_zindex += 5;
        var iframe = new Element('iframe', {
            'src': 'javascript:false',
			'id': this.iframename,
			'frameborder': '0',
			'allowtransparency': 'true',
			'class': 'iframe_layer',
            'style':  'display:none;' +
					  'background-color: transparent;' +		
					  'height:350px;' +
					  'position:absolute;' +                                                 
					  'width:1350px;' +
					  'top: 0;'+
					  'left:0;' +
					  'z-index:' + iframe_zindex + ";"
        });
		
 		iframe.style.height = this._content().style.height;
		iframe.style.width = this._content().style.width;
        return iframe;
    },
	_setCustomDimensions: function(element){
		 if (this.options.dimensions) {	
          element.style.height = this.options.dimensions.height;
          element.style.width = this.options.dimensions.width;
        }		  
	},
    show: function(link) {
        this._dialogOpened();
        this._attachModalDialogBehavior();
        this._showOverlay();
        if (link && Object.isElement($(link)) ) var parameters = $(link).readAttribute('parameters');
        if (parameters)
            this._showDialog(parameters.evalJSON());
        else
            this._showDialog();
		window.scrollTo(0,0);
    },
    _dialogOpened: function() {
        if (this.options.stateful) this.cookieJar.put('dialogclosed', false);
    },
    _dialogClosed: function() {
        if (this.options.stateful) this.cookieJar.put('dialogclosed', true);
    },
    _attachModalDialogBehavior: function() {
        var that = this;
        window.onresize = this._adustOverlayAndContent.bindAsEventListener(this);
        if (this.browserVersion.IE6) window.onscroll = this._adustOverlayAndContent.bindAsEventListener(this);
        document.observe('keypress', this._disableKeyUpKeyDown.bindAsEventListener(this));
    },
    _adustOverlayAndContent: function() {
        with (this) {
            _center();
            _resizeOverlay();
        }
    },
    _center: function() {
        var top_position = Math.round((document.viewport.getHeight() / 2) - (this._content().getHeight() / 2));
        var left_position = Math.round((document.viewport.getWidth() / 2) - (this._content().getWidth() / 2));
        
        //If content height/width is more than the viewport, position it 10px from top/left of the viewport.
        top_position = (top_position <= 0) ? 10 : top_position;
        left_position = (left_position <= 0) ? 10 : left_position;
        
        this._content().setStyle({ top: top_position + 'px' });
        this._content().setStyle({ left: left_position + 'px' });
	
		if (this.browserVersion.IE6) {
			this._iframe().setStyle({ top: top_position + 'px' });
			this._iframe().setStyle({ left: left_position + 'px' });
		}	
    },
    _resizeOverlay: function() {
        this._overlay().setStyle({ height: this._pageSize()[1] + 'px' });
        this._overlay().setStyle({ width: '100%' });
    },
    _disableKeyUpKeyDown: function(e) {
        if (!e) var e = window.event;
        if (e.keyCode == Event.KEY_DOWN ||
            e.keyCode == Event.KEY_UP ||
            e.keyCode == Event.KEY_PAGEDOWN) {
            if (this._isOverlayVisible()) {
                Event.stop(e);
            }
        }
    },
    _isOverlayVisible: function() {
        return this._content().visible();
    },
    _showOverlay: function() {
        this._resizeOverlay();
        Effect.Appear(this._overlay(), { from: 0.0, to: 0.6, duration: 0.3 });
    },
    _showDialog: function(parameters) {
		this._center();
        Effect.Appear(this._content(), { from: 0.6, to: 1.0, duration: 0.5 });

        var that = this;
        if (this._isAjaxDialog()) {
            this._showLoadingImage();
            var options = {
                method: 'get',
                parameters: { Command: that.options.command },
                onSuccess: that._handleResponse.bindAsEventListener(that)
            };
            parameters && Object.extend(options.parameters, parameters);
            new Ajax.Request(that.options.url, options);
        } else {
            this._updateNonAjaxContent();
        }
			
		if (this.browserVersion.IE6) {
			Effect.Appear(this._iframe(), { from: 0.6, to: 1.0, duration: 0.5 });
			
			//Hide all combo boxes on page except inside the dialogcontent overlay
			$$('select').each(function(combobox){
				if (that._elementChildOfDialogContent(combobox)==false){
					combobox.setStyle({
						visibility: 'hidden'
						
					});
				}		
			});
		}
    },
	_elementChildOfDialogContent: function(element)	{
		var elementPresent = false;
		element.ancestors().each(function(anscestor){
			if (anscestor.hasClassName('dialogcontent')) {
				elementPresent = true;
				return;
			}
		});
		return elementPresent;
	},
    _showLoadingImage: function() {
        this._content().innerHTML = "<div class='img_loading' >" +
                                            "<img src='skins/images/loading.gif'/>" +
                                         "</div>";
    },
    _handleResponse: function(transport) {
        this._updateContent(transport.responseText);
    },
    _updateContent: function(innerHTML) {
        with (this) {
            _content().hide();
			if (this.browserVersion.IE6){
				_iframe().hide();
			}
            _content().innerHTML = innerHTML + "<div id='closePopup'>" + _closeSpan() + "</div>";
            _modifyDOMandShow();
        }
    },
    _updateNonAjaxContent: function() {
        with (this) {
            _content().hide();
			if (this.browserVersion.IE6){
				_iframe().hide();
			}
            if (null == $(this.closeanchorid)) {
                this.closeImageElement = new Element('div', { 'id': 'closePopup' });
                this._content().insert({ top: this.closeImageElement });
                closeImageElement.innerHTML = _closeSpan();
            }
            _modifyDOMandShow();
        }
    },
    _closeSpan: function() {
        this.closeanchorid = "close" + this.dialogContentName;
        return "<span class='close'>" +
            "<a id=" + this.closeanchorid + " class='close-dialog' title='Close this window' >" +
            "close" + "</a>" + "</span>";
    },
    _modifyDOMandShow: function() {
        with (this) {
            if (modifyContentDOM) modifyContentDOM();
            _attachCloseEvent();
            _content().show();
			if (this.browserVersion.IE6) {
				_iframe().show(); 
			}
        }
    },
    _attachCloseEvent: function() {
        $(this.closeanchorid).observe('click', this._hideDialog.bindAsEventListener(this));
    },
    _hideDialog: function() {
        with (this) {
            _dialogClosed();
            _dettachModalDialogBehavior();
            _hideOverlay();
            _hideContent();
			if(this.browserVersion.IE6){
				_hideIframe();
				
				//Display the all combo boxes on the page on exit of the overlay.
				$$('select').each(function(combobox){
					combobox.setStyle({
						visibility: 'visible'
						
					});
				});
			}
        }
    },
    _dettachModalDialogBehavior: function() {
        // TODO: Should only stop observing specific functions
        document.stopObserving('keypress');
        window.onresize = function() { };
    },
    _hideOverlay: function() {
        Effect.Fade(this._overlay(), { duration: 0.2 });
    },
    _hideContent: function() {
        Effect.Fade(this._content(), { duration: 0.2 });
    },
	 _hideIframe: function() {
		Effect.Fade(this._iframe(), { duration: 0.2 });
    },
    _overlay: function() {
        return $(this.overlayid);
    },
    _content: function() {
        return $(this.dialogContentName);
    },
	_iframe: function() {
        return $(this.iframename);
    },
    _pageSize: function() {
        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;
        if (self.innerHeight) {	// all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = windowWidth;
        } else {
            pageWidth = xScroll;
        }

        arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
        return arrayPageSize;
    }
});

var SimpleSearchDialog = Class.create(Dialog, {
    initialize: function($super){
        $super({

                dimensions: {height: '', width: 'auto'}
                ,display:$('simpleSearch')
                ,name: 'extendedSearch'
                ,stateful:function(){
                     return 'true' == new String($('IsOverLayErrorPresent').value).toLowerCase();}
                }, 
                function(){ 
                            var cssPosition = this.browserVersion.IE6 ? 'absolute' : 'absolute';
                            var calPresent = ($$('.calIFrame').size()>0)?true:false;
                            if (calPresent)	{
                                $$('.calIFrame').each(function(element) {element.setStyle({position: cssPosition})});
								$$('.calIFrame').each(function(element) {element.setStyle({display: 'block'})});
                            }
                            $('simpleSearch').removeClassName('invisible');                            
                 });
    }
});

var FilterMatrixSimpleSearchDialog = Class.create(Dialog, {
    initialize: function($super){
        $super({
            dimensions : {height: '500px', width: '315px'}, 
            display : $('simpleSearch'),
            name: 'extendedSearch',
            stateful : function() {return ('true' == new String($('IsOverLayErrorPresent').value).toLowerCase())}}, 
            function() {
                $(this.dialogContentName).setStyle('height:570px;background:white;');
                $('simpleSearch').removeClassName('invisible');                
            });
    }
});

var TicketTermsAndConditionsDialog = Class.create(Dialog, {
    initialize: function($super){
        $super({
                  url:"JourneyAjaxRequest.ashx"
                  ,command:"GetTicketTermsAndConditions"
                  ,dimensions: {height: '337px', width: '725px'}
             }, 
             function(){
                $('button_major_bk').hide();
                $$('.RouteDescription').each(function(routeDescription){routeDescription.hide()});
                $('TicketRestrictionsHeaderDiv').setStyle('text-align:center;');
                $('InnerDiv').setStyle('height:250px;overflow-y:auto;overflow-x:hidden;padding:0px 20px 50px 20px;');
                $('TicketCategoryDiv0').setStyle('text-align:center;padding-bottom:10px;'); 
             }        
        );
    }
});

MakeStatic(TicketTermsAndConditionsDialog, 'show');

var StationFinderDialog = Class.create(Dialog, {
    initialize: function($super){
        $super({
         dimensions: { height: 'auto', width: '550px' },
         display: $('stationFinder'),
         stateful: function() { return false; }
        }, function(){
            loadGoogleMap();
        });
    }
});

var JourneyItineraryDialog = Class.create(Dialog, {
    initialize: function($super){
        $super({
              url:"JourneyAjaxRequest.ashx"
              ,command:"MatrixJourneyItinerary"
              ,dimensions: {height: '323px', width: '725px'}
             }, 
             function(){
             });
    }
});

MakeStatic(JourneyItineraryDialog, 'show');
