/*Inicializace formulare pro vlozeni poptavky*/

var lbox = null;

function insertText(text) {
	$('popis').value = (text.replace(/<br>/gi,"\n"));
	$('popis').focus();
}


var selectable = true;
window.addEvent('domready', function(){
	var tips = {
		initialize:function(){
			this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
		},
		onShow: function(toolTip) {
			this.fx.start(1);
		},
		onHide: function(toolTip) {
			this.fx.start(0);
		}
	}
	var Tips2 = new ToolTips($$('input, textarea, select'), tips);
	// Prilohy
	var fAt = new FileAttachments($('attachment'), $('attachmentsContainer'));

	if ((vyber == 1 || vyber == 2) && send) {
        displayForm(vyber);
        location.replace('#infoInquiry');
	}
	
	var check = new CheckForm('insertIquiryForm');
	
	/*LightBox*/
	var width = window.ie ? 675 : 655;
	//lbox = new LightBox($$('span#helpAndExamples a'), 'http://www.epoptavka.cz/include/insert_inquiry/component.inquiry_helper.php');
	lbox = new LightBox($$('span#helpAndExamples a, span#helpAndExamplesMain a'), 'http://www.123profit.hu/include/insert_inquiry/component.inquiry_helper.php', {'width':width, 'height': 650});
	lbox2 = new LightBox($$('a#exampleInquiry'), 'http://www.123profit.hu/include/insert_inquiry/component.inquiry_examples.php', {'width':740});
    lbox3 = new LightBox($$('a.personalities'), 'http://www.123profit.hu/include/insert_inquiry/component.personalities_safety.php', {'width':400, height: 160});
	lbox3 = new LightBox($$('a#beginTextExample'), 'http://www.123profit.hu/', {'width':800, height: 580});
	
	/** TextArea samo roztahovac **/
	var txtAreare = new ResizeArea($$('#popis'));

	/** Aktivni tlacitko "poptavku zadava" **/
	
	if (selectable) {
		$('addingTitle').setStyle('cursor', 'pointer');
		$('addingTitle').addEvent('click', function(event) {
		    if ($('r1').checked == false) {
	            displayForm(1);
			} else {
	            displayForm(2);
			}
		});
	}
	
});
/*Inicializace konec*/

var CheckForm = new Class({
	formID : null,
	options : {
	    checkScript : 'http://www.123profit.hu/config/insert_inquiry.config.php'
	},
	initialize: function(formID, options) {
		this.formID = formID;
		this.setOptions(options);
		$(this.formID).$tmp.obj = this;
		/*$(this.formID).addEvent('submit', function(e) {
		    e = new Event(e);
		    e.stop();
		    var urlQuery = '?action=validityAll';
			el = new Element(this);
			var toCheck = new Object();
			el.getElementsBySelector('input, textarea, select').each(function(element) {
				value = element.value;
				name = element.name;
				if (element.type == ('radio' || 'checkbox')) {
					name = element.name+'[' +element.value+ ']';
					value = element.checked;
				}
				urlQuery += '&field_'+name+'='+value;
			});
			var jSonRequest = new Json.Remote(el.$tmp.obj.options.checkScript+urlQuery, {onComplete: function(object){
				if (object.result.length == 0){
                    this.submit.click();
					
				} // Formular je v poradku!
				object.result.each(function(id){
				    $(id).addClass('errorFormField');
				    el = new Element($(id).parentNode);
					el.getElementsByClassName('error').each(function(el) {
						el.setStyle('display', 'block');
					});
					window.fireEvent('scroll');
				});
			}.bind(this)}).send();
		});*/

		elements = $$('form#'+this.formID+' input, form#'+this.formID+' textarea, form#'+this.formID+' select');
        elements.each(function(element){
			element.$tmp.obj = this;
			element.addEvent('change', function(e){
			    e = new Event(e);
				this.$tmp.obj.checkElement(this);
			});
			element.addEvent('blur', function(e){
			    e = new Event(e);
				this.$tmp.obj.checkElement(this);
			});
		}.bind(this));
	},
	
	checkElement: function(element) {
		/*var jSonRequest = new Json.Remote(this.options.checkScript+'?action=validity&field='+element.name+
			'&value='+element.value, {onComplete: function(object){
			if (!object.result) {
				el = new Element(this.parentNode);
				this.parentNode.getElementsByClassName('error').each(function(el) {
					el.setStyle('display', 'block');
				});
				this.addClass('errorFormField');
				window.fireEvent('scroll');
			} else {
				el = new Element(this.parentNode);
				this.parentNode.getElementsByClassName('error').each(function(el) {
					el.setStyle('display', 'none');
				});
				this.removeClass('errorFormField');
				window.fireEvent('scroll');
			}
		}.bind(element)}).send();*/
	}
});

CheckForm.implement(new Events, new Options);

var ToolTips = new Class({
	options: {
		onShow: function(tip){
			tip.setStyle('visibility', 'visible');
		},
		onHide: function(tip){
			tip.setStyle('visibility', 'hidden');
		},
		maxTitleChars: 30,
		showDelay: 100,
		hideDelay: 100,
		className: 'toolTip',
		offsets: {'x': 20, 'y': 10},
		fixed: true
	},

	visible : null,
	wposition: 'top',
	focused: null,

	initialize: function(elements, options){
		window.addEvent('scroll', function(event) {
			if (this.visible) {
				this.position(this.visible);
			}
		}.bind(this));
		this.setOptions(options);
		this.toolTip = new Element('div', {
			'class': this.options.className,
			'styles': {
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'visibility': 'hidden'
			}
		}).inject(document.body);
		this.wrapper = new Element('div').inject(this.toolTip);
		this.em = new Element('em').injectAfter(this.wrapper);
		this.em.addClass("real");
		this.wposition = 'top';
		$$(elements).each(this.build, this);
		if (this.options.initialize) this.options.initialize.call(this);
	},

	build: function(el){
		el.$tmp.myTitle = (el.title || false);
		if (el.title){
			var dual = el.title.split('::');
			if (dual.length > 1){
				el.$tmp.myTitle = dual[0].trim();
				el.$tmp.myText = dual[1].trim();
			} else {
				el.$tmp.myText = el.title;
			}
			el.removeAttribute('title');
		} else {
			return;
		}
		el.addEvent('focus', function(event){
			e = new Event(event);
			this.visible = e.target;
			this.start(el);
			if (!this.options.fixed) this.locate(event);
			else this.position(el);
		}.bind(this));
		if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
		var end = this.end.bind(this);
		el.addEvent('blur', end);
		el.addEvent('trash', end);
	},

	start: function(el){
		if (this.focused != el) {
			this.focused = el; 
			this.wrapper.empty();
			if (el.$tmp.myTitle){
				this.wrapper.setHTML(el.$tmp.myTitle);
			}
			$clear(this.timer);
			this.timer = this.show.delay(this.options.showDelay, this, el);
		}
	},

	end: function(event){
		this.focused = null;
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},

	position: function(element){
		var poss = element.getPosition();
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
		var prop = {'x': 'left', 'y': 'top'};
		
				
		for (var z in prop){
			var pos = poss[z] - ((z == 'y') ? tip[z] : 0) + this.options.offsets[z];
			if ((z == 'y') && (poss['y'] - tip['y'] + this.options.offsets['y'] - scroll['y'] < 0)) {
				pos = poss[z]  + this.options.offsets[z];
				if (this.wposition == 'top') {
					this.em.remove();
					this.em = new Element('em').injectBefore(this.wrapper);
					this.em.addClass("rev");
					this.wposition = 'down';
				}
			} else {
				if (this.wposition == 'down') {
					this.em.remove();
					this.em = new Element('em').injectAfter(this.wrapper);
					this.em.addClass("real");
					this.wposition = 'top';
				}
			}
			this.toolTip.setStyle(prop[z], pos);
		};
	},

	locate: function(event){
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
		var coo = this.toolTip.getCoordinates();
		var prop = {'x': 'left', 'y': 'top'};
		for (var z in prop){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
			this.toolTip.setStyle(prop[z], pos);
		};
	},

	show: function(el){
		this.visible = el;
		if (this.options.timeout) this.timer = this.hide.delay(this.options.timeout, this);
		this.fireEvent('onShow', [this.toolTip]);
	},

	hide: function(){
		this.visible = null;
		this.fireEvent('onHide', [this.toolTip]);
	}

});

ToolTips.implement(new Events, new Options);

var FileAttachments = new Class({
	container: null,
	className : 'FileAttachments',
	pointer: 0,
	inputs: 0,
	anchor : null,
	
	initialize: function(anchor, container) {
		this.container = container;
		this.anchor = anchor;
		anchor.setAttribute('onclick', 'return false;');
		anchor.setHTML(PrilozitSoubor);
		anchor.addEvent('click', function(e) {
			e = new Event(e);
			e.stop();
			if (this.inputs < 5) {
				this.add();
   			}
		}.bind(this));
	},
	
	add: function() {
		cont = new Element('div', {'class': 'element'}).inject(this.container);
		this.inputs++;
		if (this.inputs > 0) {
			this.anchor.setHTML(PrilozitDalsiSoubor);
		}
		if (this.inputs >= 5) {
			this.anchor.setStyle('display', 'none');
		}
		/**
         * IE9 saje a nedokaze new element input
         */

		/*file = new Element('input', {
			'type': 'file',
			'id': 'file_'+this.pointer,
			'name' : 'fileAttachment['+(this.pointer)+']'
		}).inject(cont);*/

        fileInput = '<input type="file" id="file_' + this.pointer + '" name="fileAttachment[' + this.pointer + ']" />';
        cont.innerHTML = fileInput;

		deleteLink = new Element('a', {'href': '#', 'onclick' : 'return false;'}).inject(cont);
		dSpan = new Element('span').inject(deleteLink).setHTML('Odstrani');
		deleteLink.$tmp.input = cont;
		deleteLink.$tmp.fAtt = this;
		var point = this.pointer++;
		deleteLink.addEvent('click', function(e){
			e = new Event(e);
			e.stop();
			this.$tmp.fAtt.inputs--;
			this.$tmp.input.remove();
	  		if (this.$tmp.fAtt.inputs == 0) {
						this.$tmp.fAtt.anchor.setHTML(PrilozitSoubor);
			}
	  		if (this.$tmp.fAtt.inputs < 5) {
						this.$tmp.fAtt.anchor.setStyle('display', '');
			}

		});
	}
	
});

window.addEvent('domready', function(){
	if ($('tabsInsertInquiry')) {
		$$('#tabsInsertInquiry input').each(function(element){
			element.addEvent('click', function(e){
				if (selectable) {
					e = new Event(e);
					e.target.checked = true;
					name = e.target.id;
					displayForm(name.charAt(1));
				}
			})
		});
	}
});

function displayForm(id) {
	removeAll();
	
	$$('.infoNS').each(function(element){
		element.removeClass('infoNS');
		element.addClass('info');
	});
	
	if ($('l'+id) != null) {
		$('l'+id).addClass('active');
	}
	if ($('r'+id) != null) {
		$('r'+id).checked = true;
	}
	
	if ($('form'+id) != null) {
		$('form'+id).setStyle('display', '');
	}

	return false;
}

function removeAll(){
	if ($('l1') != null) $('l1').removeClass('active');
	if ($('l2') != null) $('l2').removeClass('active');
	
	if ($('form1') != null) {
		$('form1').setStyle('display', 'none');
	}
	if ($('form2') != null) {
		$('form2').setStyle('display', 'none');
	}
}


var LightBox = new Class({
	name: $time().toString() + '_lightBoxIframe',
	options : {
	    'positionTop' : 'center',
	    'positionLeft' : 'center',
	    'width' : '800',
	    'height' : '600',
	    'className' : 'lightBox'
	},
	
	loaded: false,
	
	link: null,
	
	
	initialize : function(elements, link, options) {
	    this.setOptions(options);
		this.link = link;
		elements.each(function(element) {
			element.$tmp.lightBox = this;
			element.addEvent('click', function(e) {
			    e = new Event(e);
			    e.stop();
			    e.target.$tmp.lightBox.display(e.target);
			});
		}.bind(this));

		this.lightBox = new Element('div', {
			'class' : this.options.className,
			'styles' : {
				'width' : this.options.width,
				'height' : this.options.height,
				'position' : 'absolute',
				'left' : '0',
				'top' : '0',
				'display' : 'none'
			}
		}).inject(document.body);
		
		this.navig = new Element('div', {
			'styles' : {
				'width' : '100%',
				'height' : '22px'
			}
		}).inject(this.lightBox);

		/*this.iFrame = new Element('iframe', {
			'src':link,
			'frameborder' : 0,
			'name' : this.name,
			'styles' : {
				'width' : '100%',
				'height' : this.options.height - 22
			}
		}).inject(this.lightBox);*/


		/*var doc = this.iFrame.contentWindow.document;*/
		//alert(doc);
		/*doc.extend = Object.extend;
		doc.extend({
			addEvent: Element.prototype.addEvent,
			removeEvent: Element.prototype.removeEvent,
			removeEvents: Element.prototype.removeEvents,
			getElements: document.getElements,
			addListener: document.addListener,
			removeListener: document.removeListener
		});*/
		/*back = new Element('a', {'class': 'back', 'href':'#'}).inject(this.navig);
		back.$tmp.lightBox = this;
		back.addEvent('click', function(e){
		    e = new Event(e);
		    e.stop();
		    history.go(-1);
		});

		forward = new Element('a', {'class': 'forward', 'href':'#'}).inject(this.navig);
		forward.$tmp.lightBox = this;
		forward.addEvent('click', function(e){
		    e = new Event(e);
		    e.stop();
		    history.go(1);
		});*/

		closeBtn = new Element('a', {'class': 'close', 'href':'#'}).inject(this.navig);
		closeBtn.$tmp.lightBox = this;
		closeBtn.addEvent('click', function(e){
		    e = new Event(e);
		    e.stop();
		    e.target.$tmp.lightBox.hide();
		});

		/*spannBack = new Element('span').inject(back).setHTML('Zpět');
		spannForward = new Element('span').inject(forward).setHTML('Vpřed');*/
		spannClose = new Element('span').inject(closeBtn).setHTML('Zavřít');


		this.cover = new Element('div', {
			'styles' : {
				'z-index' : '99999',
				'position' : 'absolute',
				'left' : '0',
				'top' : '0',
				'width' : document.body.getCoordinates().width,
				'height' : document.body.getCoordinates().height,
				'background-color' : '#000',
				'opacity' : '0.5',
				'display' : 'none'
			}
		}).inject(document.body);

        this.cover.$tmp.lightBox = this;

        this.cover.addEvent('click', function(e){
			e = new Event(e);
			e.stop();
			e.target.$tmp.lightBox.hide();
		});

		window.addEvent('scroll', function(event) {
			//this.locate();
		}.bind(this));
		this.locate();
	},
	
	locate : function() {
		var left = 0;
		var top = 0;
		var coor = this.lightBox.getCoordinates();
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		if (this.options.positionLeft == 'center')
			left = (win.x/2) - (coor.width/2) + scroll.x;
		if (this.options.positionLeft == 'right')
			left = (win.x) - (coor.width) + scroll.x;
		if (this.options.positionTop == 'center')
			top = (win.y/2) - (coor.height/2) + scroll.y;
		if (this.options.positionTop == 'bottom')
			top = (win.y) - (coor.height) + scroll.y;
		this.lightBox.setStyle('left', left);
		this.lightBox.setStyle('top', top);
		this.cover.setStyle('width', document.body.getCoordinates().width);
		this.cover.setStyle('height', document.body.getCoordinates().height);
	},

	display : function(element) {
		/*this.iFrame.src = this.link + '?' + element.rel;
		this.cover.setStyle('display', 'block');
		this.lightBox.setStyle('display', 'block');
		this.locate();*/
		window.open(this.link + '?' + element.getAttribute('rel'),
					'lightBox', 'location=no,status=no,toolbar=no,scrollbars=yes,menubar=no,width='+this.options.width+',height='+this.options.height+',left=20,top=40');
	},

	hide: function() {
		this.cover.setStyle('display', 'none');
		this.lightBox.setStyle('display', 'none');
	}
	
});

LightBox.implement(new Events, new Options);

var ResizeArea = new Class({
	options: {
		'onResize': function(field){
			if (!field.$tmp.resizeArea['resized'] || !this.options.resizeOnce) {
				var myFx = new Fx.Style(field, 'height').start(field.getStyle('height').toInt(),
					field.getStyle('height').toInt() + this.options.resizeValue);
			}
		},
		'resizeOnce': true,
		'resizeValue': 100
	},
	
	initialize : function(elements, options) {
		this.setOptions(options);
		elements.each(function(element) {
			/**
			 * Pridani this objektu do struktury elementu
			 */
			 element.$tmp.resizeArea = new Object();
			 element.$tmp.resizeArea['obj'] = this;
			 element.$tmp.resizeArea['resized'] = false;
			/**
			 * Pridat akci na zmenu, musis se prepocitat sirka
			 */
			 element.addEvent('keyup', function(event) {
                element.$tmp.resizeArea['obj'].change(this);
			 });
		}.bind(this));

		this.testerDiv = new Element('div', {
			'styles': {
				'position' : 'absolute',
				'top' : '0px',
				'left' : '0px',
				'display' : 'none'
			}
		}).inject(document.body);
	},
	
	change : function(element) {
		coordinates = element.getCoordinates();
		styles = {
			'width' : coordinates.width,
			'display' : 'block',
			'font-family' : element.getStyle('font-family'),
			'font-size' : element.getStyle('font-size'),
			'height' : 'auto',
			'left' : '-500000px'
		}
		this.testerDiv.setStyles(styles);
		this.testerDiv.setHTML(element.value.replace(/\n/g, "<br>"));
		testerCoordinates = this.testerDiv.getCoordinates();
		if (testerCoordinates.height + 20 >= coordinates.height) {
			/**
			 * Velikost textu je vetsi nez velikost area
			 */
			this.fireEvent('onResize', [element]);
			element.$tmp.resizeArea['resized'] = true;
		}
		this.testerDiv.setStyle('display', 'none');
		
	}

});

ResizeArea.implement(new Events, new Options);

