/*
 * booking-form.js
 * handles booking form interface componenets
 */

jQuery(document).ready(function() {

	/* Handle the onClick event for the University selection panel. */
	jQuery('#selection-panel-university .item_list').click(function(event) {
		var $uni = jQuery(event.target);

	    /* if event bubbled up from li, identify the value of the <a> tag to get the university name */
	    if($uni.is('.item')) {
		    $uni = $uni.children('a:first');
	    }
	    else if(!$uni.is('a')) {
		    return false;
	    }

	    /* Update all university related fields */
	    var uniName = $uni.html();
	    var uni_id = $uni.attr('rel');
	    jQuery('#hidden_university_id').val(uni_id);
	    jQuery('#hidden_university_name').val(uniName);
	    jQuery('#selection-panel-university').hide();
	    jQuery('#select_uni').val(uniName);

	    /* Clear all other selections if the user has changed their university after already making selections from other boxes */
	    jQuery('#select_week, #select_accom').val('').attr('disabled','disabled').addClass('disabled');
	    jQuery('#hidden_trip_id, #hidden_accom_id, #hidden_accom_name, #hidden_num_pax, #hidden_agent_ref').val('');
	    jQuery('#select_num_pax').hide();

	    /* Get load all groups from this uni into an array*/
	    var uni_groups = [];
	    for(g=0; g < groups.length; g++)
		    if(groups[g] == uni_id && groups[g+1].length > 0)
			    uni_groups = groups[g+1];


	    /* Load national partners into the list first */
	    var listbox_html = '';
	    var partner_info;
	    listbox_html += '<li class="title">National Partners</li>';
	    // Load national partners into group list
	    for(p=0; p < partners.length; p++)
	    {
			//string = partners[p];
			partner_info = partners[p].split(':');
			listbox_html += '<li class="item"><a href="#" rel="'+partner_info[0]+'" rev="'+partner_info[2]+'">'+partner_info[1]+'</a></li>';
	    }

	    // Load university groups under the national partners in the list
	    if(uni_groups.length > 0) {
		    listbox_html += '<li class="title">Groups</li>';

		    // For every group, create list elements like this:  <li><a href="#" rel="(group_username)">(group_username)</a></li>
		    for(g=0; g < uni_groups.length; g++) {
			    group_info = uni_groups[g].split(':');
			    listbox_html += '<li class="item"><a href="#" rel="'+group_info[0]+'" rev="'+group_info[2]+'">'+group_info[1]+'</a></li>';
		    }
		    
	    }
	    listbox_html += '<li class="title">Can\'t find your group?</li>';
	    listbox_html += '<li class="item"><a href="#" rel="outgoing">Not booking with group</a></li></li>';
		listbox_html += '<li class="item"><a href="/rep/" rel="/rep/">Create your Group</a></li></li>';

	    /* Update the HTML */
	    jQuery('#selection-panel-group .item_list').empty();
	    jQuery('#selection-panel-group .item_list').html(listbox_html);
	    jQuery('#select_group').val('Select your group...').removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
	});


	/* Handle onclick from group selection panel */
	jQuery('#selection-panel-group .item_list').click(function(event) {
		var group_name = jQuery(event.target);
		
		// if event bubbled up from li, identify the value of the <a> tag to get the university name
		if(group_name.is('.item')) {
			group_name = group_name.children('a:first');
		}
		else if(!group_name.is('a')) {
			return false;
		}

		/* Update hidden fields */
		jQuery('#hidden_agent_ref').val("b10_"+group_name.attr('rel'));
		jQuery('#selection-panel-group').hide();
		jQuery('#select_group').val(group_name.html());
		jQuery('#select_week, #select_accom').val('').attr('disabled','disabled').addClass('disabled');
		jQuery('#hidden_trip_id, #hidden_accom_id, #hidden_accom_name, #hidden_num_pax').val('');
		jQuery('#select_num_pax').hide();

		// get the groups perferred week if this exists
		var chosen_week = group_name.attr('rev');
		if(chosen_week == "")
		{
			jQuery('#select_week').val('Select your week...').removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
			//jQuery('#select_accom').val('').attr('disabled','disabled').addClass('disabled');
		}
		else
		{
			jQuery('#hidden_week_id').val(chosen_week);
			jQuery('#select_week').val(weeks[chosen_week]).removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
			jQuery('#select_accom').val('Choose your erection...').removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
			// Depending on the Chosen Week, make only that week's accommodation available for selection.
			var chosen_week_trip_id = trip_ids[chosen_week];
			jQuery("#selection-panel-accom ul li a[rev!='"+chosen_week_trip_id+"']").parent().hide();
			jQuery("#selection-panel-accom ul li a[rev='"+chosen_week_trip_id+"']").parent().show();
			// Set the TripId because the week has been pre-selected
			jQuery('#hidden_trip_id').val( trip_ids[chosen_week] );
		}
	});

	/* Handle onclick form week selection panel */
	jQuery('#selection-panel-week .item_list').click(function(event) {
		var week_name = jQuery(event.target);
		
		if(week_name.is('.item')) {
			week_name = week_name.children('a:first');
		}
		else if(!week_name.is('a')) {
			return false;
		}
		
		var week_code = week_name.attr('rel');
		jQuery('#hidden_trip_id').val( trip_ids[week_code] );
		jQuery('#selection-panel-week').hide();
		jQuery('#select_num_pax').hide();
		jQuery('#select_week').val(week_name.html());
		jQuery('#select_accom').val('Choose your erection...').removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);

		// Depending on the Chosen Week, make only that week's accommodation available for selection.
		var chosen_week_trip_id = jQuery('#hidden_trip_id').val();
		jQuery("#selection-panel-accom ul li a[rev!='"+chosen_week_trip_id+"']").parent().hide();
		jQuery("#selection-panel-accom ul li a[rev='"+chosen_week_trip_id+"']").parent().show();
		// Reset the accomodation_id
		jQuery('#hidden_accom_id').val('');
	});

	jQuery('#selection-panel-accom .item_list').click(function(event) {
		var accommElm = jQuery(event.target);
		
		if(accommElm.is('.item')) {
			accommElm = accommElm.children('a:first');
		}
		else if(!accommElm.is('a')) {
			return false;
		}
		
		var accomm_id = accommElm.attr('rel');
		var accomm_name = accommElm.html();
		jQuery('#hidden_accom_id').val(accomm_id);
		jQuery('#selection-panel-accom').hide();
		jQuery('#select_accom').val(accomm_name);
		
		//Extract the room/berth size from the Accommodation name
		var pos = accomm_name.lastIndexOf('-');
		if(pos > 0)
		{
			var room_size = accomm_name.substr(pos+2);
			room_size = room_size.charAt(0);
			if(isNaN(room_size)==true) {
				//Set a default room size.
				room_size = 1;
			}
		}
		else
		{
		    // set default room size to 1   
		    jQuery('#hidden_num_pax').val('1');
		}
		jQuery('#hidden_num_pax').val(room_size);

		
		//Set the accommodation name
		if(accomm_name.indexOf("-") >= 0)
		{
		    jQuery('#hidden_accom_name').val( accomm_name.substring(0, accomm_name.lastIndexOf('-')-1) );
		}
		else
		{
		    jQuery('#hidden_accom_name').val( accomm_name );
		}

		//If the user has selected camping, ask how many pax
		if(accomm_name == 'Camping')
		{
		    jQuery('#select_num_pax').show().effect("highlight", {}, 2000);
		}
		else {
			jQuery('#select_num_pax').hide();
		}
	});
	
	
	/* Handle the onClick event for the University selection panel. */
	jQuery('#selection-panel-university-mallorca .item_list').click(function(event) {
		var $uni = jQuery(event.target);

	    /* if event bubbled up from li, identify the value of the <a> tag to get the university name */
	    if($uni.is('.item')) {
		    $uni = $uni.children('a:first');
	    }
	    else if(!$uni.is('a')) {
		    return false;
	    }

	    /* Update all university related fields */
	    var uniName = $uni.html();
	    var uni_id = $uni.attr('rel');
	    jQuery('#selection-panel-university-mallorca').hide();
	    jQuery('#select_uni_mallorca').val(uniName);

	    /* Get load all groups from this uni into an array */
	    var uni_groups = [];
	    for(g=0; g < groups.length; g++) {
		    if(groups[g] == uni_id && groups[g+1].length > 0) {
			    uni_groups = groups[g+1];
		    }
	    }

	    /* Load national partners into the list first */
	    var listbox_html = '';
	    var partner_info;
	    listbox_html += '<li class="title">National Partners</li>';
	    // Load national partners into group list
	    for(var p=0; p < partners.length; p++)
	    {
	    	//string = partners[p];
	    	partner_info = partners[p].split(':');
	    	listbox_html += '<li class="item"><a href="#" rel="'+partner_info[0]+'|'+partner_info[3]+'|'+partner_info[4]+'" rev="'+partner_info[2]+'">'+partner_info[1]+'</a></li>';
	    }

	    // Load university groups after the national partners in the list
	    if(uni_groups.length > 0) {
		    listbox_html += '<li class="title">Groups</li>';
		    // For every group, create list elements like this:  <li><a href="#" rel="(group_username)">(group_username)</a></li>
		    for(g=0; g < uni_groups.length; g++) {
			    group_info = uni_groups[g].split(':');
			    listbox_html += '<li class="item"><a href="#" rel="'+group_info[0]+'|'+group_info[3]+'|'+group_info[4]+'" rev="'+group_info[2]+'">'+group_info[1]+'</a></li>';
		    }
		    
	    }
	    listbox_html += '<li class="title">Can\'t find your group?</li>';
	    listbox_html += '<li class="item"><a href="#" rel="outgoing">Not booking with group</a></li></li>';
		listbox_html += '<li class="item"><a href="/rep/" rel="/rep/">Create your Group</a></li></li>';

	    /* Update the HTML */
	    jQuery('#selection-panel-group-mallorca .item_list').empty();
	    jQuery('#selection-panel-group-mallorca .item_list').html(listbox_html);
	    jQuery('#select_group_mallorca').val('Select your group...').removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
	});
	
	
	/* Handle onclick from group selection panel */
	jQuery('#selection-panel-group-mallorca .item_list').click(function(event) {
		var group_name = jQuery(event.target);
		
		// if event bubbled up from li, identify the value of the <a> tag to get the group name
		if(group_name.is('.item')) {
			group_name = group_name.children('a:first');
		}
		else if( ! group_name.is('a')) {
			return false;
		}
		
		var group_details = group_name.attr('rel').split('|');

		/* Update hidden fields */
		jQuery('#selection-panel-group-mallorca').hide();
		jQuery('#select_group_mallorca').val(group_name.html());
		if(typeof group_details[1] == 'undefined' || parseInt(group_details[1]) == 0) {
			group_details[1] = '';
		}
		if(typeof group_details[2] == 'undefined' || group_details[2].length == 0) {
			group_details[2] = '';
		}
		
		jQuery('#AGRef').val(group_details[1]);
		jQuery('#AGKey').val(group_details[2]);
		
		jQuery('#select_group_mallorca').val(group_name.html());
		jQuery('#select_package, #select_flyingfrom, #select_arrivaldate, #select_checkoutdate, #select_rooms').removeAttr("disabled").removeClass('disabled');
		jQuery('#select_package').effect("highlight", {}, 2000);
	});
	
	
	/* Handle onclick from package selection panel */
	jQuery('#selection-panel-package .item_list').click(function(event) {
		var package_name = jQuery(event.target);
		
		// if event bubbled up from li, identify the value of the <a> tag to get the holiday package type
		if(package_name.is('.item')) {
			package_name = package_name.children('a:first');
		}
		else if( ! package_name.is('a')) {
			return false;
		}
		
		// Update the search_type parameter depending on whats being searched for.
		var transportType = (package_name.html() == 'Flight') ? 'Flight' : 'Tour';
		jQuery('#search_type').val(transportType);

		/* Update hidden fields */
		jQuery('#selection-panel-package').hide();
		var $sp = jQuery('#select_package'); 
		$sp.val(package_name.html());
		
		jQuery('#tourtransportmethod').val(package_name.attr('rel'));
		jQuery('#select_flyingfrom').removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
	});
	
	
	/* Handle onclick from package selection panel */
	jQuery('#selection-panel-flyingfrom .item_list').click(function(event) {
		var flyingfrom = jQuery(event.target);
		
		// if event bubbled up from li, identify the value of the <a> tag to get the university name
		if(flyingfrom.is('.item')) {
			flyingfrom = flyingfrom.children('a:first');
		}
		else if( ! flyingfrom.is('a')) {
			return false;
		}
		
		var airportName = flyingfrom.attr('rev');
		airportName.replace('-', '');
		jQuery('#airportfrom').val(flyingfrom.attr('rel'));

		/* Update hidden fields */
		jQuery('#selection-panel-flyingfrom').hide();
		jQuery('#select_flyingfrom').val(airportName);
		var $arrival = jQuery('#select_arrivaldate');
		if($arrival.val() == '') {
			$arrival.val('Choose your Arrival date...');
		}
		$arrival.removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
	});
	
	
	/* Handle onclick from package selection panel */
	jQuery('#selection-panel-arrivaldate .item_list').click(function(event) {
		var arrival = jQuery(event.target);
		
		// if event bubbled up from li, identify the value of the <a> tag to get the university name
		if(arrival.is('.item')) {
			arrival = arrival.children('a:first');
		}
		else if( ! arrival.is('a')) {
			return false;
		}
		
		var startDate = arrival.attr('rel');
		
		alert(startDate);

		/* Update hidden fields */
		jQuery('#selection-panel-arrivaldate').hide();
		jQuery('#select_arrivaldate').val(arrival.html());
		jQuery('#startdate').val(startDate);
		var $checkout = jQuery('#select_checkoutdate');
		if($checkout.val() == '') {
			$checkout.val('Checkout date...');
		}
		$checkout.removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
		
		//Set the startdate breakdown for "Flight Only" search.
	    jQuery('#startdate_d').val( parseInt(startDate.substr(0,2)) );
	    jQuery('#startdate_m').val( parseInt(startDate.substr(3,2)) );
	    jQuery('#startdate_y').val( startDate.substr(6,4) );
	    
	    //Extract the Days from start/end dates (first 2 chars - date is in dd/mm/yyyy format)
	    //and calculate the difference in days.
	    var endDate = jQuery('#enddate').val();
	    var $days = parseInt(endDate.substr(0,2)) - parseInt(startDate.substr(0,2));
	    jQuery('#duration').val($days);
	});
	
	
	/* Handle onclick from package selection panel */
	jQuery('#selection-panel-checkoutdate .item_list').click(function(event) {
		var checkout = jQuery(event.target);
		
		// if event bubbled up from li, identify the value of the <a> tag to get the university name
		if(checkout.is('.item')) {
			checkout = checkout.children('a:first');
		}
		else if( ! checkout.is('a')) {
			return false;
		}
		
		var endDate = checkout.attr('rel');

		/* Update hidden fields */
		jQuery('#selection-panel-checkoutdate').hide();
		jQuery('#select_checkoutdate').val(checkout.html());
		jQuery('#enddate').val(endDate);
		var $rooms = jQuery('#select_rooms');
		if($rooms.val() == '') {
			$rooms.val('No. of rooms...');
		}
		$rooms.removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
		
		//Set the enddate breakdown for "Flight Only" search.
		var endDate = checkout.attr('rel');
	    jQuery('#enddate_d').val( parseInt(endDate.substr(0,2)) );
	    jQuery('#enddate_m').val( parseInt(endDate.substr(3,2)) );
	    jQuery('#enddate_y').val( parseInt(endDate.substr(6,4)) );
	    
	    //Extract the Days from start/end dates (first 2 chars - date is in dd/mm/yyyy format)
	    //and calculate the difference in days.
	    var startDate = jQuery('#startdate').val();
	    var $days = parseInt(endDate.substr(0,2)) - parseInt(startDate.substr(0,2));
	    jQuery('#duration').val($days);
	});
	
	
	/* Handle onclick from package selection panel */
	jQuery('#selection-panel-rooms .item_list').click(function(event) {
		var rooms = jQuery(event.target);
		
		// if event bubbled up from li, identify the value of the <a> tag to get the university name
		if(rooms.is('.item')) {
			rooms = rooms.children('a:first');
		}
		else if( ! rooms.is('a')) {
			return false;
		}

		/* Update hidden fields */
		jQuery('#selection-panel-rooms').hide();
		jQuery('#select_rooms').val(rooms.html());
		jQuery('#room1adults').val(rooms.attr('rel'));
	});
	

	//
	// Handle each selection panel's red 'close' button.
	//
	jQuery('div.close_trip_builder_list').click(function(event) {
		var $closeBtn = jQuery(event.target);
		jQuery('#' + $closeBtn.parent().attr('id')).hide();
	});

	
	jQuery('div.trip-builder-block input[type=\'text\']').click(function(event) {
		var $inputBox = jQuery(event.target);
		var elm_id = $inputBox.attr('id');
		
		var selectionPanels = new Array();
		selectionPanels['select_uni'] = 'selection-panel-university';
		selectionPanels['select_group'] = 'selection-panel-group';
		selectionPanels['select_week'] = 'selection-panel-week';
		selectionPanels['select_accom'] = 'selection-panel-accom';
		//selection panels for Mallorca booking form
		selectionPanels['select_uni_mallorca'] = 'selection-panel-university-mallorca';
		selectionPanels['select_group_mallorca'] = 'selection-panel-group-mallorca';
		selectionPanels['select_package'] = 'selection-panel-package';
		selectionPanels['select_flyingfrom'] = 'selection-panel-flyingfrom';		
		selectionPanels['select_arrivaldate'] = 'selection-panel-arrivaldate';		
		selectionPanels['select_checkoutdate'] = 'selection-panel-checkoutdate';		
		selectionPanels['select_rooms'] = 'selection-panel-rooms';
		
		// Obtain the panel to display
		var panel = jQuery('#'+selectionPanels[elm_id]);
		
		// If the panel is already open, make sure it is not displayed again.
		// Users can then re-click the input box to close the panel.
		var showPanel = (panel.css('display') == 'none') ? true : false;
		
		// Pro-actively set the top of the panel to appear directly underneath the input box.		
		panel.css('top', $inputBox.position().top + $inputBox.innerHeight());
		panel.css('left',$inputBox.position().left - 80);
		
		//Before displaying the panel, hide all other panels first.
		jQuery('.trip-builder-list').hide();
		if(showPanel) {
			panel.show();
		}
	});

});


/* Functions called by the template to adjust the form for use on the homepage or grouppage */

/* On page submit, check all required fields are filled in */
function validate_newquay_form()
{
    if(jQuery('#hidden_university_id').val() == '')
    {
		alert('Please select your University');
		return false;
    }
    if(jQuery('#hidden_agent_ref').val() == '')
    {
        alert('Please select a group');
        return false;
    }
    if(jQuery('#hidden_trip_id').val() == '')
    {
        alert('Please select the week you want to go');
        return false;
    }
	
	var accomm = jQuery('#hidden_accom_id').val();
    if(accomm == '')
    {
        alert('Please select your accommodation');
        return false;
    }
	if(parseInt(accomm) == 0)
	{
		alert('Sorry, you cannot book sold out accommodation. Remember our Caravans sell out super quick!');
		return false;
	}
    
    return true;
}

function validate_mallorca_form()
{
	return true;
}

/*
 * initialize the booking form for homepage
 * activate all functionality
 */
function init_booking_form_newquay_homepage()
{
	/* When page is loaded reset the booking form */
	jQuery('#select_uni').removeAttr('disabled').removeClass('disabled').val('Select your University...');
	jQuery('#select_group, #select_week, #select_accom').val('').attr('disabled','disabled').addClass('disabled');
}

/*
 * initialize the booking form for group pages
 * disable choose uni and choose group functionality
 */
function init_booking_form_newquay_group_page(uni_id, uni_name, group_name, group_username, group_default_week)
{
	/* Set university field values */
	jQuery('#select_uni').val(uni_name);
	jQuery('#hidden_university_id').val(uni_id);

	/* Set group field values */
	jQuery('#select_group').val(group_name);
	jQuery('#hidden_agent_ref').val('b10_'+group_username);

	/* Set week to default week */
	jQuery('#hidden_week_id').val(group_default_week);
	jQuery('#select_week').val(weeks[group_default_week]).removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
	jQuery('#select_accom').val('Choose your erection...').removeAttr("disabled").removeClass('disabled').effect("highlight", {}, 2000);
	// Depending on the Chosen Week, make only that week's accommodation available for selection.
	var chosen_week_trip_id = trip_ids[group_default_week];
	jQuery("#selection-panel-accom ul li a[rev != '"+chosen_week_trip_id+"']").parent().hide();
	jQuery("#selection-panel-accom ul li a[rev = '"+chosen_week_trip_id+"']").parent().show();
	// Set the TripId because the week has been pre-selected
	jQuery('#hidden_trip_id').val( trip_ids[group_default_week] );

	/* Enable/disable fields */
	jQuery('#select_uni, #select_group').attr('disabled','disabled').addClass('disabled');
}

function init_booking_form_mallorca_homepage()
{
	/* When page is loaded reset the booking form */
	//jQuery('#select_uni_mallorca').removeAttr('disabled').removeClass('disabled').val('Select your University...');
	jQuery('#select_group_mallorca, #select_package, #select_flyingfrom, #select_arrivaldate, #select_checkoutdate, #select_rooms').attr('disabled','disabled').addClass('disabled');
}

function init_booking_form_mallorca_group_page(uni_id, uni_name, group_name, group_username, group_default_week, group_agref, group_agkey)
{
	/* Set university field values */
	jQuery('#select_uni_mallorca').val(uni_name);

	/* Set group field values */
	jQuery('#select_group_mallorca').val(group_name);
	
	if(parseInt(group_agref) == 0) {
		group_agref = '';
	}
	if(group_agkey.length == 0) {
		group_agkey = '';
	}
	
	jQuery('#AGRef').val(group_agref);
	jQuery('#AGKey').val(group_agkey);

	/* Enable/disable fields */
	jQuery('#select_uni_mallorca, #select_group_mallorca, #select_package, #select_flyingfrom, #select_arrivaldate, #select_checkoutdate, #select_rooms').removeAttr('disabled').removeClass('disabled');
}

/* Update passenger number for camping option hidden field */
function update_passenger_number()
{
    var pax_num = jQuery('#select_num_pax').val();
    jQuery('#hidden_num_pax').val(pax_num);
}

