/**
 * pksFrom
 * @author Tomasz Woliński
 */


function _get(h){
	var vars = [], hash;
	
	var tmp = window.location.href.slice('?');
	
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	
	for(var i = 0; i < hashes.length; i++){
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		
		if(hash[1]!==undefined){
			hash[1] = hash[1].replace('#','');
			vars[hash[0]] = hash[1];
		}	
	}
	
	if(h){
		return vars[ h ];
	}
	
	return vars;
}

var pksForm = Class.create({
	debug : 0,	
	prefix : 'tx_pksform_pi1',
    url	: 'index.php?eID=pks_form',
	calendarFieldsClass	: 'calendarField',
	form	: 'form',				
	
	doR				: function(el){
		try {
			var inputs = [];
			
			var h = el.innerHTML;

			inputs.push('<input type="hidden" name="'+pksForm.prefix+"["+'trip_time'+']" value="'+h+'" />');
			inputs.push('<input type="hidden" name="'+pksForm.prefix+"["+'type_submit'+']" value="0" />');
			var values = $(el.parentNode).getAttribute('v').split(',');
			var names = ["trip_date","reservation_type","city_to","city_from","country_from","country_to"];
			var map = ['cars','trucks','pedestrians'];

			inputs.push('<input type="hidden" name="'+pksForm.prefix+"["+'action'+']" value="'+map[parseInt(values[1])-1]+'" />');
			
			for(i=0; i<values.length; i++){
				inputs.push('<input type="hidden" name="'+pksForm.prefix+"["+names[i]+']" value="'+values[i]+'" />');
			};		
	
			$(pksForm.form).insert(inputs.join(''));

			window.setTimeout(function() {
				 pksForm.form.submit();}, 
				 600
			);	
		
		}catch(e){
			if(pksForm.debug)alert(e)
		}
		
		return false;
	},
	
	/**
	 * przechodzi do formularza z odpowiednio wypełnionymi polami
	 */
	doReservation	: function(values){
		values = values.split(',');
	
		var names = ["trip_time","trip_date","reservation_type","city_to","city_from","country_from","country_to","type_submit","action"];

        var inputs = [];
		for(i=0; i<values.length; i++){
			inputs.push('<input type="hidden" name="'+pksForm.prefix+"["+names[i]+']" value="'+values[i]+'" />');
		};
        
		$(pksForm.form).insert(inputs.join(''));
		window.setTimeout(function() {
			 pksForm.form.submit();}, 
			 600
		);
		
		return false;
	},

	/**
	 * obsługa formularza na stronie głównej
	 * zmiana państwa początkowe/docelowe i połączenia
	 */
	changeForm		: function(el,reservationType){
		var from_value = $(pksForm.form[pksForm.prefix+'[country_from]']).getValue();
		var to_value = $(pksForm.form[pksForm.prefix+'[country_to]']).getValue();
		var connection_value = $(pksForm.form[pksForm.prefix+'[connection]']).getValue();
		var reservation_value = $(pksForm.form[pksForm.prefix+'[reservation_type]']).getValue();
		var change;
		
		if(reservationType){
			change = reservationType;
		} else {
			change = el.name;
		}
		
		new Ajax.Request(pksForm.url, {
			onSuccess	: function(tr){
				var text = pksForm.getData(tr.responseText).split('***row***');
				var country_from_options = text[0],country_to_options = text[1],connection_options = text[2];
				
				if(country_from_options != 'keep'){
                                    $(pksForm.form[pksForm.prefix+'[country_from]']).update(country_from_options);
                                }
				if(country_to_options != 'keep' ){
                                    $(pksForm.form[pksForm.prefix+'[country_to]']).update(country_to_options);
                                }
                                if(connection_options != 'keep'){
                                    $(pksForm.form[pksForm.prefix+'[connection]']).update(connection_options);
                                }
				
                            $(pksForm.form[pksForm.prefix+'[country_from]']).removeAttribute('disabled');
                            $(pksForm.form[pksForm.prefix+'[country_to]']).removeAttribute('disabled');
                            $(pksForm.form[pksForm.prefix+'[connection]']).removeAttribute('disabled');

                            $$('.spinner_form').invoke('hide');
			},

                        onLoading         : function(){
                            var index = $(pksForm.form[pksForm.prefix+'[connection]']).selectedIndex;

                            $(pksForm.form[pksForm.prefix+'[country_from]']).setAttribute('disabled',true);
                            $(pksForm.form[pksForm.prefix+'[country_to]']).setAttribute('disabled',true);
                            $(pksForm.form[pksForm.prefix+'[connection]']).setAttribute('disabled',true);

                            $$('.spinner_form').invoke('show');

                            //if( el.name == 'tx_pksform_pi1[connection]' ){
                                // jeśli wybrane połączenie >> info o wybranych miastach
                                $(pksForm.form[pksForm.prefix+'[city_from]']).setAttribute('value', $(pksForm.form[pksForm.prefix+'[connection]'][index]).getAttribute('city_from'));
                                $(pksForm.form[pksForm.prefix+'[city_to]']).setAttribute('value', $(pksForm.form[pksForm.prefix+'[connection]'][index]).getAttribute('city_to'));
                            //}
                            
                        },

			parameters	: {'data':$H({'reservation_type':reservation_value,'change':change,'action':'form_change','country_from':from_value,'country_to':to_value,'connection':connection_value}).toJSON()}
		});		
	},	
	
	/**
	 * obsługa "tabów", po wyborze zakładki ustawia pole hidden w formularzu na wybrany typ 
	 */
	changeReservationType	: function(el){
		el = $(el);
		$(pksForm.form[pksForm.prefix+'[reservation_type]']).setAttribute('value', el.getAttribute('reservation_type'));
		
		pksForm.changeForm(null,$(el.parentNode).getAttribute('id'));
		
		$(el.parentNode).addClassName('active');
		$(el.parentNode).siblings().invoke('removeClassName','active');
		
		return false;
	},
	
	displayMoreAboutCity	: function(){
		/**
		 * jeśli na tej stronie jest to pole i nie jest jako ukryte
		 */
		if( pksForm.form[pksForm.prefix+'[city_from]'] && pksForm.form[pksForm.prefix+'[city_from]'].tagName!='INPUT'){
			// city from
			var el = $(pksForm.form[pksForm.prefix+'[city_from]'][ pksForm.form[pksForm.prefix+'[city_from]'].selectedIndex ]);
			if( el.getAttribute('city_url') ){
				$('city_from_more').update('<a target="_blank" title="'+el.getAttribute('city_title')+'" href="'+el.getAttribute('city_url')+'">Więcej o porcie</a>'  );
				$('city_from_more').show();
			} else {
				$('city_from_more').hide();
			}
	
			// city to
			el = $(pksForm.form[pksForm.prefix+'[city_to]'][ pksForm.form[pksForm.prefix+'[city_to]'].selectedIndex ]);
			if( el.getAttribute('city_url') ){
				$('city_to_more').update('<a target="_blank" title="'+el.getAttribute('city_title')+'" href="'+el.getAttribute('city_url')+'">Więcej o porcie</a>'  );
				$('city_to_more').show();
			} else {
				$('city_to_more').hide();
			}
		}
	},
	
	empty	: function (el){
		return el && el.getValue()!=-1 ? true : false;
	},
	
	tabs	: function(el,k){
		$$( '[tabs='+el.getAttribute('tab_set')+']').each(function(el){
			el.hide();
		});
		
		if(el.tagName=='SELECT'){
			var set = el.getAttribute('tab_set');
			if( set ){
				$$('[tabs='+set+']').invoke('hide');
				var showID = $( el[ el.selectedIndex ].getAttribute('tab') );
				if( showID ){
					showID.show();
				}
			}
		
		} else {
			var set = el.getAttribute('tab_set');
			if( el.checked && set ){
				$$('[tabs='+set+']').invoke('hide');
				var showID = $( el.getAttribute('tab') );
				if( showID ){
					showID.show();
				}
                                
			} else {
            }
		}
	},	
	
	/**
	 * przełącznik: hide/show
	 * @param {Object} el
	 */
	toggle	: function(el,k){

		if( el.checked && el.getAttribute('value')=='1' ){
			if (k) {
				/*
				new Effect.toggle(el.getAttribute('toggle'), 'appear', {
					duration: k
				});
				*/
				$(el.getAttribute('toggle')).show();
			}
			else {
				$(el.getAttribute('toggle')).show();
			}
		} else {
			if (k) {
				/*
				new Effect.toggle(el.getAttribute('toggle'), 'slide', {
					duration: k
				});
				*/
				$(el.getAttribute('toggle')).hide();
			}
			else {
				$(el.getAttribute('toggle')).hide();
			}
		}
	
	},
	
	/**
	 * wyświetla osobny sektor dla wszystkich ludzi
	 * @param {Object} el
	 */
	displayPeoples	: function(el){
		var i = $(el).getValue();
		$(el.parentNode.parentNode).select('.user').each(function(el){
			if(i-- > 0){
				el.show();
			} else {
				el.hide();
			}
		});
	},
	
	log 	: function(msg){
		n.log(msg);
	},
	
	addSelectOption	: function(selectObj, text, value, isSelected){
		if(selectObj != null && selectObj.options != null){
			selectObj.options[selectObj.options.length] = 
			new Option(text, value, false, isSelected);
		}
	},	
	
	initCalendar	: function(){
		$$('.'+pksForm.calendarFieldsClass).each(function(el){
			
			if(el){
		        Calendar.setup({
		        	dateField: el,
		            triggerElement: el
		        });					
			}
			
		});
	},
	
	getData		: function(str){
		return str.split('***json***')[1].evalJSON(true);
	},
	
	/**
	 * !trip == back
	 */
	checkTimeTable	: function(trip){
		var el_name = trip ? 'trip' : 'back';
		
		if( !pksForm.form[pksForm.prefix+'['+el_name+'_time]'] || !pksForm.form[pksForm.prefix+'['+el_name+'_time]'][0]){
			return;
		}
		
		pksForm.log('chek timeTable...');
		
		if( pksForm.form[pksForm.prefix+'[city_from]'].selectedIndex > 0 && pksForm.form[pksForm.prefix+'[city_to]'].selectedIndex > 0 && pksForm.form[pksForm.prefix+'['+el_name+'_date]'].getValue() != "" ){
			
			var selected_time_value = pksForm.form[pksForm.prefix+'['+el_name+'_time]'][ pksForm.form[pksForm.prefix+'['+el_name+'_time]'].selectedIndex ].textContent;
			var selected_time_index = pksForm.form[pksForm.prefix+'['+el_name+'_time]'].selectedIndex;				
			
			$(pksForm.form[pksForm.prefix+'['+el_name+'_time]']).length = 1;
			$(pksForm.form[pksForm.prefix+'['+el_name+'_time]'][0]).hide();
				
			
			var from_value = trip ? pksForm.form[pksForm.prefix+'[city_from]'].getValue() : pksForm.form[pksForm.prefix+'[city_to]'].getValue();
			var to_value = trip ? pksForm.form[pksForm.prefix+'[city_to]'].getValue() : pksForm.form[pksForm.prefix+'[city_from]'].getValue();
			var reservation_type = pksForm.form[pksForm.prefix+'[reservation_type]'].getValue();
			
			new Ajax.Request(pksForm.url, {
				onSuccess	: function(tr){
					var selected,value;
					
					pksForm.getData(tr.responseText).each(function(el){						
						selected = el==selected_time_value ? 1 : 0;
						value = el.length<7 ? el : '1';
						
						pksForm.addSelectOption(pksForm.form[pksForm.prefix+'['+el_name+'_time]'],el,value,selected);
					});


				
					if( pksForm.form[pksForm.prefix+'['+el_name+'_time]'].selectedIndex <= 0 ){
						var i = 0;
						$A(pksForm.form[pksForm.prefix+'['+el_name+'_time]']).each(function(el){
						
							if( parseInt(el.value) > 0 ){
								pksForm.form[pksForm.prefix+'['+el_name+'_time]'].selectedIndex = i;
								return;
							}
							i++;
						});
						
					} else {	
						//n.log('else : '+pksForm.form[pksForm.prefix+'['+el_name+'_time]'].selectedIndex);
					}
					
					$(pksForm.form[pksForm.prefix+'['+el_name+'_time]']).removeAttribute('disabled');
				},
				
				parameters	: {'data':$H({'reservation_type':reservation_type,'city_from':from_value,'city_to':to_value,'date':pksForm.form[pksForm.prefix+'['+el_name+'_date]'].getValue()}).toJSON()}
			});
		} else {
			$(pksForm.form[pksForm.prefix+'['+el_name+'_time]'][0]).show();
			$(pksForm.form[pksForm.prefix+'['+el_name+'_time]']).length = 1;
			$(pksForm.form[pksForm.prefix+'['+el_name+'_time]']).setAttribute('disabled', 'disabled');
		}
	},
	
	initTooltips	: function(){
/*		$$('.tooltip').each(function(el){
			new Tip(el.id, el.getAttribute('t_content'),{
				'title':	el.getAttribute('t_title'),
				'delay':	0.2,
				'closeButton': 0
				//'effect':	true,
				//'duration': 0.3,
			});
			pksForm.log(el.id);
		});*/
	},
	
	clickSubmit		: function(el){
		if( $('type_submit')){
			$('type_submit').value = el.getAttribute('submit');
		
		} else {
			pksForm.form.insert( '<input id="type_submit" name="'+pksForm.prefix+'[type_submit]" type="hidden" value="'+el.getAttribute('submit')+'" />');
		}
		
		pksForm.form.submit();
	},	
	
	
	init		: function(){		
		this.form = $(this.form);
		
		if(!$(pksForm.form)){
			if(pksForm.debug){pksForm.log('nie ma takiego formularza');}
			return;
		}
		
		$$('.toggle').each( function(el){
			el.observe('click',function(event){pksForm.toggle(event.element(),0.5);});
			pksForm.toggle(el);
		});
		
		//tabs
		$$('.tabs').each( function(el){
                    if(el.tagName == 'SELECT'){
                        el.observe('change',function(event){pksForm.tabs(event.element(),0.5);});
                    } else {
                        el.observe('click',function(event){pksForm.tabs(event.element(),0.5);});
                    }
			
			pksForm.tabs(el);
		});
		$$('.tabs:checked').each(function(el){
			pksForm.tabs(el);
		});		
		
		
		// init ludzie
		$$('.people_count').each(function(el){
				el.observe('change',function(event){pksForm.displayPeoples(event.element(),1);});
				pksForm.displayPeoples(el);
		});

		var checkTT = 3;
		['[city_from]','[city_to]','[trip_date]' ].each(function(el){
			if( $(pksForm.form[pksForm.prefix+el])!==undefined){
				pksForm.form[pksForm.prefix+el].observe('change',function(event){pksForm.checkTimeTable(1)});
			} else {
				checkTT--;
			}
		});			
		if(checkTT==0){
			//pksForm.checkTimeTable(1);
		}	
		
		checkTT = 3;
		['[city_from]','[city_to]','[back_date]' ].each(function(el){
			if(pksForm.form[pksForm.prefix+el]!==undefined ){
                $(pksForm.form[pksForm.prefix+el]).observe('change',function(event){pksForm.checkTimeTable()});
			} else {
				checkTT--;
			}
		});		
		
		['[city_from]','[city_to]'].each(function(el){
			if(pksForm.form[pksForm.prefix+el]!==undefined ){
				pksForm.form[pksForm.prefix+el].observe('change',function(event){pksForm.displayMoreAboutCity()});
			} else {
			}
		});		
		pksForm.displayMoreAboutCity();
		
		if(checkTT){
			//pksForm.checkTimeTable();
		}		
		
		pksForm.initTooltips();
		
		$$('.nsubmit').each( function(el){
			el.observe('click',function(event){pksForm.clickSubmit(event.element());});
		});
		
		$$('.ch_reservation_type').each( function(el){
			el.observe('click',function(event){return pksForm.changeReservationType(event.element());});
		});
		try{
		    // tylko na stronie głównej, przy inicjalnym widoko, pzefiltrować
		    pksForm.changeReservationType($('res_t_3').select('a')[0]);
		} catch(e){}
		/**
		 * zapamiętanie ostatnio wybranej zakładki
		 */
		if( $(pksForm.form[pksForm.prefix+'[reservation_type]']) ){
			
			var val = $(pksForm.form[pksForm.prefix+'[reservation_type]']).getAttribute('value');
			if($('res_t_'+val)){
				$('res_t_'+val).addClassName('active');
				$('res_t_'+val).siblings().invoke('removeClassName','active');
			}	
				
		} else {
		}
		

			checkTT = false;
			['[connection]','[country_from]','[country_to]'].each(function(el){
				if(pksForm.form[pksForm.prefix+el] !== undefined){
					$(pksForm.form[pksForm.prefix+el]).observe('change',function(event){pksForm.changeForm(event.element());});
					checkTT = true;
				} else {				
				}
			});	
		
		$$('.select_connection').each( function(el){		
		});			
		
		// init calendar
		pksForm.initCalendar();
	}
});

document.observe("dom:loaded", function(){	
	 //setupCalendars();	
	pksForm = new pksForm();
	pksForm.init();
});

