/* Function chain obj */

if (Object.isUndefined(drk)) { var drk = {}; }

drk.FunctionChain = Class.create({

	log: function(str) {
		//console.debug('FunctionChain['+this.name+']: '+str);
	},

	initialize: function(name,options) {
		this.options = Object.extend({
			defaultPriority:	50
		},options || {});
		this.name = name;
		this._chain = [];
		this.executed = false;
	},
	
	addFunction: function(fn,name,priority) {
		if (this.executed) {
			this.log('Error: addFunction() after chain execution!');
			return false;
		}
		if (undefined===name) {
			name = 'Function #'+this._chain.length;
		}
		if (undefined===priority) {
			priority = this.options.defaultPriority;
		}
		this._chain.push({
			'fn':		fn,
			'name':		name,
			'priority':	priority
		});
	},
	
	executeChain: function() {
		var i=0;
		this.log('Begins');
		this._chain.sortBy(function(item){ return item.priority; }).each((function(item) {
			var identity = item.name+' (Priority '+item.priority+') ';
			var ok = true;
			try {
				item.fn();
			}
			catch (ex) {
				this.log(identity+'Failed: '+ex.message);
				ok = false;
			}
			if (ok) {
				this.log(identity+'Successful');
			}
		}).bind(this));
		this.executed = true;
		this.log('Ends');
	},
	hasBeenExecuted: function() {
		return this.executed;
	}
});

/* Chains setup */

var chainDomLoaded = new drk.FunctionChain('domLoaded');
var chainWindowLoaded = new drk.FunctionChain('windowLoaded');

document.observe('dom:loaded', chainDomLoaded.executeChain.bind(chainDomLoaded));
Event.observe(window, 'load', chainWindowLoaded.executeChain.bind(chainWindowLoaded));

/* element states */

var HoverObserver = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			'elementSelector':		'.hoverthis',
			'className':			'hover',
			'clickName':			'click',
			'startEvent':			'mouseenter',
			'stopEvent':			'mouseleave',
			'downEvent':			'mousedown',
			'upEvent':				'mouseup'
		},options || {});
		var elements = 0;
		if ($$(this.options.elementSelector).size() > 0) {
			$$(this.options.elementSelector).each(function(element){
				Event.observe(element, this.options.startEvent, this.onStart.bindAsEventListener(this,element));
				Event.observe(element, this.options.stopEvent, this.onStop.bindAsEventListener(this,element));
				Event.observe(element, this.options.downEvent, this.onDown.bindAsEventListener(this,element));
				Event.observe(element, this.options.upEvent, this.onUp.bindAsEventListener(this,element));
				elements++;
			},this);
		}
	},
	onStart: function(event,element) { element.addClassName(this.options.className); },
	onDown: function(event,element) { element.addClassName(this.options.clickName); },
	onUp: function(event,element) { element.removeClassName(this.options.clickName); },
	onStop: function(event,element) { element.removeClassName(this.options.className); }
});

chainWindowLoaded.addFunction(function(){
	// Observe mouse-enter/leave
	function addHover(){
		new HoverObserver();
	};
	addHover.defer();
},'HoverObserver',999);


// Load any page to target in DOM
var ajaxload = Class.create({
    initialize: function () {
    // set up the class
    },
    load: function (pId, target, pType, place) {
    
    // code to execute - insert content
        var newTarget = $(target);
        Element.extend(newTarget);
        newTarget.addClassName('pending');
        // code to execute - show
        new Ajax.Request(pId, {
            method: pType,
            onSuccess: function (transport) {
                var response = transport.responseText || "<span style='display:none;'>Siden er tom!</span>";
                // update status
                if (place =='top'){ newTarget.insert({ top: response }).addClassName('done'); } else { newTarget.insert({ bottom: response }).addClassName('done'); }
                newTarget.removeClassName('pending');
            },
            onFailure: function () {
                // update status
                newTarget.update('<span style="display:none;">Siden svarer ikke!</span>').addClassName('fail');
                newTarget.removeClassName('pending');
            }
        });
    }
});

var loadElement = new ajaxload();



/*** tab elements  ***/
var tabObserver = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			'elementSelector':		'',
			'groupSelector':		'',
			'groupHeading':			'',
			'headingPlacement':		'before',
			'tabClass':				'',
			'tabSelector':			'',
			'className':			'hover',
			'clickEvent':			'click',
			'startEvent':			'mouseenter',
			'stopEvent':			'mouseleave',
			'downEvent':			'mousedown',
			'upEvent':				'mouseup',
			'firstTab':				''
		},options || {});
	},
	addGroup: function(group,heading,placement,className) {
		var tabs = '';
		if (this.options.groupSelector != group) {
		
			// select visible tab
			var hashes = location.hash;
			var strHash = hashes.slice(1);
			
			var strTabName = '#'+group+' li[rel="tab_'+strHash+'"]';
			var tabArray = $$(strTabName).toArray();
			var strTabDiv = $('tab_'+strHash+'');
			
			var strAnchor = 'a[name="anchor_'+strHash+'"]';
			
			var target = $$(strAnchor).toArray();
			if (target.size() > 0) {this.options.firstTab = target[0].getOffsetParent();}
			
			//alert('firtTab: '+ strHash + '/'+ this.options.firstTab + '/' + target.size() + '/' + target[0].getOffsetParent()); // check to see effect
			//this.options.firstTab.show();
			//alert('strAnchor:'+strAnchor+ '/' + target.size() + '/'+ target[0].getOffsetParent());
		
		
			// set class to choose dom elements for tablist
			this.options.elementSelector = '.'+group;
			// set name for group of elements to avoid duplicates
			this.options.groupSelector = group;
			
			if (className != '' && className != undefined) this.options.tabClass = 'tablist_'+className;
			if (heading != '' && heading != undefined) this.options.groupHeading = '<span class="tabHead">' + heading + '</span>';
			if (placement != '' && placement != undefined) this.options.headingPlacement = placement;
			this.options.tabSelector = '.tab_'+this.options.groupSelector;
			$$(this.options.elementSelector).each(function(element,index){
				(index == 0)? tabs = tabs + '<li class="tab_'+this.options.groupSelector+' click" rel="' + element.readAttribute('id') + '">' + element.readAttribute('rel') + '</li>':tabs = tabs + '<li class="tab_'+this.options.groupSelector+'" rel="' + element.readAttribute('id') + '">' + element.readAttribute('rel') + '</li>';
			},this);
			$$(this.options.elementSelector).each(function(element,index){
				if ($$(this.options.elementSelector).size() > 1) {
					if (index == 0)/*(this.options.firstTab == element || this.options.firstTab == '')*/ {
						if (this.options.headingPlacement == 'before') {
							element.insert({
							  before: this.options.groupHeading + '<ul class="tablist '+this.options.tabClass+'" id="'+this.options.groupSelector+'">'+tabs+'</ul>'
							});
							$$(this.options.tabSelector).each(function(element){
								Event.observe(element, this.options.startEvent, this.onStart.bindAsEventListener(this,element));
								Event.observe(element, this.options.stopEvent, this.onStop.bindAsEventListener(this,element));
								Event.observe(element, this.options.downEvent, this.onDown.bindAsEventListener(this,element));
								Event.observe(element, this.options.upEvent, this.onUp.bindAsEventListener(this,element));
							},this);
						}
						//if (this.options.firstTab == element || this.options.firstTab == '') {element.show();}
						element.show();
					}
					if (index == $$(this.options.elementSelector).size()-1) {
						if (this.options.headingPlacement == 'after') {
							element.insert({
							  after: this.options.groupHeading + '<ul class="tablist '+this.options.tabClass+'" id="'+this.options.groupSelector+'">'+tabs+'</ul>'
							});
						$$(this.options.tabSelector).each(function(element){
							Event.observe(element, this.options.startEvent, this.onStart.bindAsEventListener(this,element));
							Event.observe(element, this.options.stopEvent, this.onStop.bindAsEventListener(this,element));
							Event.observe(element, this.options.downEvent, this.onDown.bindAsEventListener(this,element));
							Event.observe(element, this.options.upEvent, this.onUp.bindAsEventListener(this,element));
						},this);
						}
					}
				} else {
					element.show();
				}
			},this);
			// Set Anchor-selected tab
			if ($$(strTabName).toArray().size() > 0) {
				$$('#'+group+' li').invoke('removeClassName',this.options.clickEvent);
				$$('div.tabelement.'+group).invoke('hide');
				strTabDiv.show();
				$$('#'+group+' li[rel="tab_'+strHash+'"]').invoke('addClassName',this.options.clickEvent);
				document.fire('custom:contentrefreshed');
			}
		}
	
	},
	onStart: function(event,element) { element.addClassName(this.options.className); },
	onDown: function(event,element) { element.addClassName(this.options.clickEvent); },
	onUp: function(event,element) {
		$$(this.options.tabSelector).each(function(element){
			element.removeClassName(this.options.clickEvent); 
		},this);
		$$(this.options.elementSelector).invoke('hide');
		
		// eval($(element.readAttribute('rel')).show()); // why eval?
		
		var targetdiv = element.readAttribute('rel');
		$(targetdiv).show();
		element.addClassName(this.options.clickEvent);
		
		// to properly initialize maps in hidden elements
		// find any maps in shown element
		var memo = {
			mapIds: $(targetdiv).select('.drk_maps_map').invoke('identify') 
		};
		document.fire('custom:contentrefreshed', memo);
	},
	onStop: function(event,element) { element.removeClassName(this.options.className); }
});


if(!DRK){
    var DRK = {};
};

DRK.megamenu = function(){
    var that = {};

    // ID from setTimeOut: used to remove pending methods
    that.setTimeoutID = null;

    // classname of hovered menu item link
    that.currentTarget = null;

    // show the current hovered item
    that.showMegaItem = function(){
        var content_div = that.currentItem.select('.megatab')[0];

        // show the div
        //content_div.setStyle({display:'block'});
        new Effect.Appear(content_div, { from: 0.0, to: 1.0, duration: 0.25, queue: { position: 'end', scope: 'MM', limit: 3 } });
        
        // set the style of menu li element
        that.currentItem.addClassName('hover');
        
     // hide the object tags
        var oelemts = $$('#mainbox object');
        oelemts.each(function(x) {
            x.setStyle({visibility:'hidden'});
        });
      // hide the iframe tags
       var ielemts = $$('iframe');
       ielemts.each(function(y) {
            y.setStyle({visibility:'hidden'});
        });

    };

    // Hide the currently hovered item
    that.hideMegaItem = function(){
        if(that.currentItem == this)
            return;

        var content_div = that.currentItem.select('.megatab')[0];

        // hide the div
        //content_div.setStyle({display:'none'});
        new Effect.Fade(content_div, { from: 1.0, to: 0.0, duration: 0.25, queue: { position: 'end', scope: 'MM', limit: 3 } });
              
        that.currentItem.removeClassName('hover');
        
     // hide the object tags
        var oelemts = $$('#mainbox object');
        oelemts.each(function(x) {
            x.setStyle({visibility:'visible'});
        });
      // hide the iframe tags
       var ielemts = $$('iframe');
       ielemts.each(function(y) {
            y.setStyle({visibility:'visible'});
        });
    };

    that.mouseOverMegaItem = function(ev){
        if(that.timeoutID){
            // turn off the delayed show of the mega-menu
            clearTimeout(that.timeoutID);            
        }
        // if another mega item menu is currently shown hide it
        if(that.currentItem && that.currentItem != this){
            that.hideMegaItem();
        }
        that.currentItem = this;
        that.timeoutID = window.setTimeout(that.showMegaItem, 500);  
    };

    that.mouseOutMegaItem = function(ev){
        if(that.timeoutID){
            // turn off the delayed show of the mega-menu
            clearTimeout(that.timeoutID);            
        }
        that.currentItem = this;
        that.timeoutID = window.setTimeout(that.hideMegaItem, 250);  
    };

    that.addMenuItemsHoverListener = function(){
        $$('.menuitem').each(
            function(item){
                item.observe('mouseenter', that.mouseOverMegaItem);
                item.observe('mouseleave', that.mouseOutMegaItem);
            }
        );
    };

    that.init = function(){
        that.addMenuItemsHoverListener();
        return that;
    };

    return that.init();
};

document.observe("dom:loaded", function() {
   DRK.megamenu();
});

// Write index-class on selected DOM elements
function indexItems(selector, classNamePart){
	var itms = $$(selector);
	itms.each(function(element,index) {
	  element.addClassName(classNamePart+'_'+index);
	});
}

// Overlay
var overlay = Class.create({
    initialize: function (options) {
		// set up the class
		this.options = Object.extend({
			'oOrigin':		'',
			'oName':		'',
			'oWidth':		'',
			'oHeight':		'',
			'oLoad':		'',
			'oPosx':		'',
			'oPosy':		''
		},options || {});
    },
    createNew: function (setOrigin, setName, setWidth, setHeight, setLoad) {
    // setup overlay
    	this.options.oOrigin = $(setOrigin);
    	this.options.oName = setName;
    	this.options.oWidth = setWidth;
    	this.options.oHeight = setHeight;
    	this.options.oLoad = setLoad;
    	this.options.oPosx = -1.5*(setWidth/3);
    	this.options.oPosy = -1.5*(setHeight/3);

		$(this.options.oOrigin).insert({
			top: new Element('div', {style:'width:'+this.options.oWidth+';height:'+this.options.oHeight+';', id:this.options.oName, 'class': 'wrapcontent'})
		});
		var div1 = new Element('div', { 'class':'wrapout' });
		var div2 = new Element('div', { 'class':'wrapin' });
		var div3 = new Element('div', { 'class':'overlay',style:'top:'+this.options.oPosy+'px;left:'+this.options.oPosx+'px;', id:this.options.oName+'_overlay' });
		$(this.options.oName).wrap(div2).wrap(div1).wrap(div3);
		
		$(this.options.oName).insert({
			bottom: new Element('iframe', { frameborder:'0', marginheight:'0', style:'background:#FEF5F5;', marginwidth:'0', width:this.options.oWidth, height:this.options.oHeight, id:this.options.oName+'_iframe', src:this.options.oLoad})
		});
		$(this.options.oName).insert({
			bottom: new Element('div', { 'class':'wrapclose', id: this.options.oName+'_close' })
		});
		$(this.options.oName+'_close').observe('click',this.kill.bind(this));
    },
    loadTarget: function () {    
    // code to execute - insert content
       //loadElement.load(pId, target, 'get', 'top');
    },
    kill: function () {
    // kill overlay
    $(this.options.oName+'_overlay').remove();
    }
});

var overlays = new overlay();

/* Overlay for zoomio maillist */
document.observe("dom:loaded", function () {
	if ($('signup') != undefined) {
		var mailOverlay = "";
		var links = $$('form#signup');
		//alert(links.size());
		links.each(function (item) {
			item.observe('submit', function (e) {
				Event.stop(e);
					overlays.createNew('signup', 'signupOverlay', 510, 200, 'http://www.rodekors.dk/servicesider/newsletter?mail='+$F('newsletter_email'));
					//createNew(setOrigin, setName, setWidth, setHeight, setLoad);
			},'b_pop', 888);
		}.bind(this));
	}
	if ($('signup2') != undefined) {
		var mailOverlay = "";
		var links = $$('form#signup2');
		//alert(links.size());
		links.each(function (item) {
			item.observe('submit', function (e) {
				Event.stop(e);
					overlays.createNew(item.readAttribute('rel'), 'signupOverlay2', 510, 200, 'http://www.rodekors.dk/servicesider/newsletter?mail='+$F('newsletter_email'));
					//createNew(setOrigin, setName, setWidth, setHeight, setLoad);
			},'b_pop2', 888);
		}.bind(this));
	}
});

/* WATERMARK LABEL*/
var WatermarkLabel = Class.create({
	initialize: function(id) {
		this.textbox = $(id);
		this.text = '';
		
		var labels = $$('label[for="' + id + '"]');
		if(labels.length) {
			this.text = labels[0].innerHTML;
			Element.hide(labels[0]);
		}
		
		this.textbox.observe('focus', this.focus.bindAsEventListener(this));
		this.textbox.observe('blur', this.blur.bindAsEventListener(this));
		this.blur();
	},
	
	focus: function(event) {
		if(this.empty)
		this.textbox.value = '';
		this.empty = false;
		this.textbox.removeClassName('empty');
	},
	
	blur: function(event) {
		if(this.textbox.value == '') {
			this.textbox.value = this.text;
			this.textbox.addClassName('empty');
			this.empty = true;
		}
	}
});


var AccordionObserver = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			'elementSelector':		'.accordion',
			'className':			'hover',
			'clickName':			'click',
			'startEvent':			'mouseenter',
			'stopEvent':			'mouseleave',
			'downEvent':			'mousedown',
			'upEvent':				'mouseup'
		},options || {});
		var elements = 0;
		if ($$(this.options.elementSelector).size() > 0) {
			$$(this.options.elementSelector).each(function(element){
				Event.observe(element, this.options.startEvent, this.onStart.bindAsEventListener(this,element));
				Event.observe(element, this.options.stopEvent, this.onStop.bindAsEventListener(this,element));
				Event.observe(element, this.options.downEvent, this.onDown.bindAsEventListener(this,element));
				Event.observe(element, this.options.upEvent, this.onUp.bindAsEventListener(this,element));
				elements++;
			},this);
		}
	},
	onStart: function(event,element) { element.addClassName(this.options.className); },
	onDown: function(event,element) { element.addClassName(this.options.clickName); },
	onUp: function(event,element) { 
		element.removeClassName(this.options.clickName);
		Effect.toggle(element.readAttribute('rel'), 'slide', { delay: 0.2, duration: 0.5  });
	},
	onStop: function(event,element) { element.removeClassName(this.options.className); }
});

chainWindowLoaded.addFunction(function(){
	// Observe mouse-enter/leave
	function addAccordion(){
		new AccordionObserver();
	};
	addAccordion.defer();
},'addAccordionObserver',999);

// move selected DOM elements
function moveItems(copySelector, pasteSelector){
	var source = $(copySelector);
	var destination = $(pasteSelector);
	if (source==null || destination==null) { return; }
		try { 
			destination.insert({
				bottom: new Element('div', {id: 'replace_'+copySelector})
			});
			$('replace_'+copySelector).replace(source);
		}
		catch(e){}
}

// Scroll to top of page. Used for pages with iframes [KAD 09.11 2011]
function totop(){
	//window.scroll(0,0);
	//alert("test");
}
