// JavaScript Document

var Lilly = {

	InputFocus: new Class({
		text: null,
		input: null,
		initialize: function (elm) {
			this.input = $(elm);
			if (this.input == null || this.input == undefined) return false;
			this.text = this.input.value;
			alert('1');
			this.input.addEvent('focus', this.handler_focus.bindWithEvent(this));
			this.input.addEvent('blur', this.handler_blur.bindWithEvent(this));
		},
		handler_focus: function (e) {
			if (this.input.value == this.text) this.input.value = "";
		},
		handler_blur: function (e) {
			if (this.input.value == "") this.input.value = this.text;
		}
	}),

	Accordion: new Class({
		initialize: function() {
			var accordion = new Accordion($$('.toggler'),$$('.element'), {
			opacity: 0,
			alwaysHide: true,
			show: -1,
			duration: 'short',
			onActive: function(toggler) { toggler.addClass('toggleactive'); },
			onBackground: function(toggler) { toggler.removeClass('toggleactive'); }
			});
		}
	}),

	ExternalLinks: new Class({

		initialize: function () {
			$$('[rel=external]').each( function (item) {
				if (item.getProperty('rel') == "external") {
					item.setProperty('target', '_blank');
					item.addClass('external');
					if ((/^.+\.pdf$/i).test(item.getProperty('href')) == false && item.hasClass('noToolTip') == false)
					{
						this.addToolTip(item);
					}
				}
			}.bind(this));

			this.initToolTips();
		},

		addToolTip: function (elm) {
			elm.addClass('tooltip');
			elm.store('tip:title', '');
			elm.store('tip:text', 'Let op: door op deze knop te klikken verlaat je in sommige gevallen de website www.lilly.nl');
		},

		initToolTips: function () {
			var myTips = new Tips($$('.tooltip'), {
				timeOut		: 700,
				maxTitleChars	: 50,
				hideDelay		: 200,
				className		: 'external_tips',
				initialize: function () {
					this.fx = new Fx.Tween(this.tip, {duration: 200, link: 'cancel'});
					this.fx.set('opacity', 0);
				},
				onShow: function(tip){
					this.fx.start('opacity', .8);
				},
				onHide: function(tip){
					this.fx.start('opacity', 0);
				}
			});
		}
	}),

	Subnav: new Class({
		MARK_CLASS: 'selected',
		HIDDEN_CLASS: 'hidden',
		initialize: function () {
			var location, subnav;

			location = this.getUrlParts(document.URL);

			this.hideChildNav();

			$$('#subnav a').each( function (item) {
				var path = this.getUrlParts(item.getProperty('href'));
				if (path == location) this.mark(item);
			}.bind(this));

			$('subnav').setStyle('visibility', 'visible');
		},

		hideChildNav: function () {
			$$('#subnav ul ul').each( function (item) {
				item.toggleClass(this.HIDDEN_CLASS);
			}.bind(this));
		},

		mark: function (item) {
			var liParents, ulParents;

			liParents = item.getParents('li');
			ulParents = item.getParents('ul');
			ulChildren = item.getParent().getFirst('ul');

			item.addClass(this.MARK_CLASS);

			liParents.each( function (li) {
				li.addClass(this.MARK_CLASS);
			}.bind(this));
			ulParents.each( function (ul) {
				ul.removeClass(this.HIDDEN_CLASS);
			}.bind(this));

			if (ulChildren) ulChildren.removeClass(this.HIDDEN_CLASS);
		},

		getUrlParts: function (url) {
			url = url.replace(/^\/*/, '').replace(/\/*$/, '');
			url = url.split('/');

			if (url[0] == "http:") {
				url = url.slice(3);
			}

			return url.join('/');
		}
	}),

	SelectForm: new Class({
		select: null,
		initialize: function (form) {
			var submit;

			form = $(form);
			if (!form) return;

			submit = form.getElement('input');

			if (!submit) return;

			submit.setProperty('rel', 'external');

			this.select = form.getElement('select');

			if (!this.select) return;

			form.addEvent("submit", this.onSubmit.bind(this))
		},
     		onSubmit: function (e) {
			var href;
			var submitID;
			var valueList;

			if(document.getElementById("illnessValueList").selectedIndex != 0)
			{
			    valueList = document.getElementById("illnessValueList");
			    RedirectExternalURL(valueList.options[valueList.selectedIndex].value);
			    valueList.selectedIndex = 0;
			}
			else if(document.getElementById("productValueList").selectedIndex != 0)
			{
			    valueList = document.getElementById("productValueList");
			    RedirectExternalURL(valueList.options[valueList.selectedIndex].value);
			    valueList.selectedIndex = 0;
			}
			else
			{
			    alert('Er moet een geldige waarde worden opgegeven!')
			}

			e.stop();
			return false;
		}

	}),

	XMLMenu: new Class({
		div: '',
		target: '',
		intervalId: '',
		url: '',
		initialize: function (target, url, id) {
			this.target = $(target);
			this.url = url;
			this.div = new Element('div', {
				'id': id,
				'styles': {
					'display': 'none'
				}
			});
			this.parent = $('parentId');
			this.getXML();
			this.div.inject(document.body);
			this.addEvents();
		},
		getXML: function () {
			var req = new Request.HTML({
				method: 'get',
				update: this.div,
				url: this.url,
				onComplete: this.xmlComplete.bind(this)
			}).send();
		},
		addEvents: function () {
			this.target.addEvent('click', function (e) {e.stop()});
			this.target.addEvent('mouseover', this.onMouseOver.bind(this));
			this.target.addEvent('mouseleave', this.onMouseOut.bind(this));
			this.div.addEvent('mouseleave', this.onMouseOut.bind(this));
			this.div.addEvent('mouseenter', this.onMouseEnter.bind(this));
		},
		xmlComplete: function (obj) {
			var pos, coord;

			pos = this.target.getPosition();
			coord = this.target.getCoordinates();

			this.div.setStyle("top", coord.top + coord.height + 3);
			this.div.setStyle("left", coord.left);

                        // set the event to the link!
                        this.div.getElements('a').each(function(el){
                            el.addEvent('click', function (e) { visit(el.get('href')); e.stop();});
                        });
		},
		show: function () {
			this.div.setStyle('display', 'block')
		},
		hide: function () {
			this.div.setStyle('display', 'none')
		},
		onMouseOver: function (e) {
			this.show();
			e.stop();
		},
		onMouseEnter: function (e) {
			clearInterval(this.intervalId);
		},
		onMouseOut: function (e) {
			e.stop();
			this.intervalId = this.hide.delay(300, this);
		}
	}),

	Pages: new Class({

		initialize: function () {

			$(document.body).getProperty('class').split().each( function (item) {
				if (this[item]) this[item]();
			}.bind(this));

			this.global();
		},

		global: function () {
			if ($('subnav')) { new Lilly.Subnav(); }
			new Lilly.ExternalLinks();
			new Lilly.Accordion();
			new Lilly.InputFocus('s');
			new Lilly.XMLMenu(
				'worldwide',
				'../library/locales.lbi',
				'locales'
			);
		},

		home: function () {
			new Lilly.SelectForm('productSelectForm');
		},

		products: function () {
			new Lilly.SelectForm('productSelectForm');
		}
	})
}

window.addEvent('domready', function(){
	new Lilly.Pages();
        $('productValueList').addEvent('change',function(){
            $('illnessValueList').selectedIndex = 0;
        });
        $('illnessValueList').addEvent('change',function(){
            $('productValueList').selectedIndex = 0;
        });
});


function RedirectExternalURL(URLLink)
{

    if(URLLink.indexOf("http://") == -1 || URLLink.indexOf("lilly.nl") != -1)
    {
	if(URLLink.indexOf("http://") == -1)
	{

	    location.href = "http://www.lilly.nl/Nitro/main/" + URLLink;
	}
	else
	{
 	    location.href = URLLink;
	}
    }
    else
    {
        window.open("http://www.lilly.nl/Nitro/main/Legal_Disclaimer.jsp?page=10006&pagina=" + URLLink,'','width=600, height=240');
    }
}

function setOtherFontSize()
{
	//debugger;
	if(getActiveStyleSheet() != "regularFont")
	{
		setActiveStyleSheet("regularFont");
	}
	else
	{
		setActiveStyleSheet("largeFont");
	}
}

// 1. Loop through every link element in the document.
// 2. Disable all preferred and alternate style sheets that we don’t want active.
// 3. Enable all preferred and alternate style sheets that we do want active.
function setActiveStyleSheet(title)
{
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++)
  {
    if(a.getAttribute("rel").indexOf("alternate stylesheet") != -1 && a.getAttribute("title"))
	{
      a.disabled = true;
      if(a.getAttribute("title") == title)
		a.disabled = false;
    }
  }
}
//Return the current style sheet
function getActiveStyleSheet()
{
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++)
  {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled)
		return a.getAttribute("title");
  }
  return null;
}

//Create a cookie to store the preferred style sheet.
function createCookie(name,value,days) {
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

//Read the cookie to return the prefered style sheet.
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++)
  {
    var c = ca[i];
    while (c.charAt(0)==' ')
		c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0)
		return c.substring(nameEQ.length,c.length);
  }
  return null;
}

//Runs on page load...
window.onload = function(e)
{
	//debugger;
    var cookie = readCookie("style");
    var title = cookie ? cookie : "regularFont";
    setActiveStyleSheet(title);
}

//Save the cookie in the onunload event
window.onunload = function(e)
{
	//debugger;
	var title = getActiveStyleSheet();
	if (title != null)
	{
		createCookie("style", title, 365);
	}
}
