﻿var WebSiteApp = new Class({
	Implements: Options,
	options: {
		baseAppUrl: virtualPath,
		baseImagesUrl: virtualPath + '/Images',
		notification: null
	},
	initialize: function(options) {
		if (options)
			this.setOptions(options);
	},
	getBaseURL: function() {	
		return this.options.baseAppUrl;
	},
	getImagesURL: function() {	
		return this.options.baseImagesUrl;
	}
});

var WebSiteAppBase = new Class(
{
	Implements: Options,
	appInstance: function() {
		return getWebSiteAppInstance();
	}
});

var WebSiteAppURLProvider = new Class(
{
	Extends: WebSiteAppBase,
	Implements: [Events, WebSiteAppBase],
	options: {},
	provideURLFor: function(el)
	{
		if (el.nodeName == 'A')
		{
			if (el.href != null && el.href.length > 0)
			{
				var old_href = el.getAttribute('href', 2);
				if ((new RegExp('^/.*')).test(old_href))
					el.href = this.appInstance().getBaseURL() + old_href;
			}
		}
		else if (el.nodeName == 'IMG')
		{
			var old_src = el.getAttribute('src', 2);
			if ((new RegExp('^/.*')).test(old_src))
			{
				var new_img = el.clone(true, true);
				new_img.setAttribute('src', this.appInstance().getImagesURL() + old_src);
				new_img.replaces(el);
				el = new_img;
			}
		}
		el.getChildren().each(this.provideURLFor.bind(this));
	},
	replaceInURL: function(el, target, replacement)
	{
		if (el.nodeName == 'A' && (el.href != null && el.href.length > 0))
			el.href = el.href.replace(new RegExp('{{' + target + '}}', 'g'), replacement);
		else if (el.nodeName == 'IMG')
		{
			var new_img = el.clone(true, true);
			new_img.setAttribute('src', el.getAttribute('src', 2).replace(new RegExp('{{' + target + '}}', 'g'), replacement));
			new_img.replaces(el);
			el = new_img;
		}
		el.getChildren().each(function(child)
		{
			this.replaceInURL(child, target, replacement);
		} .bind(this));
	}
});

var defaultWebSiteAppInstance = null;
function setWebSiteAppInstance(instance) {
	defaultWebSiteAppInstance = instance;
}
function getWebSiteAppInstance() {
	if (defaultWebSiteAppInstance === null) {
		defaultWebSiteAppInstance = new WebSiteApp();
	}
	return defaultWebSiteAppInstance;
}
