// JavaScript Document

var CMS_DOM_Loaded = false;
var CMS_DOM_FullyLoaded = false;
document.observe('dom:loaded',function() {window.CMS_DOM_Loaded = true;});
Event.observe(window,'load',function() {window.CMS_DOM_FullyLoaded = true;});

function CMS_AddOnloadEvent(addToOnload) {
	if (CMS_DOM_Loaded === false)	document.observe('dom:loaded',function() {addToOnload();});
	else							addToOnload();
}
function CMS_AddOnFullyLoadedEvent(addToOnload) {
	if (CMS_DOM_FullyLoaded === false)	Event.observe(window,'load',function() {addToOnload();});
	else								addToOnload();
}
function CMS_Alert(text) {alert(text);}
function CMS_WindowReload() {window.location = window.location.pathname;}
function CMS_WindowRedirect(url) {window.location = url};
function CMS_Timestamp() {return parseInt(new Date().getTime().toString().substring(0,10));} 
function CMS_Microtime() {return new Date().getTime() / 1000;}
function CMS_UrlEncode(str) {return encodeURIComponent(str); }

function CMS_InputFocus(id,def,refill)
{
	if (typeof(refill)=="undefined")	refill = true;
	
	if ($(id).tagName.toLowerCase() == "textarea")	{if ($(id).innerHTML == def)	$(id).innerHTML = ''; else $(id).select();}
	else											{if ($(id).value == def)		$(id).value = ''; else $(id).select();}

	if (refill===true)
		$(id).observe('blur',function () {CMS_InputBlur(id,def);});
}

function CMS_InputBlur(id,def)
{
	if ($(id).tagName.toLowerCase() == "textarea")	{if ($(id).innerHTML == '')	$(id).innerHTML = def;}
	else											{if ($(id).value == '')		$(id).value = def;}
	
	$(id).stopObserving('blur',function () {CMS_InputBlur(id,def);});
}

function CMS_SubmitForm(form)
{
	var parameters = Form.serialize(form);
	parameters = (parameters != "") ? parameters + "&t=" + CMS_Timestamp() : "t=" + CMS_Timestamp();
	
	CMS_AjaxRequest($(form).readAttribute('action'),parameters);
}

function CMS_KeyListener(event) {
	var keycode = (event.keyCode) ? event.keyCode : event.which;
	
	switch (keycode)
	{
		case Event.KEY_ESC:
		case Event.KEY_LEFT:
		case Event.KEY_RIGHT:
			var popups = $$('div.PopupWrapper');
			if (popups.size()>0)
			{
				top_popup = popups[(popups.size()-1)];
			
				if (top_popup.readAttribute('popup_type') == "popup")
				{
					if (keycode==Event.KEY_ESC)			CMS_Popup.close(top_popup.readAttribute('popup_id'));
				}
				else if (top_popup.readAttribute('popup_type') == "gallery")
				{
					if (keycode==Event.KEY_ESC)			CMS_Galleries[top_popup.readAttribute('popup_id')].close();
					if (keycode==Event.KEY_LEFT)		CMS_Galleries[top_popup.readAttribute('popup_id')].prevImg(event);
					if (keycode==Event.KEY_RIGHT)		CMS_Galleries[top_popup.readAttribute('popup_id')].nextImg(event);
				}	
			}
		break;
		
		case 76:
			if (event.shiftKey && event.altKey)
			{
				CMS_Popup.load('login','module=login');
				event.stop();
			}
		break;
	}
}
CMS_AddOnloadEvent(function() {Event.observe(document,"keydown",CMS_KeyListener);});



var CMS_PopupClass = Class.create();
CMS_PopupClass.prototype = {
	popups : {},
	
	
	initialize : function() {	
		this.options = {
			loadingImg:		_common_url + 'gfx/gallery_loading.gif',
			closeImg:		_common_url + 'gfx/gallery_close.png',
			closeText:		'Luk vinduet',
			backend:		_site_url + 'ajax.php',
			popupMargin:	10,
			pageMargin: 	30,
			width:			200,
			height: 		200
		};
	},
	
	load : function(id,parameters,options) {
		if (typeof(parameters)=="undefined")	parameters = "";
		if (typeof(options)=="undefined")		options = {};
		
		if (typeof(this.popups[id]) == "undefined")
		{
			this.popups[id] = {'options' : Object.extend(options,this.options),'history' : Array()};
			this.prepare(id);
		}
		else
			this.popups[id].options = Object.extend(options,this.popups[id].options);
		
		this.popups[id].history.push(parameters);
		
		this.request(id,parameters);
	},
	
	reload : function(id) {
		this.load(id,this.popups[id].history.pop());
	},
	
	back : function(id) {
		this.popups[id].history.pop();
		this.load(id,this.popups[id].history.pop());
	},
	
	showLoading : function(id) {
		this.popups[id].content.hide();
		this.popups[id].closeButton.hide();
		
		this.popups[id].imgLoading.show();
	},
	
	request : function(id,parameters) {
		this.showLoading(id);
		
		if (typeof(parameters)=="string")		parameters = parameters.toQueryParams();
		parameters['t'] = CMS_Timestamp();
		
		var ajaxOptions = {
			method: 'post',
			parameters: parameters,
			onFailure : function (response) {CMS_Alert("Der opstod en fejl!\n\r\n\rDet ser ud til, at du mistede forbindelsen til serveren. Prøv venligst igen!");},
			onSuccess : (function (response) {
				response.responseText.evalScripts();
				this.update(id,response.responseText);
			}).bind(this)
		};
		
		new Ajax.Request(this.popups[id].options.backend,ajaxOptions);
	},
	
	update: function(id,content) {
		this.popups[id].content.update(content);
		
		var size = this.getSize(id);
//		size.width = (size.height < this.popups[id].content.getHeight()) ? size.width+25 : size.width +10;
		
		this.popups[id].content.setStyle({'width':(size.width)+'px','height':size.height+'px'});
//		this.popups[id].contentWrapper.setStyle({
		new Effect.Transform(this.popups[id].contentWrapper,{
			"width" : (size.width + this.popups[id].options.popupMargin*2) +"px",
			"height" : (size.height + this.popups[id].options.popupMargin) +"px"
		},{
			"endEffect" : (function() {	
				this.popups[id].imgLoading.hide();
				this.popups[id].closeButton.show();				
				this.popups[id].content.show();
				
				if (typeof(this.popups[id].onload) == "function")
				{
					this.popups[id].onload();
					delete (this.popups[id].onload);
				}
				else
				{
					var forms = this.popups[id].content.select("form");
					if (forms.size() > 0)	forms[0].focusFirstElement();
				}
			}).bind(this,id)
		});
	},
	
	getSize : function(id) {
		var dimensions = document.viewport.getDimensions();
		var max_width = dimensions.width - 2*this.popups[id].options.pageMargin;
		var max_height = dimensions.height - 2*this.popups[id].options.pageMargin;
		

		this.popups[id].content.setStyle({"width":"","height":""});
		var width  = this.popups[id].content.setStyle({"visibility" : "hidden"}).show().childElements().max(function(child) {return child.show().getWidth();});
		this.popups[id].content.hide().setStyle({"visibility" : ""});
		this.popups[id].content.setStyle({'width':(width)+'px'});
		var height = this.popups[id].content.getHeight() + this.popups[id].options.popupMargin;
		
		
		if (width > max_width)		width = max_width;
		if (height > max_height)	height = max_height;
		
		return {"width" : width, "height": height};
	},

	
	close : function(id) {
/*		Effect.Fade(this.popups[id].wrapper,{
			"endEffect" : (function() {
				if ($(this.popups[id].wrapper).descendantOf(document.body))
					this.popups[id].wrapper.remove();
			
				delete this.popups[id];
		
				if (Object.values(this.popups).size() ==0)
					CMS_WindowReload();
			}).bind(this)
		});*/
		if ($(this.popups[id].wrapper).descendantOf(document.body))
		{
			this.popups[id].overlay.remove();
			this.popups[id].wrapper.remove();
		}
		
		delete this.popups[id];
		
		if (Object.values(this.popups).size() ==0 && $$('div[popup_type="gallery"]').size() == 0)
		{
			CMS_WindowReload();
		}
	},
	
	prepare : function(id) {
		this.popups[id].overlay = new Element("div").addClassName('PopupOverlay').setStyle({'opacity' : 0.5, "zIndex": (99 + Object.values(this.popups).size()*10) });
		this.popups[id].imgLoading = new Element('img',{'src' : this.popups[id].options.loadingImg}).addClassName('PopupLoading');
		
//		this.popups[id].imgLoading = new Element('div').setStyle({"border" : "1px solid #0f0", height: "100%", width: "100%"}).update(this.popups[id].imgLoading);
		
		this.popups[id].closeButton = new Element("img",{"src" : this.popups[id].options.closeImg,"title":this.popups[id].options.closeText}).hide().addClassName("PopupClose").observe("click",this.close.bind(this,id));
		this.popups[id].content = new Element("div").addClassName('PopupContent').hide().setStyle({"marginLeft" : this.popups[id].options.popupMargin+"px","marginRight" : this.popups[id].options.popupMargin+"px","paddingTop" : this.popups[id].options.popupMargin+"px"});
		
		this.popups[id].contentWrapper = new Element("div").addClassName('PopupContentWrapper').insert(this.popups[id].imgLoading).insert(this.popups[id].closeButton).insert(this.popups[id].content);
		this.popups[id].contentWrapper.setStyle({'width' : this.popups[id].options.width+"px","height":this.popups[id].options.height+"px","top":this.popups[id].options.pageMargin+"px"});
		
		this.popups[id].wrapper = new Element("div").setStyle({"zIndex": (100 + Object.values(this.popups).size()*10) }).addClassName('PopupWrapper').writeAttribute('popup_type','popup').writeAttribute('popup_id',id).insert(this.popups[id].contentWrapper).hide();

		
		$(document.body).insert(this.popups[id].overlay);
		$(document.body).insert(this.popups[id].wrapper);
	
		this.popups[id].wrapper.show();

//		Effect.Appear(this.popups[id].wrapper);
	}
};
CMS_AddOnloadEvent(function() {
	window.CMS_Popup = new CMS_PopupClass();
});


// Funktion som behandler alle AJAX-forbindelser til serveren
function CMS_AjaxRequest(url,parameters,target){
// Parametre, som gælder for alle typer forbindelser
	if (typeof(parameters)=="string")
		parameters = parameters.toQueryParams();
	parameters['t'] = CMS_Timestamp();
	
	var ajaxOptions = {
		method: 'post',
		parameters: parameters,
		onFailure : function (response) {CMS_Alert("Der opstod en fejl!\n\r\n\rDet ser ud til, at du mistede forbindelsen til serveren. Prøv venligst igen!");}
	};

// Forbindelser som ikke skal returnere data til et felt
	if (typeof target == 'undefined' || target == '')
	{
		ajaxOptions['onSuccess'] = function (response) {response.responseText.evalScripts(); };
		new Ajax.Request(url,ajaxOptions);
	}
// Forbindelser som skal returnere data til et input-felt
	else if ($(target).tagName.toLowerCase() == 'input' || $(target).tagName.toLowerCase() == 'textarea')
	{
		ajaxOptions['onSuccess'] = function (response) {$(target).value = response.responseText;};
		new Ajax.Request(url,ajaxOptions);
	}
// Forbindelser som skal returnere data til et hvilket som helst andet element
	else
	{
		ajaxOptions['evalScripts'] = true;
		new Ajax.Updater(target,url,ajaxOptions);
	}
}


function CMS_GenerateURL(title,url)
{
	if ($(url).disabled)
	{
		var new_url = $F(title).toLowerCase().replace(/[\,\.|\/]/gi,' ');
		new_url = new_url.replace(/ /gi,'-');
		while (new_url.indexOf('--',0) !== -1)	new_url = new_url.replace('--','-');
		new_url = new_url.replace(/æ/gi,'ae').replace(/ø/gi,'oe').replace(/å/gi,'aa').replace(/\?/gi,'');
		new_url = htmlentities(new_url);

		$(url).value = new_url;
	}
}

  
var Effect = {
	Opacity : Class.create({				
		initialize : function(element) {
			this.element = $(element);
			this.options = Object.extend({
				duration: 50,
				interval: 5,
				from: this.element.getOpacity() || 0.0,
				to:   1,
				animate: false
			}, arguments[1] || { });
			
			this.loopTotal = (this.options.duration / this.options.interval).ceil();
			this.loopCurrent = (this.options.animate !== false) ? 0 : this.loopTotal;

			this.interval = setInterval(this.loop.bind(this),this.options.interval)
			this.loop();
		},
		
		loop : function() {
			this.loopCurrent++;
	
			this.element.setOpacity(this.options.from + (this.options.to - this.options.from)*(this.loopCurrent / this.loopTotal));
		
			if (this.loopCurrent >= this.loopTotal)
			{
				clearInterval(this.interval);
				if (typeof(this.options.endEffect)=="function")
					setTimeout(this.options.endEffect,50);
			}
		}
	}),


	Fade : function(element) {
		element = $(element);
		var options = Object.extend({
			from: element.getOpacity() || 1.0,
			to:   0.0
		}, arguments[1] || { });
		
		new Effect.Opacity(element,options);
	},

	Appear : function(element) {
		element = $(element);
		var options = Object.extend({
			from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
			to:   1.0
		}, arguments[1] || { });
		
		element.setOpacity(options.from).show(); 
		
		new Effect.Opacity(element,options);
	},


	Transform : Class.create({
		initialize : function(element) {
			if (!arguments[1]) return false;
			
			this.element = $(element);
			this.options = Object.extend({
				startStyle	: $H(),
				endStyle	: $H(arguments[1]),
				duration	: 125,
				interval	: 25,
				animate		: true
			}, arguments[2] || { });
			
			this.options.endStyle.each((function(pair) {
				switch (pair.key)
				{
					case "width":
					case "height":
						this.options.endStyle.set(pair.key,(pair.value+"").replace(/px/gi,"")-0);
						this.options.startStyle.set(pair.key,(this.element.getStyle(pair.key)+"").replace(/px/gi,"")-0);
					break;
					
					default:
						this.options.startStyle.set(pair.key,this.element.getStyle(pair.key));
					break;
				}
			}).bind(this));
			
			this.loopTotal = (this.options.duration / this.options.interval).ceil();
			this.loopCurrent = (this.options.animate !== false) ? 0 : this.loopTotal;

			this.interval = setInterval(this.loop.bind(this),this.options.interval)
		},
		
		loop : function () {
			this.loopCurrent++;
						
			this.loopStyles = $H();
			this.options.startStyle.each((function(pair) {
				switch (pair.key)
				{
					case "width":
					case "height":
						var loopValue = (this.loopCurrent < this.loopTotal) ? pair.value + ( (this.options.endStyle.get(pair.key)-pair.value) * this.loopCurrent / this.loopTotal  ).round() : this.options.endStyle.get(pair.key);
						loopValue = loopValue + 'px';
						this.loopStyles.set(pair.key,loopValue);
					break;
					
					case "color":
						var start = pair.value.parseColor();
						var end = this.options.endStyle.get(pair.key).parseColor();
						
						var loopValue = '#'+
						  (Math.round(start[0]+
							(end[0]-start[0])* this.loopCurrent / this.loopTotal)).toColorPart() +
						  (Math.round(start[1]+
							(end[1]-start[1])* this.loopCurrent / this.loopTotal)).toColorPart() +
						  (Math.round(start[2]+
							(end[2]-start[2])* this.loopCurrent / this.loopTotal)).toColorPart();

						this.loopStyles.set(pair.key,loopValue);
					break;
					
					default:
					break;
				}
			}).bind(this));
			
			this.element.setStyle(this.loopStyles.toObject());
				
			if (this.loopCurrent >= this.loopTotal)
			{
				clearInterval(this.interval);
				if (typeof(this.options.endEffect)=="function")
					setTimeout(this.options.endEffect,50);
			}
		}
	})
};



String.prototype.parseColor = function() {  
  var color = '#';
  if (this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if (this.slice(0,1) == '#') {  
      if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if (this.length==7) color = this.toLowerCase();  
    }  
  }  
  
  color = (color.length==7 ? color : (arguments[0] || this));  
  
  if (!this || ['rgba(0, 0, 0, 0)','transparent'].include(this)) color = '#ffffff';
  return $R(0,2).map(function(i){
	return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
  });

};




function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/htmlentities    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
        return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/get_html_translation_table    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
     useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}
