/* E-polisas */
                   
function getElementsByClass( searchClass, domNode, tagName) {
    if (domNode == null) domNode = document;
    if (tagName == null) tagName = '*';
    var el = new Array();
    var tags = domNode.getElementsByTagName(tagName);
    var tcl = " "+searchClass+" ";
    for(i=0,j=0; i<tags.length; i++) {
        var test = " " + tags[i].className + " ";
        if (test.indexOf(tcl) != -1)
            el[j++] = tags[i];
    }
    return el;
}

/**
 * Date picker settings and localization
 */

var FORMATS = {
	firstDayOfWeek : 1,
	dateFormat     : 'Y-m-d',
	calendarFormat : 'ymd',
	numberFIX      : 2,
	numberDEC      : ',',
	numberTOU      : ' '
};

extend(Date.prototype, {
	daysLong:    ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"],
	daysShort:   ["S", "P", "A", "T", "K", "P", "Š"],
	monthsShort: ['Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegužė', 'Birželis', 'Liepa', 'Rugpjūtis', 'Rugsėjis', 'Spalis', 'Lapkritis', 'Gruodis'],
	monthsLong:  ['Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegužė', 'Birželis', 'Liepa', 'Rugpjūtis', 'Rugsėjis', 'Spalis', 'Lapkritis', 'Gruodis']
});


var ERGO = {

	parentNode: window,
	widgets: {},

	ready: function() {
		window.setTimeout(function() {
			events.dispatch({
				type: 'ready',
				target: ERGO
			});
		}, 0);
	},
	
	destroy: function() {
		events.dispatch({
			type: "destroy",
			target: ERGO
		});
		for (var type in ERGO.__events) {
			if (type != "ready") {
				for (var handl in ERGO.__events[type]) {
					delete ERGO.__events[type][handl];
				};
			};
		};
	}

};


new function() {

	ERGO.newWidget = function(prototype) {
		return ERGO.widgets[prototype.name] = new Widget(prototype);
	};

	function Widget(prototype) {
		if (!prototype.name) {
			throw new Error("Widget Class must have name defined.");
		};

		this.__class = extend(function(element, settings) {
			events.add(ERGO, "destroy", bind(destroy, this));
			this.__bound = [];

			extend(this, settings, { element: element }).construct();
		}, {
			prototype: extend(copy(this._proto), prototype)
		});
	}

	function destroy() {
		this.destroy();
		this.removeEvent();
		this.unbind.apply(this.__bound);
		delete this.element.__widgets[this.name];
		this.element = null;
	}

	extend(Widget.prototype, {

		run: function(select, settings) {
			if (!select) {
				return false;
			};

			select = select instanceof Array ? select : [select];

			for (var i = 0; i < select.length; i++) {
				var widgets = select[i].__widgets;
				if (!widgets) {
					widgets = select[i].__widgets = {};
				};

				(widgets[this.name] = widgets[this.name]
					? extend(widgets[this.name], settings)
					: new this.__class(select[i], settings)
				).initialize();
			};
		},

		_proto: {
			construct: function() {},
			initialize: function() {},
			destroy: function() {},

			addEvent: function(type, method) {
				events.add(this.element, type, method = bind(method, this));
				return method;
			},

			removeEvent: function(type, method) {
				events.remove(this.element, type, method);
			},

			dispatchEvent: function(event) {       
				if (typeof event == 'string') {
					event = { type: event, target: this.element };
				} else if (!event.target) {
					event.target = this.element;
				};

				events.dispatch(event);
			},

			bind: function() {
				for (var i = 0, a = arguments; i < a.length; i++) {
					this.element[a[i]] = bind(this[a[i]], this);
					this.__bound.push(a[i]);
				};
			},

			unbind: function() {
				for (var i = 0, a = arguments; i < a.length; i++) {
					delete this.element[a[i]];
				};
			}
		}

	});

};


// COMMON WIDGETS


/**
 * INDEX NAVIGATION
 *
 * 1. Applies vertical centering to index sub-navigation blocks
 * 2. Fixes rollovers for IE <= 6
 */

ERGO.newWidget({

	name: 'indexNavigation',
	target: 'ul',
	maxNodes: 8,

	construct: function() {
		var elems = dom(this.element, this.target), list, i = 0;
		var legacyIE = false/*@cc_on!=true&&!window.XMLHttpRequest@*/;

		for (; (list = elems[i]); i++) {
			var nodes = dom(list, 'li'),
					count = this.maxNodes - nodes.length;

			(count > 0) && dom.addClass(nodes[0], 'offset-' + count);

			if (legacyIE) {
				events.add(dom.parent(list), 'mouseenter', this.showBlock);
				events.add(dom.parent(list), 'mouseleave', this.hideBlock);
			};
		};
	},

	showBlock: function(e) {
		dom.addClass(e.target, 'hover');
	},

	hideBlock: function(e) {
		dom.removeClass(e.target, 'hover');
	}

});



/**
 * PRINT VERSION
 *
 * Emulates print version preview by manipulating stylesheets.
 * Creates corresponding switch-link automatically (Lithuanian only).
 */

ERGO.newWidget({
	
	name: 'printVersion',
	sheets: { disabled: [], added: [] },
	templates: {
		'printTrigger' : '<p id="printVersion"><a href="javascript:void(0);">%1</a></p>',
		'printButtons' : '<div id="printButtons"><button onclick="window.print();">%1</button>&nbsp;<button id="printClose">%2</button></div>'
	},

	construct: function() {
		this.element.appendChild(dom.create(this.templates.printTrigger.format('Spausdinti')));

		events.add(dom(dom('printVersion'), 'a')[0], 'click', bind(this.switchToPrint, this));
	},

	switchToPrint: function(e) {
		window.switchLayout = false;
		var tags = dom(dom(), 'style').concat(dom(dom(), 'link')), item, i = 0;

		for (; (item = tags[i]); i++) {
			if (item.rel == 'stylesheet' || item.type.indexOf('css') != -1) {
				if (/print/.test(item.media)) {
					var clone = item.cloneNode(false);
					clone.media = 'screen';
					this.sheets.added.push(clone);
					dom.before(clone, item);
				} else if (!new RegExp('/all/').test(item.media) && !item.disabled) {
					this.sheets.disabled.push(item);
					item.disabled = true;
				};
			};
		};

		var printButtons = dom.create(this.templates.printButtons.format('Spausdinti', 'Uždaryti'));
		dom.before(printButtons, dom().body.firstChild);
		events.add(dom('printClose'), 'click', bind(this.switchToDefault, this));

		return false;
	},

	switchToDefault: function() {
		dom.remove(dom('printButtons'));

		for (var i = this.sheets.added.length - 1; i >= 0; i--) {
			dom.remove(this.sheets.added[i]);
		};

		for (var i = this.sheets.disabled.length - 1; i >= 0; i--) {
			this.sheets.disabled[i].disabled = false;
		};
	}

});



/**
 * DATE PICKER
 *
 * Creates a calendar to show upon trigger (focus/keyUp/mouseDown/mouseUp)
 */

ERGO.newWidget({
	name: 'datePicker',

	today: new Date(TODAY),
	rangeFromDefault: new Date(new Date().getFullYear() - 30, 0, 1),
	rangeToDefault: new Date(new Date().getFullYear() + 30, 11, 31),

	rangeFrom: null,
	rangeTo: null,

	firstDayOfWeek:	FORMATS.firstDayOfWeek,
	dateFormat:		FORMATS.dateFormat,
	calendarFormat:	FORMATS.calendarFormat,

	holder_src: '<span class="date-picker-holder"></span>',
	next_src:   '<img src="css/images/icon-cal_next.gif" class="link-next" />',
	prev_src:   '<img src="css/images/icon-cal_prev.gif" class="link-prev" />',
	body_src:   '<div class="popup-calendar"><div class="year">%1<b>%3</b>%2</div><div class="month">%1<b>%4</b>%2</div><div>%5</div></div>',
	table_src:  '<table class="weeks" cellspacing="2"><thead><tr>%1</tr></thead><tbody>%2</tbody></table>',	
	theadCell_src:         '<th class="%3" title="%2" abbr="%2" scope="col">%1</th>',
	tbodyCellActive_src:   '<td class="%3"><a tabindex="-1" rel="%2" href="javascript:;" class="%4">%1</a></td>',
	tbodyCellInactive_src: '<td class="%2 inactive">%1</td>',
	tbodyCellEmpty_src:    '<td class="%1 empty">&nbsp;</td>',

	construct: function() {

		this.rangeFrom = this.rangeFromDefault;
		this.rangeTo = this.rangeToDefault;

		this.holder = dom.create(this.holder_src);
		dom.after(this.holder, this.element);

		var timer, oldValue, blurTimer = 0, voidFocus = false;
		var pickerEvents = {

			element_focusfirst: function() {
				return false;
			},

			element_blur: function() {
				clearTimeout(blurTimer);
				blurTimer = setTimeout(bind(function() {
					this.hideCalendar();
				}, this), 50);
			},

			holder_mousedown: function(e) {
				setTimeout(bind(function() {
					clearTimeout(blurTimer);
					if (blurTimer) {
						voidFocus = true;
						this.element.focus();
					};
					blurTimer = 0;
				}, this), 0);
				return false;
			},

			element_focus: function() {
				if (!voidFocus) {
					this.showCalendar();
				};
				voidFocus = false;
			},

			holder_mouseup: function(e) {  
				this.dispatch(e.target);
				voidFocus = false;
				return false;
			},

			element_keyup: function() {
				if (this.element.value != oldValue) {
					clearTimeout(timer);
					timer = setTimeout(bind(function() {
						this.getSelected();
						if (this.selectedDate) {
							this.showCalendar();
						};
					}, this), 100);
				};
			},

			element_change: function(e){
				var value = e.target.value;

				if (!new RegExp(/\d/).test(value)) {
					e.target.value = '';
				} else if (value = value.toDate(this.calendarFormat)) {
					e.target.value = value.format(this.dateFormat);
				};
			}

		};

		for (var i in pickerEvents) {
			var a = i.split('_');
			events.add(this[a[0]], a[1], bind(pickerEvents[i], this));
		};

		this.element.setRange = bind(this.setRange, this);

		events.dispatch({       
			type: 'datepickerinit',
			target: this.element
		});
	},

	setRange: function(from, to) {
		if (from) {
			this.rangeFrom = (typeof from == 'string')
				? from.toDate(FORMATS.calendarFormat) : from;
		};
		if (to) {
			this.rangeTo = (typeof to == 'string')
				? to.toDate(FORMATS.calendarFormat) : to;
		};
	},

	hideCalendar: function() {
		dom.removeClass(this.holder, 'show-popup-calendar');
		this.holder.style.zIndex = '1';
	},

	showCalendar: function() {
		this.getSelected();
		this.currentLayoutDate = this.selectedDate
			? (this.selectedDate.format('Y/m/') +'1').toDate(FORMATS.calendarFormat)
			: this.inRange(this.today)
				? (this.today.format('Y/m/') +'1').toDate(FORMATS.calendarFormat)
				: ((this.today > this.rangeTo
					? this.rangeTo
					: this.rangeFrom).format('Y/m/') +'1').toDate(FORMATS.calendarFormat);
		
		this.holder.style.zIndex = 10000;
		dom.addClass(this.holder, 'show-popup-calendar');
		this.redraw();
	},

	dispatch: function(target) {   
		var p = target;          
		while (target != this.body) {                 
			if (dom.hasClass(target, 'link-prev')) {   
				return this.scroll(dom.hasClass(target.parentNode, 'year') ? -12 : -1);
			};                   
			if (dom.hasClass(target, 'link-next')) {
				return this.scroll(dom.hasClass(target.parentNode, 'year') ? 12 : 1);
			};                   
			if (target.rel) {          
				return this.select(target);
			};                   
			target = target.parentNode;
		};                       
		p = target = null;
	},

	scroll: function(dir) {
		this.currentLayoutDate.scrollByMonths(dir);
		this.redraw();
	},

	redraw: function() {
		if (!this.body) {
			var tmp = new Date(), row = [];
			for (var i = 0; i < 7; i++) {
				var index = (tmp.getDay() - this.firstDayOfWeek + 7) % 7;
				row[index] = this.theadCell_src.format(
					tmp.D(),
					tmp.l(),
					{ '0': 1, '6': 1 }[tmp.getDay()] ? 'weekend' : 'weekday'
				);
				tmp.tomorrow();
			};
			this.table_src = this.table_src.format(row.join(''), '%1');
			this.body = dom.create(
				this.body_src.format(
					this.prev_src,
					this.next_src,
					this.currentLayoutDate.Y(),
					this.currentLayoutDate.F(),
					this.table_src.format(this.getLayout())
				)
			);
			this.holder.appendChild(this.body);
			this.table = dom(this.body, 'div')[2];
			var b = dom(this.body, 'b');
			this.year = b[0]; this.month = b[1];
			this.yearBody = b[0].parentNode;
			this.monthBody = b[1].parentNode;
		} else {
			this.table.removeChild(this.table.firstChild);
			this.table.appendChild(
				dom.create(this.table_src.format(this.getLayout()))
			);
			this.year.firstChild.nodeValue = this.currentLayoutDate.Y() +'';
			this.month.firstChild.nodeValue = this.currentLayoutDate.F() +'';
		};
		this.refreshControls();
	},

	refreshControls: function() {
		var c = this.currentLayoutDate, e = new Date(c), b = new Date(c);
		e.setDate(e.t());
		var 
			pm = this.inRange(new Date(e).scrollByMonths(-1))  ? 'remove' : 'add',
			nm = this.inRange(new Date(b).scrollByMonths(1))   ? 'remove' : 'add',
			py = this.inRange(new Date(e).scrollByMonths(-12)) ? 'remove' : 'add',
			ny = this.inRange(new Date(b).scrollByMonths(12))  ? 'remove' : 'add';

		dom[pm +'Class'](this.monthBody, 'hide-prev');
		dom[nm +'Class'](this.monthBody, 'hide-next');
		dom[py +'Class'](this.yearBody,  'hide-prev');
		dom[ny +'Class'](this.yearBody,  'hide-next');
	},

	select: function(target) {
		this.element.value = (target.rel + '').toDate(this.calendarFormat).format(this.dateFormat);
        //var a = dom.getByClass('selected', this.table, 'a');
        var a = getElementsByClass('selected', this.table, 'a');
        //alert(this.table);
        if (a[0]) {
			dom.removeClass(a[0], 'selected');
		};         
		a = null;
		dom.addClass(target, 'selected');
		this.hideCalendar();
		this.element.blur();
		events.dispatch({
			type: 'change',
			target: this.element
		});
	},

	getSelected: function() {
		var date = this.element.value.toDate(this.calendarFormat);
		this.selectedDate = this.inRange(date) ? date : null;
	},

	inRange: function(date) {
		return date
			&& date >= this.rangeFrom
			&& date <= this.rangeTo;
	},

	getLayout: function() {
		var curr  = new Date(this.currentLayoutDate),
		    month = this.currentLayoutDate.getMonth(),
		    today = new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate());

		curr.setDate(curr.getDate() - (curr.getDay() - this.firstDayOfWeek + 7) % 7);
		var tbody = [];

		while (curr < this.currentLayoutDate || curr.getMonth() == month) {
			var row = [];
			for (var i = 0; i < 7; i++) {
				var weekDay = { '0': 1, '6': 1 }[curr.getDay()] ? 'weekend' : 'weekday';
				if (curr.getMonth() != month) {
					row[i] = this.tbodyCellEmpty_src.format(weekDay);
				} else {
					if (today.getTime() == curr.getTime()) {
						weekDay += ' today';
					};

					if (this.inRange(curr)) {
						row[i] = this.tbodyCellActive_src.format(
							curr.getDate(),
							curr.format(this.dateFormat),
							weekDay,
							this.selectedDate && this.selectedDate.getTime() == curr.getTime()
								? 'selected' : ''
						);
					} else {
						row[i] = this.tbodyCellInactive_src.format(
							curr.getDate(),
							weekDay
						);
					};
				};
				curr.tomorrow();
			};
			tbody.push(row.join(''));
		};
		return '<tr>' + tbody.join('</tr><tr>') + '</tr>';
	}

});



/**
 * SUBMIT
 *
 * .
 */

ERGO.newWidget({
	name: 'submitMessage',
	template: '<div id="waiting"><div><img src="%2" alt="" /><br />%1</div></div>',
	image: 'css/images/loading.gif',
	message: 'Prašome palaukti',
	messageHolder: null,

	construct: function() {
		this.addEvent('submit', this.showMessage);
		var preload = new Image();
		preload.src = this.image;
		this.messageHolder = dom.create(this.template.format(this.message, this.image));
		this.messageHolder.style.display = 'none';
		document.body.appendChild(this.messageHolder);
	},

	showMessage: function() {
		this.messageHolder.style.display = 'block';
		if (false/*@cc_on!=true&&!window.XMLHttpRequest@*/ && (selects = dom(document, 'select')))
			for (var i = selects.length - 1; i >= 0; i--)
				selects[i].style.visibility = 'hidden';
	}

});


/**
 * PAYER
 *
 * .
 */

ERGO.newWidget({
	name: 'payer',

	construct: function() {

		this.payerFieldset = dom('ContractPayerFields');
		this.addEvent('click', bind(this.togglePayerFields, this));

		events.dispatch({ target: this.element, type: 'click' });
	},

	togglePayerFields: function(e) {
		var fields = dom(this.payerFieldset, 'input');

		if (e.target.checked) {
			for (var i = fields.length - 1; i >= 0; i--) {
				fields[i].value = '';
				fields[i].disabled = true;
			};
			dom.addClass(this.payerFieldset, 'hidden');
		} else {
			for (var i = fields.length - 1; i >= 0; i--) fields[i].disabled = false;
			dom.removeClass(this.payerFieldset, 'hidden');
		};
	}

});

ERGO.newWidget({
	name: 'leasingCompany',

	construct: function() {

		this.codeField = dom('ContractOwnerCompanyCode');
		this.selectField = dom('ContractLeasingCompanyId');
		this.companyNameField = dom('ContractOwnerCompany');
		this.addEvent('change', bind(this.fillCode, this));

		events.dispatch({ target: this.element, type: 'change' });
	},

	fillCode: function(e) {
		value = e.target.options[e.target.selectedIndex].value;
		if (companyCodes[value])
		{
			this.codeField.value = companyCodes[value];
			this.companyNameField.value = e.target.options[e.target.selectedIndex].text;
		}
		else
		{
			this.codeField.value = '';
			this.companyNameField.value = '';
		}
	}
});


/**
 * Assign actions and widgets to run immediately after DOM tree has finished loading
 */

events.add(window || ERGO, 'ready', function() {
	dom.addClass(document.documentElement, browser.browser.toLowerCase());
	dom.addClass(document.body, 'js');

	//ERGO.widgets.printVersion.run(dom('heading'), {});
	//ERGO.widgets.breadcrumb.run(dom('breadcrumb'), {});

	ERGO.widgets.submitMessage.run(dom.getByClass('generic', document), {});
	ERGO.widgets.payer.run(dom('ContractSamePerson'), {});
	ERGO.widgets.datePicker.run(dom.getByClass('datepicker', document), {});
	ERGO.widgets.leasingCompany.run(dom('ContractLeasingCompanyId'), {});
});



/**
 * Prevent IE from caching background images (fixes flicker while hovering)
 */

events.add(window, 'load', function() {
	if (!window.opera) try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {};
});


/**
 * Destroy ERGO object when document is unloaded
 */

events.add(window, 'unload', ERGO.destroy);


// tooltip function
function tooltip() {
  $obj = $('.tooltip'); 
    
  $obj.hover( 
    function(){                                             
        $('span',$obj).hide();
        $('span',this).show();
    },
    function(){
        var self = this;
        setTimeout(function(){$('span',self).hide()},500);
    }
  );

}
