var Utils = {
	prepareForRefresh : function(elementId) {
		$(elementId)
				.set('html',
						'<div class="ajaxLoadingContent"><image src="/img/ajax-loader.gif"/><\div>');
	},
	prepareForContentRefresh : function() {
		Utils.prepareForRefresh('content-refresh');
	},
	contentRefreshCallback : function(response) {
		Utils.refreshContent(response);
	},
	execScripts : function(resText) {
		var si = 0;
		while (true) {
			console.log(resText);
			console.log(si);
			var ss = resText.indexOf("<" + "script" + ">", si);
			console.log(ss);
			var offset = 8;
			if (ss == -1) {
				ss = resText.indexOf("<" + "script type=\"text/javascript\""
								+ ">", si);
				offset = 31;
				console.log(ss);
				if (ss == -1)
					return;
			}

			var se = resText.indexOf("<" + "/" + "script" + ">", ss);
			console.log(se);
			if (se == -1) {
				return;
			}

			si = se + 9;
			// TODO: Trim
			var sc = resText.substring(ss + offset, se);
			console.log(sc);
			eval(sc);
		}
	},
	refreshContent : function(innerHTML) {
		var contentDiv = $('content-refresh').set('html', innerHTML);
		try {
			Utils.execScripts(innerHTML);
		} catch (e) {
			alert(e);
		}
	},
	toggleFieldAnnotation : function(container) {
		var fieldAnnotation = $(container).getElements('p.fieldAnnotation')[0];
		if (fieldAnnotation)
			fieldAnnotation.style.display = fieldAnnotation.style.display == ''
					? 'none'
					: '';
	},
	htmlToTableRows: function(str, selector) {
		return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElements(selector ? selector : 'tr');
	}
}

/*
 * Mixin class for pages that have a course mapper button.
 */
Utils.HasCourseMapperButton = new Class({
	/**
	 * If there is a course mapper button, initialize it to launch the
	 * course mapper.
	 */
	hookupCourseMapperButton : function() {
		var _this = this;
		if (this.mapCourseButton)
			this.mapCourseButton.addEvent('click', function(e) {
				e.stop();
				var courseIdElement = $('course_id');
				_this.launchCourseMapper(courseIdElement
						? courseIdElement.get('text')
						: -1);
			});
	},
	launchCourseMapper : function(courseId) {
		var jnlpUrl = window.location.protocol + '//'
				+ window.location.host + REQUEST_CONTEXT
				+ '/course-mapper/CourseMapper.jnlp?GolfCourseID='
				+ courseId;
		if (!deployJava.isWebStartInstalled('1.5')
				&& deployJava.installLatestJRE())
			deployJava.launch(jnlpUrl);
		else
			deployJava.launch(jnlpUrl);
	}
});

Utils.Popup = new Class({
    Implements: [Options],
    /*
     * Options:
     * url - The url of the page to load in the overlay
     * makeInvisible - Do not actually show the contents of the overlay.  This is useful if your afterLoad function needs to do some work
     *                first (ex, position the overlay to fit the content size)
     * onClose - The function to call when the overlay is closed.
     * afterLoad - An array of functions to be called in order after the overlay loads.
     */
    options: {
        /*
         url: null,
         makeInvisible: null,
         overlayBorderClass: null, */
		onClose: $empty,
		afterLoad: $empty
    },
    initialize: function(options){
        this.setOptions(options);
        this.insertContainer();
    },
   	setMarkup: function(markup) {
   		this.options.overlay.set('html', markup);
   	},
    /**
     * Grab the markup and display it as an overlay
     */
    show: function(){
        var _this = this;
        this.options.overlay.set('load', {
            onSuccess: function(response){
                _this.handleMarkupLoaded(response);
            }
        }).load(this.options.url);

		return this;
    },
    /**
     * Dispose the Popup
     *
     * @param {Object} e
     */
    hide: function(e){
        if (e) 
            e.stop();
        this.options.overlay.dispose();
        
        $$('.overlay-background').dispose();
        this.options.onClose();
    },
    makeInvisible: function(e){
        $$('.overlay-background').dispose();
        this.options.onClose();
        this.options.overlay.addClass('display-none');
    },
    makeVisible: function(){
        this.options.overlay.getElement('div').setStyle('opacity', '1').removeClass('hidden');
		return this;
    },
    grayOutBackground: function(){
        var overlayBackground = $$('.overlay-background');
        if (overlayBackground.length == 0) 
            return new Element('div', {
                'class': 'overlay-background',
                style: 'height:' + window.getScrollSize().y + 'px;'
            }).inject($$('body')[0], 'top');
        else
            return overlayBackground[0];
    },
    insertContainer: function(){
        var divBackground = this.grayOutBackground();
        this.options.overlay = new Element('div', {
            'class': 'overlay',
            style: 'height:' + window.getScrollSize().y + 'px;'
        }).inject(divBackground, 'after');
    },
    /**
     * Was the popup is made visible, hook it up.
     */
    handleMarkupLoaded: function(){
        if (this.options.overlayBorderClass) 
            $$('.overlay-border').addClass(this.options.overlayBorderClass);
        this.positionOverlay();
		this.options.afterLoad(this);
        this.hookupCloseButton();
    },
    positionOverlay: function(){
        if (!this.options.makeInvisible) 
            this.makeVisible();
		var yScroll = window.getScroll().y;
        var o = this.options.overlay.getElement('.overlay-border');
		
        var top = (window.getSize().y - o.getSize().y) / 2 + yScroll;
        var offset = (top - yScroll) / 3;
        top = (top - yScroll > (offset * 2)) ? top - offset : top - yScroll;
        if (top < 0) 
            top = 0;
		
        var left = (window.getSize().x - o.getSize().x) / 2;
        if (left < 0) 
            left = 0;
			
        o.setStyles({
			top: top.limit(0, top) + 'px',
			left: left.limit(0, left) + 'px'
		});
		
		return this;
    },
    hookupCloseButton: function(){
        var _this = this;
        this.options.overlay.getElements('.close-button').addEvent('click', function(e){
			e.stop();
            _this.hide(e);
        });
    }
});
