/*
Filename: juliaForm.js
	This file is the part of Julia 1.40 - Simply Programming Universe.

License:
	Please do not use any part of julia without written permission by the authors.

Copyright:
	Copyright (c) 2009 (www.e-future.pl).
*/
function checkstatus(element)
{
    var c = 0,
    con = null;
    var content = element.getParent('div.TabbedPanelsContent');
    while (con = content.getPrevious('div.TabbedPanelsContent')) {
        content = con;
        c++;
    }
    return c;
}

function show_tab(element) {
	
	var tab = element.getParent('div.TabbedPanels');
    if (tab) {
        var cnt = 0;
        var tab_panel_name = 'TabbedPanels' + tab.id.replace('juliaTabID_', '');
		eval(tab_panel_name + '.showPanel(' + checkstatus(element) + ')');
        if (tab.getParent('div.TabbedPanels')) {
            var previousTab = tab.getParent('div.TabbedPanels');
            var tab_panel_name = 'TabbedPanels' + previousTab.id.replace('juliaTabID_', '');
            var cnt = 0;
		   eval(tab_panel_name + '.showPanel(' + checkstatus(tab) + ')');
        };
    };
    try {
        element.focus();
		tab_shown=true;
    } catch(e) {};
}

function isUploaderNeeded()
{
	var i=false;
	$$('input[type=file]').each(function(e){
		i=true;								 
	})
	return i;
}

function fill_former(form)
{
	//nothing
}

function _fill_former(form)
{
	if(form.id=='form1'||form.id=='checkoutForm'){
		var fill_former = new Element("input",{
			'type': 'button',
			'value': 'Fill Form with Random Values',
			'jid': form.id
		}).inject(form,'top');

		fill_former.addEvent('click',function(){
			$(this.get('jid')).getElements('input,select,textarea').each(function(element){
				var ex = element.getPrevious('label');
				if(ex)
				{
					element.value = ex.get('html').replace(/:/g,'');
				}
			})						  
		})
	}
}

function IEDropdownFix()
{
	
	//if(!Browser.Engine.trident) return true; 
//	
//	$$(".PAdrop").addEvent("mouseover",function(e){
//		 this.setStyle("width", "auto");
//	})
//	$$(".PAdrop").addEvent("blur",function(e){
//	 	e = new Event(e);
//		e.stop();
//		this.setStyle("width","");
//	})
//	
//	$$(".PAdrop").addEvent("mouseout",function(e){
//	 	e = new Event(e);
//		e.stop();
//		this.setStyle("width","");
//	})
	
}

function attachFocus()
{
	$$('input,textarea,select').each(function(e){
		if(!e.getProperty('jfocusedAttached'))
		{
			e.addEvent('focus',function(){
				this.addClass('focused');
			})
			
			e.addEvent('blur',function(){
				this.removeClass('focused');
			})
		
			e.setProperty('jfocusedAttached','Yes')
		}
	})	
	IEDropdownFix();
}

function showElementValidationMessage(element,msg)
{
	form = $(element.getProperty('ParentForm'));
	if(!form) return true;
	var el = $('jmsg'+form.id+element.id);
	if (!el && msg) {
		var el = new Element('span', {
			'id': 'jmsg'+form.id+element.id,
			'class': 'julia_validation_error'
		});	
		el.setStyle("opacity", 0);
		
		next = element.getNext('input');
		if(next){
			if(!next.id.contains('_search')){
				next = null;	
			}	
		}
		el.set('html', msg).injectAfter(next?next:element).morph({'opacity':'1'});
		el.setStyle('width',element.getStyle('width'));
	}
	else
	{
		if (!msg) {
			if (el) {
				if(!$('V_noOK'))
				{
					el.set('html',jlang_value_ok).morph('.eia');
				}
				else
				{
					var myTween = new Fx.Tween($(el),'opacity');
					myTween.addEvents({
						'complete': function() {
							el.dispose();
						}
					});
					myTween.start('opacity', 1, 0);
				}
			}
		} 
		else
		{
			 if (el && msg != el.get('text')) {
				var myTween = new Fx.Tween($(el),'opacity');
				myTween.addEvents({
					'complete': function() {
						el.set('html', msg);
						el.tween('opacity', 0, 1);
						el.removeClass('eia');
					}
				});
				myTween.start('opacity', 1, 0);
				$(el).morph('.julia_validation_error');
			}
		}
	}
}

function getElementValue(element) {
	if (element) {
		switch (element.type.toLowerCase()) {
		case 'checkbox':
		case 'radio':
			if(!this.form)return true;
			var group = this.form[element.getProperty("name")];
			if (group.length > 0) {
				for (x = 0; x < group.length; x++) {
					if (group[x].checked) {
						return true;
					}
				}
			} else {
				if (group.checked) {
					return true;
				}
			}
			break;
		default:
			return element.value;
		}
	}
}

function getAllValidateElements(area)
{
	return area.getElements('*[j^=V:]');
}

function validateElement(el)
{
	if(!el) return true;
	var jFieldName,N,M,If,JN,allM='',SM;
	var l = $(el).getPrevious('label');
	if(l)
	{
		jFieldName = l.innerHTML.replace(':','');
	}
	else
	{
		jFieldName = el.name.replace(/_/g, " ");
	}
	N=jFieldName;
	var pCache = el.getProperty('j').split(';');
	pCache.each(function(j){
		var jp = j.split(':');
		if(jp[0]!=''&&jp[0]!='V')eval(jp[0]+'="'+jp[1]+'";'); //czytanie parametrów np. N:moja nazwa pola,M: wiadomosc;	
	});
	if(If)
	{
		var jp = If.split(':');	
		if(getElementValue($(If))=='')
		{
			return true;
		}
	}
	//rozdzielone na 2 osobne loopy zeby parametry mogly byc ulozone w dowolnej kolejnosci.
	var req=false;
	pCache.each(function(j){
		
		var jp = j.split(':'),subparam=null;
		if(jp[0]=='V'){
			jp[1].split(',').each(function(parameter) {
				if (parameter.contains('|')) {
					subparam = parameter.split('|')[1];
					parameter = parameter.split('|')[0];
				}
				switch (parameter) {
                    case 'w':
						if (!getElementValue(el)) {
							req = true;
							if (M) {
								allM += M;
							} else {
								allM += jlang_field + ' "' + N + '" ' + jlang_is_required;
							}
						}
					break;
					case 'ajax':
						if (allM==''&&getElementValue(el) != '' && getElementValue(el) != el.getProperty('jajax')) {
                            var CCurl = julia_base_url + 'event/val_ajax' + '/' + subparam + '/' + escape(getElementValue(el).replace(/\@/g, '__at__'));
                            if($j.growl)$j.growl('', jlang_CheckingLogin+', '+jlang_PleaseWait+'..');
                            var aj_response = new Request.HTML({
                                onComplete:function()
								{
									 if($j.growl)$j.growl('', jlang_Ready+'.');
								},
								url: CCurl,
                                method: 'get',
                                async: false
                            }).send();

                            if (aj_response.response.text) {
                                if (!aj_response.response.text.contains('Error')) {
                                    allM += N + ' ' + jlang_exists_select_another_one;
                                } else {
                                    if (aj_response.response.text.contains('A Database Error Occurred')) {
                                        var a = aj_response.response.text.split('</p><p>')[1];
                                        a = a.replace('</p><p>', '\n');
                                        a = a.replace('</div>', '');
                                        a = a.replace('</body>', '');
                                        a = a.replace('</html>', '');

                                        alert('Database Error: \n' + a);

                                    } else {
                                        if (aj_response.response.text.contains('PHP Error wa')) {
                                            var a = aj_response.response.text.split('<p>Message:')[1];
                                            a = a.split('</p>')
                                                a = a.replace('</p><p>', '\n');
                                            a = a.replace('</div>', '');
                                            a = a.replace('</body>', '');
                                            a = a.replace('</html>', '');
                                            alert('Database Error: \n' + a);

                                        }
                                    }
                                }
                            } else {
                                el.setProperty('jajax', getElementValue(el));
                            }
                        }
                        break;
					
					
					
					case 'i':
                        var i_e;
                        val = this.val;
                      
					   subparam.split(' ').each(function(elem) {
                            if (getElementValue($(el)) != getElementValue($(elem))) {
                                i_e = true; 
                            }
                        });
                        if (i_e) {
                            allM += N + ' i ' + subparam.replace(' ', ', ').replace(/_/g, " ") + ' ' + jlang_must_be_the_same;
                        }
                    break;
					case 'lub':
						lub_e=false;
						subparam.split(' ').each(function(el) {
                            if (getElementValue($(el)) != '') {
                                lub_e = true;
                            }
                        });
                        var labels_text='';
						labels = subparam.split(' ');
						labels.each(function(e){
							if($(e))
							{
								var l = $(e).getPrevious('label').innerHTML.replace(':','');
								labels_text+=', '+l;
							}
						})
						labels_text = labels_text.substring(2);
						if(getElementValue(el)+''!='')
						{
							lub_e=true;
						}
						
						if (!lub_e) {
                            allM += jlang_fill_at_least_one_of_fields + ' "' + N + '", "' + labels_text + '".';
                        }
                    break;
					case 'email':
                        if (getElementValue(el) && !/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i.test(el.value)) {
                            allM += jlang_put_correct_email_address;
                        }
                    break;
                    case 'float':
                        el.value = getElementValue(el).replace(' ','').replace('.',',');
						if (getElementValue(el) && !/^[-+]?\d*\,?\d*$/.test(el.value)) {
                            allM += N + ' ' + jlang_must_be_a_number;
                        }
                    break;
                    case 'liczba':
                        if(getElementValue(el) && !/^([-]|[0-9])[0-9]*$/.test(el.value)) {
                            allM += N + ' ' + jlang_must_be_a_whole_number;
                        }
                    break;
					case 'npl':
                        if(getElementValue(el) && !/^([0-9]|[a-z]|[A-Z]|_)*$/.test(el.value)) {
                            allM += N + ' ' + jlang_can_have_characters + ' [a-z][A-Z][0-9].';
                        }
					break;
                    case 'tpl':
                        if(getElementValue(el) && !/^([0-9]|[a-z]|[A-Z]|_|-)*$/.test(el.value)) {
                            allM += N + ' ' + jlang_can_have_characters + ' [a-z][A-Z][0-9].';
                        }
                    break;
					case 'login':
                        if(getElementValue(el) && !/^([0-9]|[a-z]|[A-Z]|_|-|\.|@|\+)*$/.test(el.value)) {
                            allM += N + ' ' + jlang_can_have_characters + ' [a-z][A-Z][0-9] @ + - _ .';
                        }
					break;
					case 'maxlength':
                        val = this.val;
                        if (waliduj && this.val($(element)).length >= subparam) {
                            komunikat += swoja_nazwa + ' ' + jlang_cant_be_more_than + ' ' + subparam + ' ' + jlang_characters;
                        }
                    break;
					case 'date':
							var date_string = getElementValue(el)
						    var days = [0,31,28,31,30,31,30,31,31,30,31,30,31];
							var year, month, day, date_parts = null;
							var rtrn = false;
							var decisionTree = {
								'm/d/y':{
									're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})$/,
									'month': 1,'day': 2, year: 3
								},
								'mm/dd/yy':{
									're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{2})$/,
									'month': 1,'day': 2, year: 3
								},
								'mm/dd/yyyy':{
									're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/,
									'month': 1,'day': 2, year: 3
								},
								'y/m/d':{
									're':/^(\d{2}|\d{4})[./-](\d{1,2})[./-](\d{1,2})$/,
									'month': 2,'day': 3, year: 1
								},
								'yy/mm/dd':{
									're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{1,2})$/,
									'month': 2,'day': 3, year: 1
								},
								'yyyy/mm/dd':{
									're':/^(\d{4})[./-](\d{1,2})[./-](\d{1,2})$/,
									'month': 2,'day': 3, year: 1
								}
							};
							var test = decisionTree['yyyy/mm/dd'];
							if (test) {
								date_parts = date_string.match(test.re);
								if (date_parts) {
									year = date_parts[test.year];
									month = parseInt(date_parts[test.month]);
									day = parseInt(date_parts[test.day]);

									test = (month == 2 && 
											isLeapYear() && 
											29 || 
											days[month] || 0);

									rtrn = 1 <= day && day <= test;
								}
							}

							function isLeapYear() {
								return (year % 4 != 0 ? false : 
									( year % 100 != 0? true: 
									( year % 1000 != 0? false : true)));
							}
							if(!rtrn){
								allM += jlang_field + ' "' + N + '" ' + jlang_must_be_a_date;
							};
                    break;
				}
			});
		}			 
	});
	showElementValidationMessage(el,allM?(M&&req?M:(SM?SM:allM)):'');
	return allM!=''?false:true;
	
}

var ffe=null; ; //focused form element element;
function jForm(form_id) // Form Tools init / form handling.
{
	if(!form_id)
	{
		form_id = $$('form');
	}
	form_id.each(function(form) {
		getAllValidateElements(form).each(function(element) {
			var p = element.getProperty('j');
			element.setProperty('ParentForm',form.id);
			if (p && p.contains('V:w')) {
				var a = element.getParent('div.jc').addClass('required');
			};
			if (element.addEvent) {
				element.addEvent('blur', function(e) {
					validateElement(element);
				}.bind(this));
				element.addEvent('focus', function(e) {
					ffe=this;
				}.bind(this));
			};
		})
		
		fill_former(form);
		
		form.addEvent('submit', function(e) {
			if(tinyMCE) tinyMCE.triggerSave(); //fix for second time save ajax form bug...
			var errors = 0;
			fnv=null;
			getAllValidateElements(this).each(function(element){
				var v = validateElement(element);
				if(!v)errors++;
				if(!fnv&&!v)fnv=element;
				
			})
			if(errors>0){
				if(julia_scroll_to&&fnv)
				{
					if (fnv.type != 'hidden') {
						show_tab(fnv);
					};
					julia_scroll_to(fnv);
				}
				else
				{
					try {
                         if (fnv.type != 'hidden') {
							show_tab(fnv);
						};
						fnv.focus();
                     } catch(e) {}
				}
				return false;
			}
			else
			{
				if($('julia_processing'))
				{
					$('julia_processing').setStyle('display','block').addClass('julia_validation_error');
					this.getElements('input[type=image],input[type=submit]').each(function(e){e.setStyle('display','none');})	
				}
				else
				{
					if(control_seg!='jad')this.getElements('input[type=image],input[type=submit]').each(function(e){e.disabled='disabled';})
				}
			}
			
			
			
			
			//var action = (!this.action.contains('#plempl')&&this.action!='#')?this.action:'Zdefiniuj atrybut action dla formy id: '+this.id+'.';
			//form.action = action;
			var uploader_needed = isUploaderNeeded();
			if(uploader_needed){
				this.setProperty('enctype','multipart/form-data');
				if(!uploader_iframe){
					juliaLoading();
					//if($j&&$j.growl)$j.growl('',jlang_db_updating_data+' '+jlang_db_please_wait);
					uploader_iframe = new Element('iframe',{'id':'julia_uploader','name':'julia_uploader','src':'#','style':'width:0px;height:0px;border:0px solid #fff;'})
					uploader_iframe.injectAfter(f);	
					uploader_iframe.addEvent('load',function(){
						
						var resultHTML=$('julia_uploader').contentWindow.document.body.innerHTML;
						if(julia_parse_error(resultHTML)){
							if($j&&$j.growl)$j.growl('',julia_add_record_message);	
							
							juliaLoaded();
							
							(function(){$$('.loading').each(function(element){
								element.set('html','&nbsp;&nbsp;');
							})}).delay(1000);
							//alert(resultHTML);
							//$exec(resultHTML);
							$$('input[type=file]').each(function(e){
								e.value='';							 
							})
							
							if(window.top.julia_get_data){
								window.top.julia_get_data();
							}
							
						};									 
					})
				}
				//f.target ='_blank';
				f.target ='julia_uploader';
				//f.target ='_blank';
				f.enctype="multipart/form-data";
				f.method="post";
				f.submit();
				return true;
				
				//f.target ='_blank'; above submit moved.
			}
			
			var s = '';
			if(!form.getElement('#noHistory'))
			{
				form.getElements('input').each(function(el){
					if(el.value!='')s+='/'+el.name+'/'+el.value;
								   
				})
			}
			if((form.getProperty('jdestination')||control_seg=='jad')&&form.getProperty('j')!='noajax')
			{
				julia_keep=$random(1,20000);
				if($j.historyLoad&&!form.getElement('#noHistory'))$j.historyLoad(juliaParseURL(form.action+s+(julia_keep?'/keep/'+julia_keep:'')+'-juliasep-'+default_container+'-juliasep-'),true);
				var date=new Date(); 
				var empty = new Request.HTML({ //request HTML needed for eval response.
					url: (control_seg=='jad'&&form.action=='')?julia_add_record_template_url:(form.action+'/rnd/P'+date.getMinutes()+date.getSeconds()+'/type/_ajax/'),
					evalScripts:true,
					evalResponse:true,
					onRequest: function(request){
						juliaLoading(); //if(control_seg=='jad')
						if($j&&$j.growl)$j.growl('',jlang_db_please_wait);
						julia_message(jlang_db_please_wait+'..');
					},
					onComplete: function(request,e,responseHTML){
						request=request+' '; //fix for
						if(julia_parse_error(responseHTML)){
							if($j&&$j.growl)$j.growl('',julia_add_record_message?julia_add_record_message:jlang_Done);	
							juliaLoaded();
							if(responseHTML){
								var fgp = form.getProperty('jdestination');
								if(fgp){
									$(fgp).set('html',responseHTML)
								}	
								
								if(julia_parse_links){julia_parse_links('#'+fgp)};
								jForm($$('#'+fgp+' form'));
								julia_edit_areas_highlighting();
								//alert('a');
								if(julia_scroll_to&&$('user_nav_id'))
								{
									julia_scroll_to('user_nav_id');
								}
							}
							
							//(function(){$$('.loading').each(function(element){
//								element.removeClass('ajax-loaded');
//								element.addClass('ajax-loading');
//								element.set('html','&nbsp;&nbsp;');
//								})
//							}).delay(1000);
						};
						if(control_seg=='jad')juliaLoaded();
						julia_message(jlang_PageLoadedSuccessfuly);
					},
					onFailure: function(instance){
						julia_parse_error(instance.responseText);
					}
				}).post(this);
				e = new Event(e);
				e.stop();
				return true;
			}
			
			e = new Event(e);
			e.stop();
			juliaLoading();
			this.submit();
		});
	});
	
	
}

function julia_parse_error(text_in)
{
	if(!text_in)return true;
	if(text_in.contains('#j#juliaError#j#')){
		if($j&&$j.growl)$j.growl('',text_in.split('#j#juliaError#j#')[1]);
		return false;
	}
	else
	{
		if(text_in.contains('A Database Error Occurred')){
			var a = text_in.split('</p><p>')[1];
			a = a.replace('</p><p>','\n');
			a = a.replace('</div>','');
			a = a.replace('</body>','');
			a = a.replace('</html>','');
			alert('Database Error: \n'+a);
			return false;
		}
		else
		{
			if(text_in.contains('PHP Error wa')){
				var a = text_in.split('<p>Message:')[1];
				var temp = a.split('</p>')
				a = a+temp[1]+'\n'+temp[2]+'\n'+temp[3]+'\n';
				a = a.replace('</p><p>','\n');
				a = a.replace('</div>','');
				a = a.replace('</body>','');
				a = a.replace('</html>','');
				alert('PHP Error: \n'+a);
				return false;
			}else{
				//window.top.MochaUI.notification(julia_add_record_message);
				return true;
			}
		}
	}
}

window.addEvent('domready', function() {
	jForm();
});
