if (!window.people) people = {};

$(document).ready(function () {
	var nss = ['vars', 'framework'], l = nss.length, i,
	brandFestival;

	for (i = 0; i < l; i++) {
		if (!people[nss[i]]) people[nss[i]] = {};
	}

	people.framework.initObj = {};
	brandFestival = {
			init : function () {
				var that = this;
				this.hovers();
				this.userBox();
				this.intervalBox();
				this.boxEvents();
				if ($('body').hasClass('register')) {
					this.payCalculation();
				}				
				this.showInfo();
				this.formActions();
				this.flashContent();
				this.buyTicket();
				this.lineUp();
				this.infoShow();
				this.socialShare();
				this.actions();
				this.jcarousel();
			},			
			
			
			pageValid: function(obj, carousel) {
					var idx = $(carousel).attr('data'),
					postData = $($('.jcarousel-item')[idx-1]).find('input, textarea, select'),
					that = this,
					ret = Boolean(false),
					retData = [],
					i = l = 0,
					validTab = false,
					error = postData.length,
					form = $(carousel).parents('form:eq(0)');					
					
					form.validate({
						rules: {
						'q2':	{
							required: true
							},
						'q3':	{
							required: true
							},
						'q4':{
							required: true
							},
						'q5':{
							required: true
							},
						'q6':{
							required: true
							},
						'q7':{
							required: true
							},
						'q8':{
							required: true
							},
						'q9_1':{
							required: true
							},
						'q9_2':{
							required: true
							},
						'q9_3':{
							required: true
							},
						'q9_4':{
							required: true
							},
						'q9_5':{
							required: true
							}/*,
						'q9_6':{
							required: true
							}*/
						},
						messages: {
							'q2': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q3': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q4': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q5': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q6': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q7': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q8': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q9_1': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q9_2': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q9_3': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q9_4': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							},
							'q9_5': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							}/*,
							'q9_6': {
								required: 'Kérjük válasszon egyet a lehetséges válaszok közül!'
							}*/
						}
					});
					
					l = postData.length;
				
					for (i = 0; i < l; i++) {
						if ($(postData[i]).valid()) {
							error--;
						}
					}
					
					if (error > 0) {
						ret = false;
					} else {
						ret = true;
					}
					return ret;
			},
			
			ajaxProcessing: function(response, retData, carousel) {
				var ajaxResponder = $(carousel).parents('.jcarousel:eq(0)').find('.ajaxResponder'),
				i = 0,
				l = retData.length,
				msg = '';
				if (response.success) {
					return false;
				} else {
					for (i = 0; i < l; i++) {
						if (response.data[retData[i]] != undefined) {
							msg += response.data[retData[i]];
						}
					}
					$(ajaxResponder).html(msg)
				}
			},
			
			formSubmit : function (param) {
				var form = param.form,
				method,
				action,
				postData;
				
				if ($(form).hasClass('ajaxPost')) {
					method = $(form).attr('method') || $(form).data('method');
					action = $(form).attr('action') || $(form).data('action');
					postData = $(form).serialize();
					
					$.ajax({
						type: method,
						url: action,
						data: postData,
						dataType: "json",
						success: function(response){
							if (response.success) {
								$('.pollPhone').after('<h2 class="thx" style="position: relative; font-size: 24px; top: 200px; left: 215px; width: 480px;">Köszönjük, hogy válaszoltál kérdéseinkre</h2>');
								$('.carousel-clip-region, .pollCounter, .jcarousel-prev, .jcarousel-next').remove();									
							}							
						}
					});
				}
			},
			
			jcarousel: function (){
				if ($('.jcarousel').length > 0) {
					var prev = '<div class="jcarousel-prev jcarousel-prev-horizontal" style="display: block;"></div>',
						next = '<div class="jcarousel-next jcarousel-next-horizontal" style="display: block;"></div>',
						pos = 0,
						that = this;
					
					$('#pollItem').html($('.carousel-list>li').length);
					
					$('.pollSubmit').bind('click', function (event){
						event.preventDefault();						
						var form = $(this).parents('form');
						that.formSubmit({
							'form': form							
							});
						
					});
						
					
				carouselControl = function (obj) {
						var carousel = $(obj).parent().find('.carousel-list'),
						data = parseInt($(carousel).attr('data')),
						carouselElements = $(carousel).children('li');
						max = $(carouselElements).length,
						width = parseInt($(carousel).children('li').eq(0).css('width')),
						roll = false;
						
						roll = that.pageValid(data, carousel);
						if (roll) {
							if ($(obj).hasClass('jcarousel-prev')) {
								if (data > 1) {
									data -= 1;
									pos += width;
								} else {
									pos = 0;
									return false;
								}
							}				
							
							if ($(obj).hasClass('jcarousel-next')) {
								if (data < max) {
									data += 1;
									pos -= width;
								} else {
									return false;
								}
							}
						
							$(carousel).attr('data', data);
							$(carousel).animate({
								'left': pos
							});
							//$('.ajaxResponder div').remove();
							$('#pollCounter').html(data);
						}
					}					
					
					$('.jcarousel').each( function () {
						var carousel = $(this).find('.carousel-list'),
						width = parseInt($(carousel).children('li').eq(0).css('width')),
						carouselElements = $(carousel).children('li'),
						max = $(carouselElements).length;
						carousel.css('width', max * width);
						
						$(carouselElements).each(function() {							
							$(this).addClass('jcarousel-item');
							$(this).addClass('item_' + parseInt($(carouselElements).index(this) + 1));
						});
						
						
						if (!$('.carousel-list').attr('data')) {
							$('.carousel-list').attr('data', 1);
						}
						if ($(this).find('.jcarousel-prev-horizontal, .jcarousel-next-horizontal').length < 1) {
							$(this).append($(prev));
							$(this).append($(next));
							
							$(this).find('.jcarousel-prev-horizontal, .jcarousel-next-horizontal').bind('click', function (event) {
								event.preventDefault();
								carouselControl(this);
							});
							
						}
					});					
				}
			},						
			
			actions: function () {
				$('.print').bind('click', function (event) {
					event.preventDefault();
					window.print();
				});
				
				$('.url').bind('click', function(event) {
					event.preventDefault();
					window.open($(this).attr('href'),'','');
				});
				
				if ($('#poll').length > 0) {
					$("#poll").fancybox({
						'width'				: 852,
						'height'			: 479,
						'autoScale'     	: false,
						'transitionIn'		: 'fade',
						'transitionOut'		: 'fade',
						'type'				: 'iframe',
						'opacity'			: true,
						'overlayColor'		: '#FFF',
						'onComplete'		: function() {
							$('iframe#fancybox-frame').attr({'allowtransparency': true});
						}
					});
				}
			},

			socialShare: function () {
				$('.socialLink').click(function (event) {
						event.preventDefault();
						window.open($(this).attr("href"),'','width=800, height=460');
					});
			},
					
			infoShow: function () {
				if ($('.info').length > 0) {
					$('.info').bind('mouseover', function(event) {
						$('.info').each(function () {
							$(this).next().hide();
						});						
						if (!$(this).next().hasClass('showed')) {							
							$(this).parent().find('.desc, .close').addClass('showed');
							$(this).next().fadeToggle('slow', function () {});
						}
					}).bind('mouseout', function(event) {
						$(this).next().hide();
						if ($(this).next().hasClass('showed')) {
							$(this).parent().find('.desc, .close').removeClass('showed');
						}
					});
					$('.close').bind('click', function(event) {
						$(this).parent().find('.desc, .close').removeClass('showed');
						$(this).parent().find('.desc').fadeToggle('slow', function () {});
					});
				}
			},
			
			lineUp: function () {
				if ($('.sessionLabel .opener').length > 0) {
					$('.sessionLabel').bind('click', function () {
						if (!$(this).hasClass('noopen')) {
							if ($(this).hasClass('current')) {
								$(this).removeClass('current');
								$(this).next().fadeOut(400);
							} else {
								$(this).addClass('current');
								$(this).next().delay(400).fadeIn(200);
							}
						}
					});
					
					$('.showAll').bind('click', function () {
						$('.showAll .show').toggle();
						$('.showAll .hide').toggle();
						
						if ($('.showAll .hide').css('display') != 'none') {
							$('.sessionLabel').each(function(){
								$(this).addClass('current');
								$(this).next().fadeIn(200);
							});
						} else {
							$('.sessionLabel').each(function(){
								$(this).removeClass('current');
								$(this).next().fadeOut(50);
							});
						}
					});
				}				
			},

			buyTicket: function () {
				if ($('.buyTicket').length > 0) {
					$('.buyTicket').bind('click', function (event) {
						event.preventDefault();
						if (!$(this).parents('.ticketType').hasClass('disabled')) {
							$(this).addClass('hidden');
							$(this).parents('.ticketType').toggleClass('clicked');
							if (!$(this).parents('.leisureOne').hasClass('disabled')) {
								$('#regisztracio fieldset.hidden:eq(0), #regisztracio .addBox, .companyBox').removeClass('hidden');
							}
						}
					});
				}
			},
			
			flashContent: function () {
				if ($('.flashContent').length > 0) {
					var flID,
					flWidth = 0,
					flHeight = 0,
					flashvars = {
						xmlPath : "/xml/data.xml"
					},
					params = {
						wmode : "transparent"
					}					
					attributes = {};
					if ($('.flashContentRegistration').length > 0 ) {						
						flashvars = {
							clickTAG : "/regisztracio"
						},
						params = {
							wmode : "transparent"
						},
						attributes = {
							bgcolor: '#FFFFFF'
						};
					}
					
					$('.flashContent').each(function () {
						flID = $(this).attr('id');
						$(this).html('<div id="' + flID + '_c"></div>');
						flWidth = $(this).css('width');
						flHeight = $(this).css('height');
						swfobject.embedSWF('swf/' + flID + '.swf', flID + '_c', flWidth, flHeight, '10.0.0', 'swf/expressInstall.swf', flashvars, params, attributes);
					})
				}
			},
			
			formatNumber: function (params) {
				var prefix,
					num,
					splitStr,
					splitLeft,
					splitRight, 
					regx,
					ret;
					
					prefix = params.prefix || '';
					num = params.num + '';
					param = params.param;				
				if (param) {
					ret = param.replace(/([^0-9\.\-])/g,'') * 1;
				} else {
				   splitStr = num.split('.');
				   splitLeft = splitStr[0];
				   splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
				   regx = /(\d+)(\d{3})/;
				   while (regx. test(splitLeft)) {
					  splitLeft = splitLeft.replace(regx, '$1' + ' ' + '$2');
				   }
				   ret = splitLeft + splitRight + ' ' + prefix;
				}
				return ret;
			},
			
			formActions: function () {
//				$.validator.setDefaults({
//					highlight: function(input) {
//						$(input).parents('label').addClass("error").removeClass("valid");
//					},
//					unhighlight: function(input) {
//						if ($(input).val().length==0)
//							$(input).parents('label')
//							.addClass("required");
//						else {
//							$(input).parents('label')
//							.removeClass("error")
//							.addClass("valid");
//						}
//					}
//				});
				
//				$('.regForm').validate({
//					rules: {
//						'email':		    {
//							required: true,
//							email: true
//						}
//					},
//					messages: {
//						email : {
//							required: 'Adja meg az email címét!',
//							email: 'Kérjük valós email címet adjon meg!'
//						}
//					},
//					submitHandler: function() {
//						$('#sample_regForm form').ajaxSubmit({
//							target: "#sample_regForm form"
//						});
//					}
//				});
			},
			
			showInfo: function () {
				$('#infoUsers').text($('.userBox').length);
				$('#infoPay').text($('#fullPay span').text());
			},

			payCalculation: function () {				
				var postData,
				that = this,
				ajaxUrl;				
				
				$('#postAddress').bind('click', function () {
					if ($(this).is(':checked')) {
						$('#post_postal_code').val($('#invoice_postal_code').val());
						$('#post_city').val($('#invoice_city').val());
						$('#post_street').val($('#invoice_street').val());
					} else {
						$('#post_postal_code').val('');
						$('#post_city').val('');
						$('#post_street').val('');
					}
				})
				
				if ($('form#regisztracio').length > 0) {
					postData = $('form#regisztracio').serialize();
					ajaxUrl = 'regisztracio/ajaxresponse.php';
				} else {
					postData = $('form').serialize();
					ajaxUrl = 'ajaxresponse.php';
				}
				
				function fullPay() {					
					var ret = 0;
					$('.packagePrice').each(function () {
						ret += parseInt($(this).val(), 10);
					});
					$('#fullPay span').text(that.formatNumber({'num' : ret}));
					that.showInfo();
				}

				ajaxProcessing = function (data) {
					var i = -1;
					$('.userBox').each(function () {
						i++;
						$(this).find('.packagePrice').val(data[i]);
					});
					fullPay();
				}
				
				$.ajax({
				   type: "post",
				   url: ajaxUrl,
				   data: postData,
				   dataType: "json",
				   success: function(response){
						ajaxProcessing(response);
				   }
				 });				
			},

			boxEvents: function () {
				var that = this;
				$('.userBox').each( function () {
					$(this).find('input[type="checkbox"]').bind('click', function() {
						that.payCalculation();
					}).end()
					.find('input[type="radio"]').bind('click', function() {
						that.payCalculation();
					}).end()
				});
			},

			regUsers: function () {
				$('.userBox').each( function () {
					$('#users').html('<li><span>' + $(this).find('.username').val() + '</li>');
				})
			},

			intervalBox : function () {
				$('.interval').bind('click', function () {
						inputs = $(this).parent().next().find('input');
						$(inputs).each(function () {
								$(this).attr('disabled', false);
							});
						formSet();
					});

				formSet = function (data) {
					$('.interval').each(function () {
							if ($(this).is(':checked')) {
								inputs = $(this).parent().next().find('input');
								$(inputs).each(function () {
										$(this).attr('disabled', false);
									});
							} else {
								inputs = $(this).parent().next().find('input');
								$(inputs).each(function () {
										$(this).attr({
												'disabled' : true,
												'checked' : false
											});
									})
							}
						});
				}
			},

			hovers : function () {
				/*$('.regForm fieldset').bind('mouseover', function () {
						$(this).addClass('hovered');
					}).bind('mouseout', function () {
						$(this).removeClass('hovered');
					});*/
			},

			reOrder: function () {
				var boxIndex, check, chkLength, that = this;
				$('.userBox').each(function () {
						var th = $(this);
						boxIndex = $('.userBox').index(this) + 1;
						$(this).find('b.order').text(boxIndex).end()
						.find('input').each(function () {
								patt = /\d/g;
								str = $(this).attr('name');
								str = str.replace(patt, boxIndex);
								$(this).attr('name', str)
							}).end()
					});
				$('#total_attendees').val(boxIndex);
				this.boxEvents();
				this.payCalculation();
			},

			userBox: function () {
				var that = this;
				
				//$('.ticketInfo .disabled').css('opacity', 0.4);

				selfRemove = function () {
					$('.removeBox').bind('click', function (event) {
							event.preventDefault();
							if ($('.removeBox').length > 1) {
								$(this).parents('.userBox').remove();
								that.reOrder();
							} else {
								$(this).parents('.userBox').addClass('hidden');
								$('.companyBox').addClass('hidden');
								$(this).parents('#regisztracio').find('.addBox').addClass('hidden');
								$('.clicked').removeClass('clicked');
								$('.buyTicket').removeClass('hidden');
							}
						});
				}
				selfRemove();
				
				$('userbox .txtField').bind('click', function (){
					$(this).addClass('hovered').end()
				})

				$('.addBox').bind('click', function (event) {
					event.preventDefault();
					var indexNum = $('.userBox').length + 1,
					patt,
					str,
					chk,
					chkLength;
					
					cloned = $(this).prev().clone();
					$(cloned).removeClass('hidden');
					$('.companyBox').removeClass('hidden');
					
					$(cloned).find('input').each(function () {
							patt = /\d/g;
							$(this).removeClass('error').end()
							$(this).removeClass('func').end()
							.parents('label').removeClass('error').end()
							.closest('label').removeClass('error').end();
							str = $(this).attr('name');
							str = str.replace(patt, indexNum);
							$(this).attr('name', str).val('');
						}).end()					
					.find('b.order').each(function () {
							indexNum = parseInt($(this).text()) + 1;
							$(this).text(indexNum)
						}).end()
					.find('input.member:eq(0)').val('1').end()
					.find('input.member:eq(1)').val('2').end()
					.insertAfter($(this).prev()).end()
					.delegate('.removeBox', 'click', selfRemove).end();					
					that.reOrder();
				});
			}
		}
		brandFestival.init();
		people.framework.initObj = brandFestival;

		// function to center div
		jQuery.fn.center = function () {
			this.css("position","absolute");
			this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
			this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
			return this;
		}
		// while AJAX is loading
		$('#loadingDiv')
			.hide()  // hide it initially
			.ajaxStart(function() {
				$(this).center().show();
			})
			.ajaxStop(function() {
				$(this).hide();
			})
		;
	});
