function debug(obj) {
	if (window.console && console.log) {
		console.log(obj);
	}
}

/* --- form validation functions --- */

	/* --- check if haystack contains needle --- */
	function inArray(needle,haystack) {
		var valid = false;
		$.each(haystack, function(i) {
			if( haystack[i] == needle )
				valid = true;
		});
		return valid;
	}
	
	/* --- return filtered array with unique values only --- */
	function returnUniqueArray(arr, position) {
		var arr_length = arr.length;
		if( typeof(arr) == 'object' && arr_length ) {
			if( position < arr_length ) {
				var elem = arr[position];
				for(i=parseInt(position)+1; i<arr_length; i++) {
					if( elem == arr[i] ) {
						arr.splice(i,1)
						arr_length--;
						i--;
					}
				}
				arr = returnUniqueArray(arr, (position+1));
			}
			return arr;
		} else {
			return false;
		}
	}
	
	/* --- check input value against array with possible/correct values and return true or false --- */
	function returnValidValue(obj) {		
		if( obj['input'].get(0).nodeName.toLowerCase() == 'input' && obj['input'].attr('type') == 'radio' ) {
			if( !inArray( $( obj['name'] + ':checked' ).val(), obj['values'] ) ) {
				return obj['name'];
			}
		} else {
			if( !inArray( obj['input'].val(), obj['values'] )	)
				return obj['name'];
		}	
		
		return false;
	}
	
	/* --- check valid e-mailaddress */
	function validEmail(val) {
		var re_email = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		return re_email.test(val)
	}
	
	/* --- return title of given obj name --- */
	function getTitle(name) {
	
		var elem = $(name);
		// get text of <dt> for radiobuttons and checkboxes
		if( elem.get(0).nodeName.toLowerCase() == 'input' && ( elem.attr('type') == 'radio' || elem.attr('type') == 'checkbox' ) )
			return elem.parents('dd').prev().text().replace('*','');
		// else just get the label
		else
			return $('label[for=' + elem.attr('id') + ']').text();
	
	}
	
	/* --- form validation --- */
	function validFormPost(obj) {
		//alert(obj.attr('id'));
		switch (obj.attr('id')) {
		case 'login':
			
			var invalid_fields = new Array;
			var not_empty = new Array('input#login_password'),
				valid_email = new Array('input#login_email');
			
			// check if not empty
			$.each(not_empty, function(i) {
				if( obj.find(not_empty[i]).val() == '' )
					invalid_fields.unshift(not_empty[i]);
			});
			
			// check ik valid e-mail
			$.each(valid_email, function(i) {
				if( !validEmail( obj.find(valid_email[i]).val() ) )
					invalid_fields.unshift(valid_email[i]);
			});
			
			break;
		case 'subscribe':
		
			var invalid_fields = new Array;
			var not_empty = new Array('input#subscribe_password','input#subscribe_password_repeat','input#subscribe_firstname','input#subscribe_lastname','input#subscribe_bank','input#subscribe_street','input#subscribe_zipcode','input#subscribe_city'),
				valid_email = new Array('input#subscribe_email','input#subscribe_email_repeat');
			
			// check if not empty
			$.each(not_empty, function(i) {
				if( obj.find(not_empty[i]).val() == '' )
					invalid_fields.unshift(not_empty[i]);
			});
			
			// check ik valid e-mail
			$.each(valid_email, function(i) {
				if( !validEmail( obj.find(valid_email[i]).val() ) )
					invalid_fields.unshift(valid_email[i]);
			});
			
			if( !$('#subscribe_conditions:checked').length ) {
				invalid_fields.unshift('input#subscribe_conditions');
			}
			if( !$('#subscribe_above18:checked').length && !$('#subscribe_approval:checked').length )  {
				invalid_fields.unshift('input#subscribe_above18');
				invalid_fields.unshift('input#subscribe_approval');
			}
			
			break;
		case 'special':
		
			var invalid_fields = new Array;
			var not_empty = new Array('input#special_firstname','input#special_lastname','input#special_bank'),
				valid_email = new Array('input#special_email');
			
			// check if not empty
			$.each(not_empty, function(i) {
				if( obj.find(not_empty[i]).val() == '' )
					invalid_fields.unshift(not_empty[i]);
			});
			
			// check ik valid e-mail
			$.each(valid_email, function(i) {
				if( !validEmail( obj.find(valid_email[i]).val() ) )
					invalid_fields.unshift(valid_email[i]);
			});
			
			if( !$('#special_conditions:checked').length ) {
				invalid_fields.unshift('input#special_conditions');
			}
			if( !$('#above18:checked').length && !$('#approval:checked').length )  {
				invalid_fields.unshift('input#above18');
				invalid_fields.unshift('input#approval');
			}
			
			break;
		}
		
		return returnUniqueArray(invalid_fields,0);
	}
	
	/* --- mark invalid fields in form --- */
	function markInvalidFields(signup,invalid_fields) {
		var invalid_name = 'finput_invalid';
	
		// remove all highlighted inputs
		signup.find('.'+invalid_name).removeClass(invalid_name);	
		// remove errormessage
		signup.find('.errormsg').remove();
		
		$.each(invalid_fields, function(i) {
			var current = signup.find(invalid_fields[i]);
			
			if( current.get(0).nodeName.toLowerCase() == 'input' && ( current.attr('type') == 'radio' || current.attr('type') == 'checkbox' ) ) {
				$.each(current,function(i) {
					signup.find('label[for=' + current.eq(i).attr('id') + ']').addClass(invalid_name);
				});
			} else {
				current.addClass(invalid_name);		
				signup.find('label[for=' + current.attr('id') + ']').addClass(invalid_name);
			}
		});
	
	}
	
	// validate discount code
	function checkDiscountcode(action, discountcode, wininput) {

		if (action === 1) {
			$.ajax({
				url: '/inc/cfc/discountcode.cfc',
				dataType: 'json',
				data: {
					method: 'checkDiscountcode',
					returnformat: 'json',
					discountcode: discountcode
				},
				success: function(data) {
					var win_input = $('#' + wininput);
					win_input.val(data.price);
					countDiscount();

					if(parseInt(data.price, 10) === 0) {
						if (win_input.parents('tr').find('td:first-child input').val().length > 0) {
							win_input.parents('tr').find('td:last-child').html('<div class="error">' + data.text + '</div>');
						}
					} else {
						aantal = parseInt($('input:hidden[name=valids]').val()) + 1;
						$('input:hidden[name=valids]').val(aantal);
					}
					toggleInstructions();
					
				}
			});	
			return false;
		} else if (action === 2) {

			/* store all codes */
			var codes = [];
			var ok = true;
			
			wininput.parents('table#special_discount').find('tr.enabled .special_code').each(function () {
				if ($.inArray($(this).val(), codes) === -1) {
					codes.push($(this).val());
				} else {
					$(this).next().text('Code komt al voor op deze online spaarkaart').show();
					ok = false;
				}
			})
			
			if (ok) {
				$.ajax({
					url: '/inc/cfc/discountcode_summer.cfc',
					dataType: 'json',
					data: {
						method: 'checkdiscountcode',
						returnformat: 'json',
						discountcode: discountcode
					},
					success: function(data) {
						wininput.text(data.text);
					}
				});	
			}

			return false;
		}
	}
		
	// count discounts
	function countDiscount() {
		
		var sum = 0,
			codes = $("input[name^=special_win]");

		codes.each( function(i) {
			if( codes.eq(i).val() !== '' ) {
				sum += parseFloat(codes.eq(i).val().replace(',','.'));
			}
		});
		$('#special_summary').val(parseFloat(sum).toFixed(2).replace('.',','));
	}

	// check if empty 'actiecode' inputs are available
	function hasEmptyInput() {
		return $("input.special_code:text[value='']").length;
	}
	
	// return number of 'actiecode' inputs
	function returnSpecialCodeCount() {
		return parseInt($('form#special input:hidden[name=valids]').val());
	}
	
	// show/remove instructions based on number of 'actiecode' inputs
	function toggleInstructions() {		
		var count = returnSpecialCodeCount();
		if (count >= 3) {
			if(!$('#msgGt3').length) {
				$('.footnote').after('<div class="instructions" id="msgGt3">Let op: bij drie actiecodes of meer geldt dat u na het verzenden het ingevulde actieformulier per mail ontvangt. Print dit formulier uit en stuur het samen met het aankoopbewijs (graag vast nieten of plakken) op naar: <br/><br/> Deoleen <br/> Antwoordnummer 1300 <br/> 1800 VC Alkmaar (postzegel niet nodig)</div>');
			}
		} else {
			$('#msgGt3').remove();
		}
		if (count >= 10) {
			if(!$('#msgGte10').length) {
				$('#special_discount').after('<div class="instructions" id="msgGte10">Je kunt maximaal 10 codes per keer invoeren.</div>');
			}
		} else {
			$('#msgGte10').remove();
		}
	}
	
	// clone 'actiecode' input
	function cloneInput(special_tbody) {
		if (returnSpecialCodeCount() < 10) {
			special_tbody.find('tr:eq(0)').clone().appendTo(special_tbody);
			
			// make sure to have a unique id and name on both inputs
			var last_row = special_tbody.find('tr:last');
			var row_count = special_tbody.find('tr').length;
			var code = last_row.find('input:first');
			var win = last_row.find('input:last');
				
			last_row.find('td:last-child').html('');
				
			code.attr('id', code.attr('id') + '_' + row_count).attr('name', code.attr('name'));
			code.bind('change',function(){
				checkDiscountcode(1, $(this).val(),'special_win_' + row_count);
			});
			win.attr('id', win.attr('id') + '_' + row_count).attr('name', win.attr('name') + '_' + row_count);
			code.attr('value', "");
			win.attr('value', "");
			
			$('#special_code').css('outline',0);
			
			pushFooter();
		}
	}

	function checkActionCode(homepageActionInput) {
		if (homepageActionInput.length && homepageActionInput.val().length === 9) {
			$.get('/inc/cfc/discountcode_summer.cfc?method=getDiscountCodeType&discountcode=' + homepageActionInput.val(), function(data) {
				switch (parseInt(data, 10)) {
					case 1:
						alert('Je hebt helaas een code ingevoerd die niet meer geldig is. Deze actie liep tot 31-12-2011');
						break;
					case 2:
						window.location = '/actie2/q/code/' + homepageActionInput.val();
						break;
					case -1:
						alert('De code "' + homepageActionInput.val() + '" is onjuist.');
						break;
				}
			});
		}
	}


// fix height to push footer on ...
function pushFooter() {
	// homepage
	if( $('body').hasClass('home') ) {
		$('#container').height( 
			20 +
			$('#footer').height() + 
			parseInt($('#footer').css('padding-top')) + 
			parseInt($('#footer').css('padding-bottom')) + 
			$('#jezelf').height() + 
			parseInt($('#jezelf').css('top'))
		);
		
	// ohter pages
	} else if( $('body').hasClass('other') ) {
		var defaultOffset = ($('#content.small').length) ? 80 : 20;
		
		$('#container').height(
			defaultOffset +
			$('#content').outerHeight(true) +
			parseInt($('#content').css('top'))
		);
		
	}
}

$(document).ready(function() {

	pushFooter();

	/* --- special --- */
	var special = $('form#special');
	
	if (special.length) {
				
		var special_table = special.find('table');
		
		/* --- append table footer --- */
		special_table.append('<tfoot><tr valign="top"><td class="summary" scope="row">Totale korting:</td><td class="w30">&nbsp;</td><td><input type="text" name="special_summary" id="special_summary" class="finput special_win" disabled="disabled" /></td><td class="nobg"><div id="special_discount_add"></div></td></tr></tfoot>');
		
		/* --- add new item on '+' click --- */
		var special_discount = $('div#special_discount');
		var special_tbody = special_discount.find('tbody');

		if (!hasEmptyInput()) {
			cloneInput(special_tbody);
			countDiscount();
		}
		toggleInstructions();
		
		// clone row on click
		$('input.special_code')
			.live('keyup', function() {
					if ($(this).val() === '' && $(this).attr('id') !== 'special_code' && hasEmptyInput() > 1) {
						$(this).parents('tr').remove();
						toggleInstructions();
						countDiscount();
					} else if( !hasEmptyInput() ) {
						cloneInput(special_tbody);
						toggleInstructions();
					}
				}
			)
			.each(function () {
				if ($(this).val() != '') {
					checkDiscountcode(1, $(this).val(), 'special_win');
				}
			})
			.bind('change',function(){
				checkDiscountcode(1, $(this).val(),'special_win');
			});
		// validate #special form
		special.submit( function() {
			var invalid_fields = validFormPost(special);
			if (invalid_fields.length) {
				markInvalidFields(special, invalid_fields);
				return false;
			} 
		});
	}	
	
	/* --- login --- */
	var login = $('form#login');
	if (login.length) {
				
		login.submit(function() {
			var invalid_fields = validFormPost(login);
			if (invalid_fields.length) {
				markInvalidFields(login, invalid_fields);
				return false;
			} 
		});
	}
	
	/* --- subscribe --- */
	var subscribe = $('form#subscribe');
	if (subscribe.length) {

		subscribe.submit(function() {
			var invalid_fields = validFormPost(subscribe);
			if (invalid_fields.length) {
				markInvalidFields(subscribe, invalid_fields);
				return false;
			} 
		});
		
	}
	
	/* --- special discount --- */
	var specialDiscount = $('table#special_discount');
	var showNext = true;
	if (specialDiscount.length) {
		
		specialDiscount.find('input.special_code').each(function() {
			
			$(this).after('<span class="wininput" />');
			
			if (showNext && $(this).val().length === 9) {
				$(this).parents('tr').next().addClass('enabled');
			} else {
				showNext = false;
			}

			if ($(this).val() != '') {
				checkDiscountcode(2, $(this).val(), $(this).parents('td').find('span.wininput'));
			}
			$(this).bind('bind keyup', function() {
				/* show next row with input if current code contains 8 characters */
				if ($(this).val().length === 9) {
					$(this).parents('tr').next().addClass('enabled').find('input').focus();
					
					checkDiscountcode(2, $(this).val(), $(this).parents('td').find('span.wininput'));
					
				}
			});
		});
		
	}
	
	/* --- facebook like button --- */
	var facebookButton = $('img.fb_like_btn');
	var facebookLink = facebookButton.parent();
	if (facebookButton.length) {
		facebookLink.click(function() {
			window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(document.URL) + '&t=' + encodeURIComponent($('meta[property=og:title]').attr('content')), 'facebook', 'width=550,height=450');
		});
	}
	
	/* --- actie code homepage --- */
	var homepageAction = $('#actioncode');
	var homepageActionInput = homepageAction.find('input#actioncodeInput');
	if (homepageAction) {
		checkActionCode(homepageActionInput);
		$('form', homepageAction).bind('submit', function (e) {
			checkActionCode(homepageActionInput);
			e.preventDefault();
		});
	}
	
});
