jQuery(document).ready(function($) {
	$('#FormEventDate').datepicker({dateFormat:'dd/mm/yy'});
	$('a#addAnotherTable').click(function() {
		$(this).parent().before($('.quotationTableRow:first').clone().fadeIn(function() {
			$('.quotationTableRow:last input').val('');
			$('.quotationTableRow:last img.formOptionRowClose').click(removeTableRow);
		}));
		return false;
	});
	$('a#addAnotherChair').click(function() {
		$(this).parent().before($('.quotationChairRow:first').clone().fadeIn(function() {
			$('.quotationChairRow:last input').val('');
			$('.quotationChairRow:last img.formOptionRowClose').click(removeTableRow);
		}));
		return false;
	});
	$('#FormLightingRequired').change(function() {
		if($(this).val() == 'Yes') {
			$('#FormLightingOptionsChandeliers').attr('disabled', '');
			$('#FormLightingOptionsLEDUpLights').attr('disabled', '');
			$('#FormLightingOptionsOutsideLighting').attr('disabled', '');
			$('#FormLightingOptionsEmergencyLights').attr('disabled', '');
		} else {
			$('#FormLightingOptionsChandeliers').attr('disabled', 'disabled');
			$('#FormLightingOptionsLEDUpLights').attr('disabled', 'disabled');
			$('#FormLightingOptionsOutsideLighting').attr('disabled', 'disabled');
			$('#FormLightingOptionsEmergencyLights').attr('disabled', 'disabled');
		}
	});
	$('#FormDay').blur(workOutDays);
	$('#FormEvening').blur(workOutDays);
	$('#FormVenueSameAsAddress').click(function() {
		if(this.checked) {
			$('#FormVenueAddress').attr('disabled', 'disabled').val($('#FormAddress').val());
			$('#FormVenuePostcode').attr('disabled', 'disabled').val($('#FormPostcode').val());
		} else {
			$('#FormVenueAddress').val('').attr('disabled', '');
			$('#FormVenuePostcode').val('').attr('disabled', '');
		}
	})
	// Preview quotation form submission
	$('div#quoteFormContainer form').submit(formPreview);
	// remove row button clicks
	$('img.formOptionRowClose').click(removeTableRow);
});

function removeTableRow() {
	var parentType = $(this).parent().parent().attr('rel');
	var check = 'div[rel="'+parentType+'"]';
	if($(check).length > 1) {
		$(this).parent().parent().remove();
	}
}

function workOutDays() {
	var val1, val2;
	val1 = parseInt($('#FormDay').val());
	val2 = parseInt($('#FormEvening').val());
	if(isNaN(val1)) {
		val1 = 0;
	}
	if(isNaN(val2)) {
		val2 = 0;
	}
	$('#FormTotalNumberOfGuests').val(val1 + val2);
}

// Code for previewing quotation for submission
function formPreview() {
	if($('#formSummary').length > 0) {
		// already submitted
		return true;
	} else {
		// VALIDATION
		if($('#FormSurname').val() == '') {
			alert('Please enter your surname');
			return false;
		}
		if($('#FormForename').val() == '') {
			alert('Please enter your forename');
			return false;
		}
		if($('#FormEmailAddress').val() == '') {
			alert('Please enter an email address');
			return false;
		}
		if($('#FormAddress').val() == '' || $('#FormPostcode').val() == '') {
			alert('Please enter your contact address and postcode');
			return false;
		}
		if($('#FormHomePhone').val() == '' && $('#FormMobilePhone').val() == '') {
			alert('Please enter either your home or mobile phone number');
			return false;
		}
		if($('#FormVenueSameAsAddress').attr('checked') == false && ($('#FormVenuePostcode').val() == '' || $('#FormVenueAddress').val() == '')) {
			alert('Please enter the venue address and postcode');
			return false;
		}
		if($('#FormLightingRequired').val() == 'Yes') {
			if($('#FormLightingOptionsChandeliers').attr('checked') == false && $('#FormLightingOptionsLEDUpLights').attr('checked') == false && $('#FormLightingOptionsOutsideLighting').attr('checked') == false && $('#FormLightingOptionsEmergencyLights').attr('checked') == false) {
				alert('Please select at least one lighting option');
				return false;
			}
		}
		if($('#FormSeatingType').val() != 'Standing Only') {
			// we must enter tables and chairs
			var chairError = tableError = 0;
			$('.quotationChairRow input').each(function() {
				if($(this).val() == '') {
					chairError ++;
				}
			});

			$('.quotationTableRow input').each(function() {
				if($(this).val() == '') {
					tableError ++;
				}
			});

			if(chairError > 0 || tableError > 0) {
				alert('Please ensure you provide us with the number of tables and chairs you require for your seated event');
				return false;
			}
		}
		// END OF VALIDATION
		// scroll to top
		$('html, body').animate({scrollTop:0}, 'slow');
		// init
		var container = $(this).parent();
		var form = $(this);
		var fields = $('[name*=data]');
		container.css('position', 'relative');
		// add the overlay containing div
		container.append('<div id="formSummary"></div>');
		var overlay = $('#formSummary');
		// style the overlay and fade in
		overlay.css('position', 'absolute').css({'background': 'white', 'height': '92%', 'width': '90%', 'padding': '5%', 'border': '1px solid #666', 'top': 0, 'opacity': 0.9, 'display': 'none'}).fadeIn();
		// add a summary paragraph
		overlay.append('<div class="intro"><h2>Summary</h2><p>Please find the below summary of the information you supplied. If it is correct, you can click on the "Send" button below.</p></div>');
		// send / cancel buttons
		overlay.append('<div class="formSummaryOptions" style="clear:both; margin-top:10px"><button id="formPreviewSend" value="" style="float:right">OK, send this information</button><button id="formPreviewCancel">Cancel, I want to amend this information</button></div>');
		// form fields which we are manually going to manage
		var blacklist = ['TableQuantity', 'Tables', 'ChairQuantity', 'Chairs', 'OtherRequirementsDanceFloor', 'OtherRequirementsStage', 'OtherRequirementsHeaters', 'OtherRequirementsBarMarquee', 'OtherRequirementsCateringMarquee', 'OtherRequirementsToilets', 'OtherRequirementsGenerator', 'OtherRequirementsEntranceMarquee', 'LightingOptionsChandeliers', 'LightingOptionsLEDUpLights', 'LightingOptionsOutsideLighting', 'LightingOptionsEmergencyLights'];
		// loop through the form and output a summary
		$(fields).each(function() {
			var add = false;
			var title = $(this).attr('id').replace(/form/i, '');
			var value = $(this).val();
			if(value.length > 0 && this.type != 'hidden' && $(this).css('visibility', 'visible') && !in_array(title, blacklist)) {
				if(this.type == 'text') {
					add = true;
				} else if(this.type == 'textarea') {
					add = true;
				} else if(this.checked) {
					// radio / checkbox
					add = true;
					value = 'Yes';
				} else if(this.type == 'select-one' && $(this).val() != 'No' && $(this).val() != ''){
					// select box
					add = true;
				}
				if(add) {
					$('.formSummaryOptions').before('<div class="field"><span class="title"><b>' + title.underscore().humanize() + '<br/></b></span> '+ value + '</div>');
				}
			}
		});
		// loop through the blacklist fields
		var tablesText = [];
		var chairsText = [];
		var otherRequirements = [];
		var lightingOptions = [];
		var tables = [];
		var chairs = [];
		var tableQuantities = [];
		var chairQuantities = [];
		for(var bf in blacklist) {
			$('[id*=Form'+blacklist[bf]+']').each(function() {
				if(blacklist[bf] == 'TableQuantity') {
					tableQuantities.push(this.value);
				} else if(blacklist[bf] == 'Tables') {
					tables.push(this.value);
				} else if(blacklist[bf] == 'ChairQuantity') {
					chairQuantities.push(this.value);
				} else if(blacklist[bf] == 'Chairs') {
					chairs.push(this.value);
				} else if(stristr(blacklist[bf], 'otherrequirements') && this.checked) {
					otherRequirements.push(this.value);
				} else if(stristr(blacklist[bf], 'lightingoptions') && this.checked) {
					lightingOptions.push(this.value);
				}
			});
		}

		for (var t in tables) {
			tablesText.push(tableQuantities[t] + 'x ' + tables[t]);
		}

		for (var c in chairs) {
			chairsText.push(chairQuantities[c] + 'x ' + chairs[c]);
		}

		// add the manual fields to the summary
		$('.formSummaryOptions').before('<div class="field"><span class="title"><b>Tables:<br/></b></span> '+ implode('<br/>', tablesText) + '</div>');
		$('.formSummaryOptions').before('<div class="field"><span class="title"><b>Chairs:<br/></b></span> '+ implode('<br/>', chairsText) + '</div>');
		if(otherRequirements.length > 0) {
			$('.formSummaryOptions').before('<div class="field fullWidth"><span class="title"><b>Other Requirements:</b><br/></span> '+ implode(', ', otherRequirements) + '</div>');
		}
		if(lightingOptions.length > 0) {
			$('.formSummaryOptions').before('<div class="field fullWidth"><span class="title"><b>Lighting Options:</b><br/></span> '+ implode(', ', lightingOptions) + '</div>');
		}
		// add hidden fields for table / chair data
		form.append('<input type="hidden" name="data[Form][table_requirements]" value="' + implode(', ', tablesText) + '" id="tableRequirements" />');
		form.append('<input type="hidden" name="data[Form][chair_requirements]" value="' + implode(', ', chairsText) + '" id="chairRequirements" />');
		// set css styles for the summary data
		$('#formSummary div.field').css({'width':'45%', 'float':'left', 'margin':'0 5% 10px 0', 'font-size':'0.9em'});
		$('#formSummary div.fullWidth').css({'width':'100%', 'float':'none', 'margin':'0 0 10px 0', 'font-size':'0.9em'});

		// cancel event
		$('button#formPreviewCancel').click(function() {
			overlay.fadeOut('normal', function() {
				overlay.remove();
				// remove the hidden fields for chairs and tables
				$('input#chairRequirements').remove();
				$('input#tableRequirements').remove();
			});
		});
		// submit event
		$('button#formPreviewSend').click(function() {
			form.submit();
		});
		return false;
	}
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function stristr (haystack, needle, bool) {
    // Finds first occurrence of a string within another, case insensitive
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/stristr
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfxied by: Onno Marsman
    // *     example 1: stristr('Kevin van Zonneveld', 'Van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: stristr('Kevin van Zonneveld', 'VAN', true);
    // *     returns 2: 'Kevin '
    var pos = 0;

    haystack += '';
    pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() );
    if (pos == -1){
        return false;
    } else{
        if (bool) {
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

function implode (glue, pieces) {
    // Joins array elements placing glue string between items and return one string
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/implode
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}
