﻿var debug = false;

if (console == undefined) {
	var $console = undefined;
	var console = {
		log: function(message) {
			if ($console != undefined) {
				$console.append(message + '<br/>');
				//$console.css('display', 'block');
			}
		}
	};
	if (debug) {
		//$console = $('body').append('<div id="debugframe" style="display: none; position: fixed; height: 8em; overflow: scroll; font-size: 10px; font-family: arial; bottom: 0; left: 0; width: 100%; border-top: 1px solid #000; background-color: #fff; color: #000;"></div>').find('#debugframe');
	}
}

(function($) {

	var pupForm = function(id, options) {
		return new pupForm.fn.init(id, options);
	};

	pupForm.fn = pupForm.prototype = {

		step1firstrun: true,
		step2firstrun: true,
		step3wfirstrun: true,
		step3pfirstrun: true,

		options: {
			validation_group1: '',
			validation_group2: '',
			astrupsDocumentRoot: ''
		},

		init: function(id, options) {
			var base = this;
			base.$el = $(id);
			base.options = $.extend({}, base.options, options);

			base.initForm();
		},

		initForm: function() {
			var base = this;

			// step 1
			base.$selectbox = $('.step1 .fields .selectbox-wrapper', base.$el);
			base.buildSelectBox();

			// validate step 1
			base.checkStep1(null, {});


			// step 2: validate step 1, if user clicks step 2
			var a = $('.step2 input:text', base.$el).focus(function() {
				Page_ClientValidate(base.options.validation_group1);
			});


			// step 2: remove label on focus
			$('.step2 input', base.$el).each(function() {
				var input = $(this);
				if (input.val() == undefined || input.val().trim() == '') {
					input.parent().find('label').css('visibility', 'visible');
				}
			}).focus(function(ev) {
				$(this).parent().find('label').css('visibility', 'hidden');
			}).blur(function(ev) {
				var input = $(this);
				if (input.val() == undefined || input.val().trim() == '') {
					input.parent().find('label').css('visibility', 'visible');
				}
				base.checkStep2TextBoxes();
			}).keyup(function() {
				base.checkStep2TextBoxes();
			});

			// fixes focus bug in IE
			$('.step2 label', base.$el).click(function() {
				$(this).parent().find('input').focus();
			});


		},

		buildSelectBox: function() {
			var base = this;

			var $textfield = base.$selectbox.find('.selectbox-textfield');
			var $dropdown = base.$selectbox.find('.selectbox-dropdown-wrapper');
			var selectboxHoverTimeout;

			// INIT

			// find already checked items (from viewstate)
			var othertext = $('.step1 .fields input.other-company', base.$el);
			if (othertext.val() != '') {
				var $cb = othertext.parent().find('input[type=checkbox]');
				$cb.attr('checked', 'checked');
			}

			var $selectedItems = $dropdown.find('input:checked');
			if ($selectedItems.length > 0) {

				base.step1firstrun = false;
				// enable step 2
				base.enableStep2();
			}
			$selectedItems.each(function() {
				$(this).parent().addClass('selected');
			});
			base.rebuildSelectedItems($selectedItems);
			base.checkStep2TextBoxes(true);

			// EVENTS

			// click on dropdown-button/textfield
			$textfield.click(function() {
				$(this).toggleClass('active');
				$dropdown.toggleClass('hidden');
			});
			// hover on selectbox keeps the dropdown visible, on hoverOut hide the dropdown
			base.$selectbox.hover(function() {
				if (selectboxHoverTimeout != undefined) {
					clearTimeout(selectboxHoverTimeout);
					selectboxHoverTimeout = undefined;
				}
			}, function() {
				selectboxHoverTimeout = setTimeout(function() {
					$dropdown.addClass('hidden');
				}, 1000);
			});

			// click on dropdown item label
			$dropdown.find('input:checkbox').click(function() {
				$(this).parent().toggleClass('selected');
				// verify text in the textbox before selecting
				if ($(this).parent().hasClass('other-company') && $(this).parent().hasClass('selected')) {
					var txtbox = $(this).parent().find('input.other-company');
					if (txtbox.val() == undefined || txtbox.val().trim() == '') {
						$(this).removeAttr('checked');
						$(this).parent().removeClass('selected');
					}
				}
				// clicktracking step 1, action 8
				base.clickStep1();

				// below: for IE 8
				var checkbox = $(this).parent().find('input:checkbox').get(0);
				setTimeout(function() {
					checkbox.blur();
					checkbox.focus();
				}, 1);
			});

			// changing the text of the other company
			var otherCompanyTextFieldFirstRun = true;
			$dropdown.find('input.other-company').keyup(function() {
				var $item = $(this);
				if ($item.val().trim() == '') {
					$item.parent().find('input:checked').removeAttr('checked');
					$item.parent().removeClass('selected');
				} else {
					// clicktracking step 1, action 8
					base.clickStep1();
					$item.parent().find('input:checkbox').attr('checked', 'checked');
					$item.parent().addClass('selected');
				}
				var $selectedItems = $dropdown.find('input:checked');
				base.rebuildSelectedItems($selectedItems);
				if (otherCompanyTextFieldFirstRun) {
					otherCompanyTextFieldFirstRun = false;
				} else {
					Page_ClientValidate(base.options.validation_group1);
				}
			});

			// change on dropdown list item checkbox
			$dropdown.find('input:checkbox').change(function() {
				var $selectedItems = $dropdown.find('input:checked');
				base.rebuildSelectedItems($selectedItems);
				Page_ClientValidate(base.options.validation_group1);
			});

			// close the dropdown with a link
			$dropdown.find('.close-link a').click(function() {
				$dropdown.addClass('hidden');
			});
		},

		rebuildSelectedItems: function($items) {
			var base = this;

			var $textfield = base.$selectbox.find('.selectbox-textfield');
			var $dropdown = base.$selectbox.find('.selectbox-dropdown-wrapper');
			var $selectedItemsWrapper = base.$selectbox.find('.selectbox-selecteditems-wrapper');
			var textOne = "Velg selskap";
			var textMany = "Velg flere selskap";

			if ($items != undefined && $items.length > 0) {
				$selectedItemsWrapper.html('');
				$items.each(function(index, obj) {
					var $label = $(this).parent().find('label');
					var $item = $label.clone();

					if ($label.parent().hasClass('other-company')) {
						$item.text($label.text() + ' ' + $label.parent().find('input.other-company').val());
					}

					$item.appendTo($selectedItemsWrapper);
				});
				$textfield.find('span').text(textMany);
			} else {
				$selectedItemsWrapper.html('');
				$textfield.find('span').text(textOne);
			}
		},


		enableStep2: function() {
			var $textboxes = $('.step2 input:text', this.$el);
			$textboxes.removeAttr('disabled');
		},


		checkStep2TextBoxes: function(isinit) {
			var base = this;
			var $boxes = $('.step2 input.required', base.$el);
			var valid = true;
			$boxes.each(function() {
				if ($(this).val().trim() == '') {
					valid = false;
				}
			});

			if (valid) {
				if (isinit == undefined) isinit = false;
				if (!isinit) {
					base.clickStep2();
				} else {
					base.step2firstrun = false;
				}
				$('.step3w', base.$el).removeClass('inactive');
				$('.step3p', base.$el).removeClass('inactive');
			} else {
				$('.step3w', base.$el).addClass('inactive');
				$('.step3p', base.$el).addClass('inactive');
			}
		},

		// Get the selected companies
		getSelectedCompanies: function() {
			var base = this;
			var $checkboxes = $('.step1 .selectbox-dropdown input:checked', base.$el);
			var companies = new Array();
			$checkboxes.each(function(index) {
				if ($(this).parent().hasClass('other-company')) {
					companies[index] = $(this).parent().find('input:text').val();
				} else {
					companies[index] = $(this).parent().find('label').text();
				}
			});
			return companies.join(',');
		},


		/**
		* Custom validators
		*/
		// custom validation step 1
		checkStep1: function(sender, args) {
			var base = this;
			var valid = false;

			var $checked = $('.step1 .fields input:checked', base.$el);
			valid = ($checked.length > 0);

			// sanity check for empty other company
			$checked.each(function() {
				var othertext = $(this).parent().find('input.other-company');
				if (othertext.length == 1) {
					var val = othertext.val();
					if (val == undefined || val.trim() == '') {
						valid = false;
					}
				}
			});

			if (valid == false) {
				args.IsValid = false;
				$('.step2', base.$el).addClass('inactive');
			} else {
				args.IsValid = true;
				$('.step2', base.$el).removeClass('inactive');
			}
		},


		checkStep2: function(sender, args) {
			var base = this;
			if (Page_ClientValidate(base.options.validation_group1) &&
				Page_ClientValidate(base.options.validation_group2)) {
				args.IsValid = true;
			} else {
				args.IsValid = false;
			}
		},



		/**
		* Click tracking
		*/
		clickStep1: function() {
			var base = this;
			if (base.step1firstrun) {
				base.step1firstrun = false;
				clicktracking('Trinn 1 - Velg selskap', '08', '', '', base.options.astrupsDocumentRoot);
				if (debug) console.log('Trinn 1 - Velg selskap');
				base.enableStep2();
			}
		},

		clickStep2: function() {
			var base = this;
			if (base.step2firstrun) {
				base.step2firstrun = false;
				clicktracking('Trinn 2 - Kontaktinformasjon', '', '', '', base.options.astrupsDocumentRoot);
				if (debug) console.log('Trinn 2 - Kontaktinformasjon');
			}
		},

		clickStep3w: function() {
			var base = this;
			if (Page_ClientValidate(base.options.validation_group1) &&
				Page_ClientValidate(base.options.validation_group2)) {
				if (base.step3wfirstrun) {
					base.step3wfirstrun = false;
					// page is valid
					var companies = base.getSelectedCompanies();
					// clicktracking step 3
					clicktracking('Trinn 3A - Signer på nett', '', '10', companies, base.options.astrupsDocumentRoot);
					if (debug) {
						console.log('Trinn 3A - Signer på nett');
						console.log('Firmaer: ' + companies);
					}
				}
				document.forms[0].target = '_blank';
			}
		},

		clickStep3p: function() {
			var base = this;
			if (Page_ClientValidate(base.options.validation_group1) &&
				Page_ClientValidate(base.options.validation_group2)) {
				// page is valid
				if (base.step3pfirstrun) {
					base.step3pfirstrun = false;
					var companies = base.getSelectedCompanies();
					// clicktracking step 3
					clicktracking('Trinn 3B - Signer på papir', '', '10', companies, base.options.astrupsDocumentRoot);
					if (debug) {
						console.log('Trinn 3B - Signer på papir');
						console.log('Firmaer: ' + companies);
					}
				}
				document.forms[0].target = '_blank';
			}
		}

	};
	pupForm.fn.init.prototype = pupForm.fn;
	window.pupForm = pupForm;





	// on DOM ready
	$(function() {

		var triggerEmployer = $('.pup-byemployer-wrapper .pup-switch');
		var triggerMe = $('.pup-byme-wrapper .pup-switch');

		var pupEmployer = pupForm('.pup-byemployer', {
			validation_group1: 'vgStep1',
			validation_group2: 'vgStep2',
			astrupsDocumentRoot: 'Flyttemelding'
		});

		var pupMe = pupForm('.pup-byme', {
			validation_group1: 'vg2Step1',
			validation_group2: 'vg2Step2',
			astrupsDocumentRoot: 'Flyttemelding egen sparing'
		});
		window.pupEmployer = pupEmployer;
		window.pupMe = pupMe;


		// init triggers that switch between the forms
		var f_duration = 350;
		var f_delay = 50;
		var f_easing = '';

		triggerEmployer.click(function() {
			setTimeout(function() {
				// disable the effect for IE 7
				if ($.browser.msie && $.browser.version <= 7) {
					pupMe.$el.parent().parent().hide();
					pupEmployer.$el.parent().parent().show();

				} else {
					pupEmployer.$el.parent().parent().slideToggle(f_duration, f_easing);
					pupMe.$el.parent().parent().slideToggle(f_duration, f_easing);
				}
			}, f_delay);
		});

		triggerMe.click(function() {

			setTimeout(function() {
				// disable the effect for IE 7
				if ($.browser.msie && $.browser.version <= 7) {
					pupEmployer.$el.parent().parent().hide();
					pupMe.$el.parent().parent().show();
				} else {
					pupMe.$el.parent().parent().slideToggle(f_duration, f_easing);
					pupEmployer.$el.parent().parent().slideToggle(f_duration, f_easing);
				}

			}, f_delay);
		});


		// step1 links for more text
		var $infolinks = $('.pup-byme .step1 .text2 ul li a');
		var $infotexts = $('.pup-byme .step1 .text2 ul li p');
		$infolinks.each(function() {
			var $a = $(this);
			var $p = $(this).parent().find('p');

			$a.click(function() {
				$infotexts.hide();
				$infolinks.removeClass('active');
				$p.show();
				$a.addClass('active');
			});

		});



	});




})(jQuery);





