jQuery(document).ready(function($) {
	pc_form_pag_acting 		= false; // just one form pagination per time
	pc_reg_is_acting 		= false; // know when registration form is being submitted
	pc_login_is_acting 		= false; // security var to avoid multiple calls
	pc_del_user_is_acting 	= false; // security var to avoid multiple calls
	
	pc_curr_url 				= window.location.href;
	var pre_timestamp 			= (pc_curr_url.indexOf('?') !== -1) ? '&' : '?';
	var reg_form_captcha_data 	= {}; // cache userd by form sysrtem to allow invisible recaptcha 

	
	// fields focus/blur tracking
	var focus_track_subj = '.pc_field_container input';
	$(document).on('focus', focus_track_subj, function(e) {
		$(this).parents('.pc_field_container').addClass('pc_focused_field');
		
	}).on('blur', focus_track_subj, function(e) {
		$(this).parents('.pc_field_container').removeClass('pc_focused_field');
	});
	
	
	
	/**************************
			 LOGIN
	**************************/
	
	// triggers
	$('body, form').delegate('.pc_auth_btn', 'click', function(e) {
		e.preventDefault();
			
		var $target_form = $(this).parents('form');
		var f_data = $target_form.serialize();

		pc_submit_login($target_form, f_data);
	});
	$('.pc_login_row input').keypress(function(event){
		if(event.keyCode === 13){
			var $target_form = $(this).parents('form');
			var f_data = $target_form.serialize();

			pc_submit_login($target_form, f_data);
		}
		
		event.cancelBubble = true;
		if(event.stopPropagation) event.stopPropagation();
   	});
	
	
	// handle form
	pc_submit_login = function($form, f_data) {
		if(!pc_login_is_acting) {
			
			if(!$form.find('input[name="pc_auth_username"]').val() || !$form.find('input[name="pc_auth_psw"]').val()) {
				return false;	
			}
			
			pc_login_is_acting = true;	
			var forced_redirect = $form.data('pc_redirect');

			$form.find('.pc_auth_btn').addClass('pc_loading_btn');
			$form.find('.pc_login_smalls').fadeTo(200, 0);
			$form.find('#pc_auth_message').empty();
			
			$.ajax({
				type: "POST",
				url: pc_curr_url,
				dataType: "json",
				data: "type=js_ajax_auth&" + f_data,
				success: function(pc_data){
					pc_login_is_acting = false;
					
					// a bit of delay to display the loader
					setTimeout(function() {
						$form.find('.pc_auth_btn').removeClass('pc_loading_btn');
					}, 370);
			
					if(pc_data.resp == 'success') {
						$form.find('#pc_auth_message').append('<div class="pc_success_mess"><span>'+ pc_data.mess +'<span></div>');
						
						if(typeof(forced_redirect) == 'undefined' || forced_redirect == 'refresh') {
							if(pc_data.redirect == '' || forced_redirect == 'refresh') {var red_url = pc_curr_url + pre_timestamp + new Date().getTime();}
							else {var red_url = pc_data.redirect;}
						}
						else {red_url = forced_redirect;}
						
						// redirect
						setTimeout(function() {
						  window.location.href = red_url;
						}, 1000);
					}
					else {
						$form.find('#pc_auth_message').empty().append('<div class="pc_error_mess"><span>'+ pc_data.mess +'</span></div>');	
						
						// wait button to be re-resized
						setTimeout(function() {
							$form.find('.pc_login_smalls').fadeTo(200, 1);
						}, 500);
					}
				}
			});
		}
	};
	
	
	/* manage checkbox status on "remember me" label click */
	$(document).delegate('.pc_login_remember_me small', 'click', function() {
		$(this).parents('.pc_login_remember_me').find('.pc_checkbox').trigger('click');
	});
	
	
	/* check to avoid smalls over button on small screens */
	pc_login_smalls_display_check = function() {
		$('.pc_rm_login .pcma_psw_recovery_trigger').each(function() {
            var $form = $(this).parents('.pc_login_form');
			var $smalls = $form.find('.pc_login_smalls > *');
			
			// check smalls
			var smalls_w = 0;
			$smalls.each(function() {
                smalls_w = smalls_w + $(this).outerWidth(true);
            });
			
			
			if( 
				($form.width() - smalls_w) < ($form.find('.pc_auth_btn').outerWidth(true) + 10)
			) {
				$form.addClass('pc_mobile_login');
			} else {
				$form.removeClass('pc_mobile_login');
			}
        });
	};
	pc_login_smalls_display_check();


	/* LONG LABELS CHECK */
	var pc_lf_labels_h_check = function() {
		$('.pc_login_form').not('.pc_lf_long_labels').each(function() {
			var user_h 		= $(this).find('label[for=pc_auth_username]').outerHeight();
			var user_f_h 	= $(this).find('input[name="pc_auth_username"]').outerHeight();
			
			var psw_h 	= $(this).find('label[for=pc_auth_psw]').outerHeight();
			var psw_f_h = $(this).find('input[name="pc_auth_psw"]').outerHeight();
			
			if((user_h > user_f_h || psw_h > psw_f_h) && $(window).width() >= 440) {
				$(this).addClass('pc_lf_long_labels');		
			} else {
				$(this).removeClass('pc_lf_long_labels');
			}
        });	
	};
	pc_lf_labels_h_check();
	
	
	// on resize
	$(window).resize(function() {
		if(typeof(pc_is_resizing) != 'undefined') {clearTimeout(pc_is_resizing);}
		
		pc_is_resizing = setTimeout(function() {
			pc_login_smalls_display_check();
			pc_lf_labels_h_check();
		}, 50);
	});
	
	
	
	
	/**************************
			USER DELETION
	**************************/
	
	// triggers
	$(document).delegate('.pc_del_user_btn', 'click', function(e) {
		e.preventDefault();
			
		var $target_form = $(this).parents('form');
		pc_del_user($target_form);
	});
	$('.pc_del_user_form input').keypress(function(event){
		if(event.keyCode === 13){
			var $target_form = $(this).parents('form');
			pc_del_user($target_form);
		}
		
		event.cancelBubble = true;
		if(event.stopPropagation) event.stopPropagation();
   	});
	
	
	// handle form
	var pc_del_user = function($form) {
		var val = $form.find('input[name=pc_del_user_psw]').val();	
	
		if( $.trim(val) !== '' && !pc_del_user_is_acting) {
			
			pc_del_user_is_acting = true;	
			var redirect = $form.data('pc_redirect');
			
			//$form.find('.pc_warn_box').slideUp(370);
			$form.find('.pc_del_user_btn').addClass('pc_loading_btn');
			$form.find('.pc_user_del_message').empty();
			
			$.ajax({
				type: "POST",
				url: pc_curr_url,
				dataType: "json",
				data: {
					type 		: 'pc_del_user_ajax',
					pc_ud_psw	: $form.find('input[name=pc_del_user_psw]').val()				
				},
				success: function(pc_data){
					pc_del_user_is_acting = false;
					
					// a bit of delay to display the loader
					setTimeout(function() {
						$form.find('.pc_del_user_btn').removeClass('pc_loading_btn');
					}, 370);
			
					if(pc_data.resp == 'success') {
						$form.find('.pc_user_del_message').append('<div class="pc_success_mess"><span>'+ pc_data.mess +'<span></div>');

						// redirect
						setTimeout(function() {
						  window.location.href = redirect;
						}, 1000);
					}
					else {
						$form.find('.pc_user_del_message').empty().append('<div class="pc_error_mess"><span>'+ pc_data.mess +'</span></div>');	
					}
				}
			});
		}
	};
	
	
	
	
	/**************************
			 LOGOUT
	**************************/
	
	// execute logout		 
	$(document).delegate('.pc_logout_btn', 'click', function(e) {	
		e.preventDefault();
		
		var forced_redirect = $(this).data('pc_redirect');
		$(this).addClass('pc_loading_btn');
		
		$.ajax({
			type: "POST",
			url: pc_curr_url,
			data: "type=pc_logout",
			success: function(response){
				resp = $.trim(response);
				
				if(typeof(forced_redirect) == 'undefined') {
					if(resp == '') {window.location.href = pc_curr_url + pre_timestamp + new Date().getTime();}
					else {window.location.href = resp;}
				}
				else {window.location.href = forced_redirect;}
			}
		});
	});
	
	
			
		
	/**************************
		   REGISTRATION
	**************************/	
	
	// triggers
	$('body, form').delegate('.pc_reg_btn', 'click', function(e) {	
		e.preventDefault();
		
		var $target_form = $(this).parents('form');
		var f_data = $target_form.serialize();

		pc_submit_registration($target_form, f_data);
	});
	$('.pc_registration_form input, .pc_registration_form textarea').keypress(function(event){
		if(event.keyCode === 13){ // enter key
			var $target_form = $(this).parents('form');
			
			// maintain textarea line breaks
			$target_form.find('textarea').each(function() {
				$(this).val( $(this).val().replace(/\r\n|\r|\n/gi, "<br />") );
			});
			
			var f_data = $target_form.serialize();
			
			// restore textarea values
			$target_form.find('textarea').each(function() {
				$(this).val( $(this).val().replace(/<br \/>/gi,"\n") );
			});
			
			$(this).parents('.pc_registration_form').find('.pc_reg_btn').trigger('click');
		}
		
		event.cancelBubble = true;
		if(event.stopPropagation) event.stopPropagation();
   	});
	
	
	// handle form
	pc_submit_registration = function($form, f_data, passed_captcha) {
		if(pc_reg_is_acting) {return false;}
				
		// HTML5 validate first
		if(!$form.pc_validate_form_fieldset()) {
			return false;	
		}
		
		$form.find('.pc_reg_btn').addClass('pc_loading_btn');
		
		
		var fid 	= $form.attr('id');	
		var cc 		= (typeof($form.data('pc_cc')) == 'undefined') ? '' : $form.data('pc_cc');
		var redir 	= $form.data('pc_redirect');
		var gre_id	= false; // recaptcha widget id
	
		
		// using recaptcha?
		if($form.find('.pc_grecaptcha').length) {
			
			// get widget ID
			gre_id = get_recaptcha_widget_id($form);
			
			// check if it hasn't been done yet
			if( typeof(passed_captcha) == 'undefined' ) {
				if(typeof(grecaptcha) == 'undefined') {
					alert('recaptcha script not loaded');
				}
				
				reg_form_captcha_data = {
					form : $form,
					f_data : f_data	
				};
				grecaptcha.execute(gre_id);

				$form.find('.pc_reg_btn').removeClass('pc_loading_btn');
				return false;	
			}
		}
		/////
		

		pc_reg_is_acting = true;
		$form.find('.pc_form_response').empty();
		
		var data =
			'type=pc_registration'+
			'&form_id=' + $form.attr('rel') +
			'&pc_cc=' + cc +
			'&' + $form.serialize()
		;
		$.ajax({
			type: "POST",
			url: pc_curr_url,
			data: data,
			dataType: "json",
			success: function(pc_data){
				if(pc_data.resp == 'success') {
					$form.find('.pc_form_response').append('<div class="pc_success_mess"><span>'+ pc_data.mess +'<span></div>');
					
					// redirect
					var redirect = (typeof(redir) != 'undefined') ? redir : pc_data.redirect;
					if(redirect == 'refresh') {redirect = pc_curr_url;}
					if(redirect) {
						setTimeout(function() {
						  window.location.href = redirect;
						}, 1000);	
					}
				}
				else {
					$form.find('.pc_form_response').append('<div class="pc_error_mess">'+ pc_data.mess +'</div>');
					
					// if exist recaptcha - reload
					if( $('#recaptcha_response_field').length) {
						Recaptcha.reload();	
					}
				}
				
				// a bit of delay to display the loader
				setTimeout(function() {
					$form.find('.pc_reg_btn').removeClass('pc_loading_btn');
				}, 370);
				
				pc_reg_is_acting = false;
				
				// reset recaptcha widget
				if(gre_id) {
					grecaptcha.reset(gre_id);	
				}
			}
		});
	};
	
	
	// recaptcha bridge function, waiting for response
	pc_recaptcha_cb = function() {
		pc_submit_registration( 
			reg_form_captcha_data.form,
			reg_form_captcha_data.f_data,
		  	true
		);
	};
	
	
	// given the form object - returns the recaptcha widget ID
	var get_recaptcha_widget_id = function($form) {
		var gre_id_arr = $form.find('.g-recaptcha-response').attr('id').split('-');
		return (gre_id_arr.length == 4) ? parseInt(gre_id_arr[3], 10) : 0;	
	};	

	
	///////////////////////////////////
	
	
	
	/* setup multiple select plugin */
	var pc_multiselect_setup = function() {
		if($('.pc_multiselect, .pc_singleselect').length && typeof($.fn.multipleSelect) == 'function') {
			$('.pc_multiselect select').each(function() {
				$(this).multipleSelect( {
					selectAll: false,
					filter: true,
					countSelected: pc_ms_countSelected,
					allSelected: pc_ms_allSelected,
					placeholder: $(this).data('placeh'),	
				});
			});
			
			$('.pc_singleselect select').each(function() {
				$(this).multipleSelect( {
					single: true,
					selectAll: false,
					filter: true,
					placeholder: $(this).data('placeh'),	
				});
			});
				
			
			setTimeout(function() {
				$('.ms-search input').attr('placeholder', pc_ms_search_placeh +' ..');
				$('.ms-search .ms-no-results').text(pc_ms_search_nores +' ..');	
			}, 50);
		}
	};
	pc_multiselect_setup();
	
	
	/* setup custom checkboxes */
	var pc_checkboxes_setup = function() {
		$('.pc_login_form input[type=checkbox], .pc_check_wrap input[type=checkbox], .pc_single_check input[type=checkbox], .pc_rf_disclaimer input[type=checkbox]').each(function() {
			if($(this).hasClass('pc_checkboxed')) {return true;}
			
			var $subj = $(this);
			$subj.addClass('pc_checkboxed');
			
			var checked = ($subj.is(':checked')) ? 'pc_checked' : '';
			$subj.after('<div class="pc_checkbox '+ checked +'" data-name="'+ $subj.attr('name') +'" data-val="'+ $subj.val() +'"><span>&#10003;</span></div>');
		});
		
		
		
		$(document).undelegate('div.pc_checkbox', 'click').delegate('div.pc_checkbox', 'click', function() {
			var $subj = $(this);
			var $checkbox = $subj.prev('input[type=checkbox][name="'+ $subj.data('name') +'"][value="'+ $subj.data('val') +'"]');
			
			if(!$checkbox.length) {return true;}
			
			if($subj.hasClass('pc_checked')) {
				$subj.removeClass('pc_checked');
				$checkbox.removeAttr('checked');
			}
			else {
				$subj.addClass('pc_checked');	
				$checkbox.attr('checked', 'checked');
			}
		});
	};
	pc_checkboxes_setup();
	

	
	
	/* fluid forms - columnizer */
	pc_fluid_form_columnizer = function() {
		$('.pc_fluid_form').each(function() {
			// calculate
			var form_w = $(this).width();

			var col = Math.round( form_w / 315 );
			if(col > 5) {col = 5;}
			if(col < 1) {col = 1;}

			// if is not first check - remove past column 
			if(typeof( $(this).attr('pc_col') ) != 'undefined') {
				var curr_col = $(this).attr('pc_col');
				if(col != curr_col) {
					$(this).removeClass('pc_form_'+curr_col+'col');	
				}
			}
			
			// apply
			$(this).attr('pc_col', col);
			$(this).addClass('pc_form_'+col+'col');		
        });	
	};
	pc_fluid_form_columnizer();
	
	$(window).resize(function() { 
		if(typeof(pc_ffc) != 'undefined') {clearTimeout(pc_ffc);}
		pc_ffc = setTimeout(function() {
			pc_fluid_form_columnizer();
		}, 50);
	});
	

	
	/////////////////////////////////////////////////////////////////////
	
	
	
	/**************************
		  FORM PAGINATION
	**************************/	
	
	$('body, form').delegate('.pc_pag_btn', 'click', function(e) {
		if(pc_form_pag_acting || pc_reg_is_acting) {return true;}
		
		var $form = $(this).parents('form');
		var tot_pag = $form.find('fieldset').length;
		
		var curr_pag = parseInt($form.data('form-pag'));
		var $curr_fieldset = $form.find('fieldset.pc_f_pag_'+curr_pag);
		
		// HTML5 validate first
		if(!$form.pc_validate_form_fieldset()) {
			return true;	
		}
		
		// next
		if($(e.target).hasClass('pc_pag_next')) {
			var new_pag = curr_pag + 1;
			if(new_pag > tot_pag) {return true;}
			
			var $new_fieldset = $form.find('fieldset.pc_f_pag_'+new_pag); 	
		}
		// prev
		else {
			var new_pag = curr_pag - 1;
			if(new_pag < 0) {return true;}
			
			var $new_fieldset = $form.find('fieldset.pc_f_pag_'+new_pag); 		
		}
		
		
		// apply
		pc_form_pag_acting = true;

		$form.css('height', $form.outerHeight());
		$form.data('form-pag', new_pag);
		$form.find('> *').animate({opacity : 0}, 150);
		
		setTimeout(function() {
			$new_fieldset.removeClass('pc_hidden_fieldset');

			var new_form_h = ($form.outerHeight() - $curr_fieldset.outerHeight(true)) + $new_fieldset.outerHeight(true);  
			$form.animate({height : new_form_h}, 300);
			
			$curr_fieldset.addClass('pc_hidden_fieldset');
			
			if(new_pag == tot_pag) {
				$form.find('.pc_pag_submit').show();
			} else {
				$form.find('.pc_pag_submit').hide();	
			}
			
			setTimeout(function() {	
				$form.find('fieldset, .pc_pag_submit, .pc_pag_btn, .pc_form_response').animate({opacity : 1}, 150);
				
				// next btn and submit visibility
				if(new_pag == tot_pag) {
					$form.find('.pc_pag_next').css('visibility', 'hidden');
				} else {
					$form.find('.pc_pag_next').css('visibility', 'visible');	
				}
				
				// prev btn visibility
				if(new_pag == 1) {
					$form.find('.pc_pag_prev').css('visibility', 'hidden');	
				}
				else {
					$form.find('.pc_pag_prev').css('visibility', 'visible');	
				}
				
				$form.css('height', 'auto');
				pc_form_pag_acting = false;
			}, 350);
		}, 300);
		
	});
	
	
	
	/////////////////////////////////////////////////////////////////////
	
	
	/**************************
		  FORM VALIDATION
	**************************/	
	
	
	// validate fields using HTML5 engine
	$.fn.pc_validate_fields = function() {
		if(typeof(pc_html5_validation) == 'undefined' || !pc_html5_validation) {return true;}
		
		// if browser doesn't support validation - ignore
		if(!(typeof document.createElement( 'input' ).checkValidity == 'function')) {return true;}
		
		var errorless = true;
		var multicheck_objs = {}; // store multi-checkbox wrapper's obj to be validated after
		 
		$(this).each(function() {
			
			// multicheck element
			if($(this).parents('.pc_check_wrap').length && $(this).parents('section').find('.pc_req_field').length) {
				multicheck_objs[ $(this).attr('name') ] = $(this).parents('section.pc_rf_field');
				return true;	
			}
			
			// avoid select search field
			if($(this).is('input') && typeof($(this).attr('name')) == 'undefined') {
				return true;	
			}
			
			// remove old errors
			$(this).parents('section.pc_rf_field, section.pc_rf_disclaimer').find('.pc_field_error').remove();
			
			// validate
            if( !$(this)[0].checkValidity() ) {

				errorless = false;
				var mess = $(this)[0].validationMessage; 
				
				// remove ugly point at the end
				if( mess.substr(mess.length - 1) == '.') {
					mess = mess.substr(0, (mess.length - 1));
				}
				
				$(this).parents('section.pc_rf_field, section.pc_rf_disclaimer').prepend('<div class="pc_field_error">'+ mess +'</div>');	
			}
        });
		

		// validate multichecks
		$.each(multicheck_objs, function(i, $wrap) {
			var show_mess = true;
			$wrap.find('.pc_field_error').remove();
			
			$wrap.find('input[type=checkbox]').each(function() {
				if($(this).is(':checked')) {
					show_mess = false;
					return false;	
				}
			});
			
			if(show_mess) {
				// generate message to append
				var mess = $('<input type="checkbox" name="" required="required" />')[0].validationMessage;
				
				// remove ugly point at the end
				if( mess.substr(mess.length - 1) == '.') {
					mess = mess.substr(0, (mess.length - 1));
				}
				
				$wrap.prepend('<div class="pc_field_error">'+ mess +'</div>');
			}
		});

		
		return errorless;
	};
	
	// shortcut to validate active fieldset fields
	$.fn.pc_validate_form_fieldset = function() {
		return $(this).find('fieldset').not('.pc_hidden_fieldset').find('input, select, textarea').pc_validate_fields();
	};
	
	
	// re-validate on field change
	$('body, form').delegate('.pc_rf_field input, .pc_rf_field select, .pc_rf_field textarea, .pc_rf_disclaimer input', 'change', function() {
		
		if($(this).pc_validate_fields()) {
			$(this).parents('.pc_rf_field').find('.pc_field_error').pc_close_tooltip();	
		}
	})
	
	
	// close field error tooltip
	$.fn.pc_close_tooltip = function() {
		var $subj = $(this);
		$subj.addClass('pc_fe_closing');
		
		setTimeout(function() {
			$subj.remove();
		}, 310);
	};
	
	// close form tooltips on single tooltip click
	$('body, form').delegate('.pc_field_error', 'click', function() {
		$(this).parents('form').find('.pc_field_error').each(function() {
			$(this).pc_close_tooltip();
		});
	});
	
	
	/////////////////////////////////////////////////////////////////////
	

	/**************************
			LIGHTBOX
	**************************/	
		
	if(typeof(pc_lb_classes) != 'undefined' && typeof($.magnificPopup) != 'undefined') {
		
		// persistent check to preload contents
		var pc_lb_load_intval = setInterval(function() {
			var to_load = [];
			
			$.each(pc_lb_classes, function(i, v) {
				var id = v.replace('.pc_lb_trig_', '');
				if($.inArray(id, pc_ready_lb) !== -1) {return true;}
				
				// ajax call to get
				if($(v).length) {
					to_load.push(id);
					pc_ready_lb.push(id);
				}
			});
			
			if(to_load.length) {
				pc_is_loading_lb = true;

				// just one ajax call to get codes
				var data = {
					type 	: 'pc_lightbox_load',
					ids		: to_load
				};
				$.ajax({
					type: "POST",
					url: pc_curr_url,
					data: data,
					success: function(data){
						$('#pc_lb_codes').append(data);
					}
				});
			}
			
			// if loaded every lightbox - end interval 
			if(pc_lb_classes.length == pc_ready_lb.length) {
				clearInterval(pc_lb_load_intval);	
			}
		}, 200);
		
		
		
		// track lightbox triggers click
		$.each(pc_lb_classes, function(i,v) {
			var lb_id = v.replace('.pc_lb_trig_', '');
			
			$(document).delegate(v, 'click', function(e) {
				if(!$('.pc_lb_'+lb_id).length) {return true;}
				e.preventDefault();
				
				$.magnificPopup.open({
					items : {
						src: '.pc_lb_'+lb_id,
						type: 'inline'
					},
					mainClass			: 'pc_lightbox',
					closeOnContentClick	: false,
					closeOnBgClick		: false, 
					preloader			: false,
					modal				: ($(this).hasClass('pc_modal_lb')) ? true : false,
					focus				: 'input',
					removalDelay		: 300,
					callbacks: {
						open: function() {
							pc_multiselect_setup();
							pc_checkboxes_setup();
							pc_fluid_form_columnizer();
							
							// if last element is a form - remove bottom margin
							if($('.pc_lightbox_contents > *').eq(-2).hasClass('pc_aligned_form')) {
								$('.pc_lightbox_contents > *').eq(-2).find('form').css('margin-bottom', 0);
							}
							
							// allow other plugins to hook here
							$(document).trigger('pc_opening_lightbox');
						}
					}
				});
				
				return false;
			});
		});	
	}
	
	

});
