var gWin;
var lastArea;
var lastCountry;
var AccountCountry = new Array();
var sexes = new Array(10);
var ages = new Array(10);
var lastSource;
var lastCount;

var sp_last_camper_count;
var sp_last_change;
var selectedSession = -1;
var entered_email;
var selected_year;
var selected_month;

//function LoadContent(content) {
//    $.get('components/ContentRead.aspx?c=' + content, function (data) {
//        if (data != null) {
//            $('#' + content).html(data.content);

//            if (data.script) {
//                jQuery.globalEval(data.script);
//            }
//        }
//    });
//}

function LoadContent( content ){
	new Ajax.Request('components/ContentRead.aspx?c=' + content, {
		method: 'get',
		onSuccess: function(transport) {
			if( transport.responseText.length > 0){
				var json = transport.responseText.evalJSON(true);

				if( json ) {
					$(content).insert( { bottom: json.content} );
					
					if( json.script ) {
						eval(json.script);
					}
				}
			}
		}
	});
}

function SP_NextStep( page ){
	var pageNumber = $F('pagenumber');
	
	switch( pageNumber ) {
	case '0':
		// check sex/ages
		SP_CheckPrices( page );
		break;
	default:
		window.location = page;
	}
	
	return false;
}

function PS_ValidateOnLoad() {
	var cc = $("camper_count").value;
	
	for (i=0; i<cc; i++ ){
		PS_CDChange( 'S', i );
		PS_CDChange( 'A', i );
	}
	
	sp_last_camper_count = cc;
}

function PS_CamperCountChange() {
    var selectedParent = $("camper_count").value;
	    
    // Update both affected fields
    if( selectedParent.length > 0 && sp_last_camper_count != selectedParent ){
    
		new Ajax.Updater({ success: 'CamperSelections' }, 'components/SalesProcess.aspx?CHANGE=camper_count&TARGET=camper_row&PARAM=' + selectedParent, { 
			method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    if( selectedParent != "" ) {
						$('camper_select_heading').show();
					}
                }
                sp_last_camper_count = selectedParent;
            }
		 } );
    }
}

function PS_CDChange( type, count ) {
    var val = ( type == 'S' ? $('sex_' + count).value : $('age_' + count).value );
		
	if( ( type == 'S' && sexes[count] != val ) || ( type == 'A' && ages[count] != val ) ){
			new Ajax.Updater({ success: 'SP_' + type + count }, 'components/SalesProcess.aspx?CHANGE=' + type +'&TARGET=' + type +'&PARAM=' + val + '&PARAM2=' + count, { 
			method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
					if(type == 'S') {
						sexes[count] = val;
					} else {
						ages[count] = val;
					}
				}
            }
		 } );
	}
}

function SP_CheckPrices( location ){
	var abort = false;
	
	if( $F('camper_count') != null && $F('camper_count') != "" ){
		sp_last_camper_count = $F('camper_count');
		
		var extraData = '';
		
		for(i=0; i<sp_last_camper_count; i++){
			if( !$F('sex_' + i) ) {
				alert('Please fill out the camper details.');
				$('sex_'+i).focus();
				abort = true;
				break;
			}
			
			if( !$F('age_' + i) ) {
				alert('Please fill out the camper details.');
				$('age_'+i).focus();
				abort = true;
				break;
			}
			
			// store the valid details
			extraData = extraData + 'age_' + i + '=' + $F('age_' + i) + ',sex_' + i + '=' + $F('sex_' + i) + '|';
		}
		
		if( abort ) {
			return false;
		} else {
			// Check validity now (and remember to save the cookie with the entered info)
			new Ajax.Request('components/SalesProcess.aspx?CHANGE=1&isValidCheck=' + extraData, {
				method: 'post',
				onSuccess: function(transport) {
					if( transport.responseText.length > 0 && transport.responseText == '1' ) {
						window.location = location;
					} else {
						DisplayDialogWindow( 'ValidateCamperDetails', true, extraData );
					}		
				}
			});
			
			return false;
		}
		
	} else {
		alert("Please enter how many campers you are checking availability for.");
		return false;
	}
}

function SP_CamperCountChange() {
    var selectedParent = $("camper_count").value;
	    
    // Update both affected fields
    if( selectedParent.length > 0 && sp_last_camper_count != selectedParent ){
    		new Ajax.Updater({ success: 'CamperSelections' }, 'components/SalesProcess.aspx?CHANGE=camper_count&TARGET=camper_row&PARAM=' + selectedParent, { 
			method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    if( selectedParent != "" ) {
						$('camper_select_heading').show();
					}
					
					SP_Toggle( 'camperCount', selectedParent );
                }
                sp_last_camper_count = selectedParent;
            }
		 } );
		 /*
        new Ajax.Request('components/SalesProcess.aspx?CHANGE=camper_count&TARGET=sales_camper_row&PARAM=' + selectedParent, {
            method: 'get',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    $('CamperSelections').update( transport.responseText );
                    
                    if( selectedParent != "" ) {
						$('camper_select_heading').show();
					}
					
					SP_Toggle( 'camperCount', selectedParent );
                }
                sp_last_camper_count = selectedParent;
            }
        });*/
    }
}

function SP_CDChange( type, count ) {
	PS_CDChange(type,count);
}

function SP_SelectSession( session ) {
	$(session).checked = true;
	
	SP_SessionSelected( $F(session) );
}

function SP_SessionSelected( session ) {
	// Update Cost
	$('tldr').innerHTML = '<img src="img/loading.gif"/>';

	new Ajax.Updater({ success: 'SP_Cost' }, 'components/SalesProcess.aspx?CHANGE=session&TARGET=COST&PARAM=' + session + '&PN=' + $F('pagenumber'), { method: 'post' } );
}

function SP_UpdateTotals( what, field, id ) {
	// Update Invoice
	$('tldr').innerHTML = '<img src="img/loading.gif"/>';

	new Ajax.Updater({ success: 'SP_Cost' }, 'components/SalesProcess.aspx?CHANGE='+what+'&TARGET=COST&PARAM=' + id + "&PARAM2=" + $F(field) + '&PN=' + $F('pagenumber'), { method: 'post' } );
}

function SP_Toggle( type, togval ) {
	if( type == 'INS' && togval == 0 ) {
		DisplayDialogWindow( 'DeselectInsurance', true, '' );
	} else {
		// Update Invoice
		$('tldr').innerHTML = '<img src="img/loading.gif"/>';
		
		new Ajax.Updater({ success: 'SP_Cost' }, 'components/SalesProcess.aspx?CHANGE='+type+'&TARGET=COST&PARAM=' + togval + '&PN=' + $F('pagenumber'), { method: 'post' } );
	}
	return false;
}

function SP_DeselectInsurance() {
	CloseForm();

	// Update Invoice
	$('tldr').innerHTML = '<img src="img/loading.gif"/>';
	
	new Ajax.Updater({ success: 'SP_Cost' }, 'components/SalesProcess.aspx?CHANGE=INS&TARGET=COST&PARAM=0&PN=' + $F('pagenumber'), { method: 'post' } );
	
	return false;
}

function SP_Account( exists ) {

	new Ajax.Request('components/SalesProcess.aspx?CHANGE=SIGNINTYPE&TARGET=SIGNIN&PARAM=' + exists, {
		method: 'post',
		onSuccess: function(transport) {
			if( transport.responseText.length > 0){
				$('salesmain').update( transport.responseText );
			}
		}
	});
	
	return false;
}

/*
function SP_FindEmail( email_addr ) {
	if( entered_email != email_addr ) {
		// Is there an entry in the leads table for this?
		new Ajax.Request('components/SalesProcess.aspx?CHANGE=ACCLU&TARGET=EMAIL&PARAM=' + email_addr, {
			method: 'get',
			onSuccess: function(transport) {
				if( transport.responseText.length > 0){
					var json = transport.responseText.evalJSON(true);

					if( json ) {
						$('fname').value = json.firstName;
						$('lname').value = json.lastName;
						$('Title').value = json.titleID;
						$('Address1').value = json.address1;
						$('Address2').value = json.address2;
						$('Address3').value = json.address3;
						$('Postcode').value = json.postcode;
						$('Country').value = json.countryCode;
						$('Mobile').value = json.mobileNumber;
						
						// store
						entered_email = email_addr;
						
						// Update region id
						$('Region').update( json.regionList );
						
					}
				}
			}
		});
	} 	
}*/

function SP_BillingAddressChange() {
	if( $F('Billing') != "true" ) {
		$('billing_address').show();
	} else {
		$('billing_address').hide();
	}
}

function SP_CountryChange( element, target ) {
/*    var selectedParent = $(element).value;
	    
    // Update both affected fields
    if( selectedParent.length > 0 && AccountCountry[element] != selectedParent ){
        new Ajax.Request('components/SalesProcess.aspx?CHANGE=country&TARGET=region&PARAM=' + selectedParent, {
            method: 'get',
            onSuccess: function(transport) {
				AccountCountry[element] = selectedParent;
            
                if( transport.responseText.length > 0){
                    $(target).update( transport.responseText );
                }
            }
        });
    }
*/
}

function SP_SelectCamper() {
    var camperID = $F('CamperSelect');
	    
    // Update both affected fields
    if( camperID.length > 0 ){
        new Ajax.Request('components/SalesProcess.aspx?CHANGE=camper&TARGET=camper_details&PARAM=' + camperID, {
            method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    $('salesmain').update( transport.responseText );
                }
            }
        });
    }
}

function SP_UpdateBirthDate(){
    var month = $F('BirthDate_MM');
    var year = $F('BirthDate_YY');
    var day = $F('BirthDate_DD');
	    
    // Update both affected fields
    if( month != selected_month || year != selected_year ){
        new Ajax.Request('components/SalesProcess.aspx?CHANGE=birthDate&TARGET=birthDate&PARAM=' + month + '&PARAM2=' + year + '&PARAM3=' + day + '&PARAM4=' + $F('ThisChild'), {
            method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    $('birthDateSelection').update( transport.responseText );
                    
                    selected_month = month;
                    selected_year = year;
                }
            }
        });
    }
	
}

function SP_CamperAddressChange() {
	if( $F('Address') != "true" ) {
		$('address_entry').show();
	} else {
		$('address_entry').hide();
	}
}

function SP_MedicalChange(){
	if( $F('MedicalCondition') == "true" ) {
		$('medical_entry').show();
	} else {
		$('medical_entry').hide();
	}
}

function SP_DietaryChange(){
	if( $F('DietaryRequirements') == "true" ) {
		$('dietary_entry').show();
	} else {
		$('dietary_entry').hide();
	}
}

function SP_ParticipationChange(){
	if( $F('ParticipateInAll') == "true" ) {
		$('participation_prevented').hide();
	} else {
		$('participation_prevented').show();
	}
}

function SP_UpdatePayment( type, amount, formattedamount ) {
	$('inputamount').value = amount;
	$('paymenttype').value = ( type == 'd' ? 'Deposit Amount' : 'Amount');
}

// Area change; update state
function FP_AreaChange(){
    var selectedParent = $("Area").value;
	    
    // Update both affected fields
    if( lastArea != selectedParent ){
        new Ajax.Request('components/FindPackage.aspx?CHANGE=area&TARGET=state&PARAM=' + selectedParent, {
            method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    $('State').update( transport.responseText );
                }
                lastArea = selectedParent;
            }
        });
    }
}

function FP_CampSelected(){
	var camp = $("CampName").value;
	
	if( camp != '' ) {
		window.location = 'components/FindPackage.aspx?camp=' + camp;
	}
}

// Leads Capture Details
function LC_CountryChange() {
    var selectedParent = $("Country").value;
	    
    // Update both affected fields
    if( selectedParent.length > 0 && lastCountry != selectedParent ){
        new Ajax.Request('components/LeadsCapture.aspx?CHANGE=country&TARGET=region&PARAM=' + selectedParent, {
            method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    $('Region').update( transport.responseText );
                }
                lastCountry = selectedParent;
            }
        });
    }
}

function LC_SourceChanged(){
    var selectedParent = $("How1").value;
    
    // Update both affected fields
    if( selectedParent.length > 0 &&  lastSource != selectedParent ){
        new Ajax.Request('components/LeadsCapture.aspx?CHANGE=how1&TARGET=howheard2&PARAM=' + selectedParent, {
            method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0){
                    $('q10a').update( transport.responseText );
                    $('q10a').show();
                } else {
					$('q10a').hide();
                }
                lastSource = selectedParent;
                
            },
            onFailure: function(transport) {
				$('q10a').hide();            
            }
        });
    }
}

function LC_MailBrochure() {
	var typeValue = '';
	var elem = $('q12');
	
	if( $$('input[type=checkbox][name=Brochure]:checked').first() != null ) {
		typeValue = $$('input[type=checkbox][name=Brochure]:checked').first().value;
	}

	if( typeValue != 'M' ) {
		elem.hide();
	} else{
		elem.show();
		new Effect.Highlight( elem, { startcolor: '#ffff99', endcolor: '#f2f2f2' } );
	}
	
}

function LC_CamperCountChanged(){
    var selectedParent = $("CamperCount").value;
    
    // Update both affected fields
    if( selectedParent.length > 0 && lastCount != selectedParent ){
        new Ajax.Request('components/LeadsCapture.aspx?CHANGE=campercount&TARGET=camperdetails&PARAM=' + selectedParent, {
            method: 'post',
            onSuccess: function(transport) {
                if( transport.responseText.length > 0 ){
					$('CI').update( transport.responseText );
                }
                lastCount = selectedParent;
                
            },
            onFailure: function(transport) {
				$('CI').hide();            
            }
        });
    }
}

function LC_Validate() {
	var rv = true;
	
	if( $F('Title') == '' ) {
		alert("Please enter your title");
		$('Title').focus();
		rv = false;
	}
	
	if( rv && $F('fname') == '' ) {
		alert("Please enter your first name");
		$('fname').focus();
		rv = false;
	}
	
	if( rv && $F('lname') == '' ) {
		alert("Please enter your last name");
		$('lname').focus();
		rv = false;
	}
	
	if( rv && !CheckEmail( $F('Email') ) ) {
		alert("Please enter your email address");
		$('Email').focus();
		rv = false;
	}
			
	if( rv && $F('Country') == '' ) {
		alert("Please select your country of residence");
		$('Country').focus();
		rv = false;
	}
				
	if( rv && $F('Address1') == '' ) {
		alert("Please enter your address details");
		$('Address1').focus();
		rv = false;
	}
				
	if( rv && $F('How1') == '' ) {
		alert("Please select how you heard about the Camper programme");
		$('How1').focus();
		rv = false;
	}
	
	if( rv && $F('How2') == '' ) {
		alert("Please enter how you heard about the Camper programme");
		$('How2').focus();
		rv = false;
	}
	
		
	if( rv ) {
		var brochure = '';
		
		if( $$('input[type=checkbox][name=Brochure]:checked').first() != null ) {
			brochure = $$('input[type=checkbox][name=Brochure]:checked').first().value;
		}	
		
		if( brochure == '' ) {
			alert("Please select how you would like to receive your Camper programme brochure");
			rv = false;
		}
	}
	
	return rv;
}

/// utility functions
function CheckEmail(em){	
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    return ( pattern.test(em) ) ;
}

function DisplayDialogWindow( dialogName, isModal, extraData ) {
	var url = "components/DisplayDialog.aspx";
	
	new Ajax.Updater('MWA', url, 
		{
		parameters: { dialog: dialogName, modal: isModal, extra: extraData },
		onComplete:	
			function(transport) 
			{
				ShowDialog(isModal);
			}
		}
	);
}

function ShowDialog( isModal ) {
		if( isModal ) { $('modalBackground').style.display = 'block'; }

		$('modalWindow').style.left = '-10000px';
		$('modalWindow').style.display = 'block';
		$('modalWindow').style.height = ( $('modalWindow').getHeight() + 52 ) + 'px';
		
		if( $F('md_init').length > 0 ){
			eval($F('md_init'));
			$('md_init').value = '';
		}
	
		CenterDialog();

		gWin = new Draggable('modalWindow', {
				handle: 'modalHeader',
				starteffect:function(){
				  new Effect.Opacity('modalWindow');
				},
				endeffect:function(){
				  new Effect.Opacity('modalWindow');
				}
			  });
		gWin.element.setStyle({ cursor: '' });
}

///
/// Size and centre the dialog
///
function SizeDialog( size ) {
	var div = $('modalWindow');
	div.style.height = size;
	
	CenterDialog();
}

function CenterDialog() {
	// we only need to move the dialog based on scroll position if
	//   we're using a browser that doesn't support position: fixed, like < IE 7
	var left = window.XMLHttpRequest == null ? document.documentElement.scrollLeft : 0;
	var top = window.XMLHttpRequest == null ? document.documentElement.scrollTop : 0;
	var div = $('modalWindow');

	div.style.left = Math.max((left + (GetWindowWidth() - div.offsetWidth) / 2), 0) + 'px';
	div.style.top = Math.max((top + (GetWindowHeight() - div.offsetHeight) / 2), 0) + 'px';
}

function CloseForm() {
	$('modalWindow').hide();
	$('modalBackground').hide();

	gWin = null;

	if( $('MWA') != null ) {
		$('MWA').innerHtml = '';
	}

	return false;
}

function GetWindowWidth() {
	var width =
		document.documentElement && document.documentElement.clientWidth ||
		document.body && document.body.clientWidth ||
		document.body && document.body.parentNode && document.body.parentNode.clientWidth ||
		0;
		
	return width;
}

function GetWindowHeight() {
    var height =
		document.documentElement && document.documentElement.clientHeight ||
		document.body && document.body.clientHeight ||
  		document.body && document.body.parentNode && document.body.parentNode.clientHeight ||
  		0;
  		
  	return height;
}

// From http://agrath.blogspot.com/2007/11/prototypejs-text-caretselection-methods.html
function setCaretPos(oField, iCaretPos) {
	if (Prototype.Browser.IE) {
		var oSel = document.selection.createRange ();
		oSel.moveStart ('character', -oField.value.length);
		oSel.moveStart ('character', iCaretPos);
		oSel.select ();
	}else{
		oField.selectionStart = iCaretPos;
		oField.selectionEnd = iCaretPos;
		oField.focus();
	}
}


