/**
 * This File contains all the source code JS for the Movember Forms
 */

if (typeof mov === 'undefined')
    var mov = {};

function form_setupWatermarks()
{
    $("input[watermark='1']").each( function() {
        $( this ).watermark( $( this ).next( "p.description" ).text() );
        if( typeof SamuraiCms == 'undefined' ) // Don't hide the description if we're in CMS mode
            $( this ).next().css( 'display', 'none' );
    } );
}

/**
 * Part of the Registration Form
 * If Team Captain radio has been selected, then we can add in the team field
 * Hide it again, if the person changes there mind. 
 * Also make sure that the value is set to something, so if it's hidden it doesn't make the form invalid
 */
function showTeamField( input, id )
{
	if( input.value == "captain" )
	{
//		$('#team-label').slideDown("fast");
//		$('#team-element').slideDown("fast");
		$('#register-team').slideDown("fast");
		$('#team').val("");
		//Set the step number back to 1
		$('#rego_steps_number').html( "1" );
	}
	else
	{
//		if( $('#team-label') != "none" )
//		{
//			$('#team-label').slideUp("fast");
//			$('#team-element').slideUp("fast", function() {
//				$('#'+id).attr("value", "0");
//			});
//		}
		$('#register-team').slideUp("fast", function() {
			$('#'+id).attr("value", "0");
		});
	}
	
	//Set the step number back to 1 or 2 depending on the value selected
	if( input.value == 'team' )
	{
		$('div.process_message').hide();
		$('#rego_steps_1_2').show();
	}
	else
	{
		$('div.process_message').hide();
		$('#rego_steps_1_1').show();
	}
}

/**
 * Part of the Details form. This replaces the Location field with a text of the selected
 * location and a change button. Data obtained via ajax autocomplete fucntion appliod
 * to the document.ready() in the form phtml.
 * 
 * @param row - The selected location
 * @return false if they try to select 'No matches found'
 */
function setLocation( row, id )
{
	if( row.id == -1 )
	{
		alert( 'You must indicate a location' );
		return false;
	}
	else if( row.postcode )
	{
		var output = row.suburb + ", " + row.postcode + ", " + row.state;
		if( id == null )
			id = row.id;
	}
	else
	{
            var output = row.suburb + ", " + row.state;
            if( id == null )
                id = row.id;
	}

	output += '<button onClick="changeLocation();">Change</button>';
	var parnetElement = $('#location').parent();
	parnetElement.after( '<div id="selectedSuburb">' + output + '</div>' );

	$('#selectedSuburb').addClass("selectedSuburb");
	$('#searchPredictionResults').css('display','none');

	$('#location_id').val( id );
	$("#location").css( 'display', 'none' );
	$("#location + p.description").css('display','none');
	
	return true;
}

/**
 * Called when a user has selected a suburb, but then wants to change it.
 */
function changeLocation()
{
	$("#location").css( 'display', 'block' );
	//$("#location + div.description").css('display','block');
	//$("#location-element > p.description" ).html( "Enter a suburb, or a postcode to search.." );
	$('#selectedSuburb').remove();
//	$('#selectedSuburb').hide();
	document.getElementById( "location" ).focus();
}

/**
 * Ajax call to check if an email is already in use
 * @param input|form input - The form input to check, usually email. 
 */
function checkEnteredEmail( input )
{
    return;
    // TODO - Phil - change this to be a post. If you think we need it at all..
    // Also, if the e-mail address value is empty it should ignore the call.
    // Disabled - bad idea using get to lookup peoples e-mail addresses
	$.getJSON( '/register/look-up-email/email/' + input.value, function( json ) {
		if( json.id )
		{
			$('#emailCheckerOk').slideUp( 'fast' );
			$('#emailCheckerErrors').slideDown( 'fast' );
		}
		else
		{
			$('#emailCheckerOk').slideDown( 'fast' );
			$('#emailCheckerErrors').slideUp( 'fast' );
		}
	} );
}

/**
 * Simple function to check that the entered emails match
 */
function checkMatchingEmails()
{
	//This is pointless if the above function is not also used.
	return true;

	if( $('#email').val() != '' && $('#email').val() == $('#confirm_email').val() )
	{
		$('#emailCheckerMatchError').slideUp( 'fast' );
		$('#emailCheckerMatchOk').slideDown( 'fast' );
	}
    else if ($('#email').val() == '' || $('#confirm_email').val() == '')
    {
		return false;
    }
	else
	{
		$('#emailCheckerMatchOk').slideUp( 'fast' );
		$('#emailCheckerMatchError').slideDown( 'fast' );
	}
	return true;
}

/**
 * Ajax Submit function for the team search
 */
function findTeamResponse( response, status )
{
	var html = '<div>';
	for( var i = 0 ; i < response.count ; i++ )
	{
		html += '<div class="team_result">'
		html += '<strong>Team:' + response.results[i].name  + '</strong><br />';
		html += 'Captain: '+ response.results[i].firstname + ' ' + response.results[i].lastname;
		html += '</div>';
	}
	html += '</div>';
	$('#findTeamResults').html( html );
}

/**
 * Function to add a value to a team_id hidden variable and then submit the form
 */
function joinTeam( teamID, teamName )
{
	$('#team_id').val( teamID );
	$('#team_name').val( teamName );	
	$('#submitSelectedTeam').trigger("click");
}

/**
 * Checks if a user has entered one of the member countries in the Living Elsewhere form.
 * Asks to redirect to that rego.
 */
function checkCountry( input )
{
	if( input.value == 'au' || input.value == 'nz' || input.value == 'gb' || input.value == 'ie' || input.value == 'us' || input.value == 'ca' )
	{
		if( confirm( 'Do you want to register for your selected country?' ) )
		{
			window.location = '/register' ;
		}
	}
}

function displayGalaParties( input )
{

	if( $(input).is(':checked') )
	{
		$('#gala-parte-your-choice-container').slideDown( 'fast' );
	}
	else
	{
		$('#gala-parte-your-choice-container').slideUp( 'fast' );
		$('#galaparte-details').css('display','none');
	}
}

function displayGalaPartyInfo( input )
{
	$('#galaparte-details').hide();
	$.getJSON( baseUrl + 'register/get-galaparte/id/' + input.value, function( json ) {
		if( json.id )
		{
			$('#galaparte-details').css('display','block');
			$('#galaparte-name').html( json.location );
			$('#galaparte-venue').html( json.venue );
			$('#galaparte-date').html( json.party_date );
			$('#galaparte-start').html( json.start_time );
			$('#galaparte-finish').html( json.end_time );
			$('#galaparte-address').html( json.address );
		}
	} );
}

function displayOtherField( input )
{
	if( input.value == 'other' )
		$('#form_element_venue_type_other').css('display', 'block');
	else
		$('#form_element_venue_type_other').css('display', 'none');
//	$('#venue-type-other-field').remove();
//	if( input.value == 'other' )
//	{
//		$('#form_element_venue_type').after( '<div id="venue-type-other-field"><p class="optional">Please specify</p><input name="other_details" id="venue_other_text" type="text" /></div>' );
//	}
}

if (typeof mov.momoney === 'undefined')
    mov.momoney = {};

mov.momoney.reloadLeaderBoardView = function( baseUrl, type, size, top )
{
    var url = baseUrl + type + '/search_country/' + $('#country_drop').val() + '/search_gender/' + $('#gender_drop').val() + '/search_occupation/' + $('#occupation_drop').val();
    if( size )
        url += '/size/'+size;
    if( top )
        url += '/top/'+top;
    window.location = url;
}

mov.momoney.reloadTeamLeaderBoardView = function( list, baseUrl, top ) 
{
    var url = baseUrl + '/search_country/' + $('#country_drop').val() + '/size/'+ $(list).val();
    if( top )
        url += '/top/'+top;
    window.location = url;
}

mov.momoney.reloadTopMoSpaceView = function( baseUrl, sortBy ) 
{
    var url = baseUrl + '/selected_country/' + $('#countryList').val();
    if ( $('#genderList').val() != '0' ) 
        url += '/gender/' + $('#genderList').val();
    if( sortBy )
        url += '/sort/' + sortBy;
    window.location = url;
}

function loadCountryView( baseUrl, type, input, size, top )
{
	var url = baseUrl + type +'/search_country/' + input.value;
	if( size )
		url += '/size/'+size;
	if( top )
		url += '/top/'+top;
	window.location = url;
}

/**
 * Alternative Ajax Location search info below
 *
 */
function callLocationPredictions()
{
	if( $('#location').val().length > 3 )
		sendPredicitonRequest($('#location').val() );
	else
		$('#searchPredictionResults').css('display','none');
}

function sendPredicitonRequest( value )
{
	$.getJSON( '/register/ajax-get-address-list/q/'+value, function( response ) {
		_div = $('#searchPredictionResults');
		if( response.length > 0 )
		{
			fillSearchPredicitons( _div, response );
		}
	});
}

function fillSearchPredicitons(element, response)
{
	var html = "<ul>";

	for ( var i = 0 ; i < response.length ; i++ )
	{
		displayText = response[i].suburb + ', ' + response[i].postcode + ', ' + response[i].state;

		var startHighlight = displayText.indexOf( $('#location').val() );
		var displayTextLegnth = $('#location').val().length;
		html += '<li><a href="javascript:void(0)" onclick="setLocation( \'' + displayText + '\', \'' + response[i].id + '\' )">';
		//First bit
		html += displayText.substring( 0, startHighlight );
		html += '<b>' + displayText.substring( startHighlight, startHighlight + displayTextLegnth ) + "</b>";
		html += displayText.substring( startHighlight + displayTextLegnth );
		html += '</a></li>';
	}

	html += '</ul>';

	element.html( html );
	element.css('display','block');
	if( response.length > 12 )
		element.css('overflow','scroll');
	else
		element.css('overflow','hidden');

}

function checkIfDonateToSelf()
{
	$.getJSON( sBaseUrl + 'donate/check-donate-to-self/',
	{
		email: $('#email').val()
	},
	function( response ) {
		if (response)
		{
			if ( response.result )
			{
				if (confirm( response.message ))
					document.getElementById('payment_form').submit();
			}
			else
				document.getElementById('payment_form').submit();
		}
		else
			document.getElementById('payment_form').submit();
	});
}

function emailAlert()
{
	if ($P.strpos($('#email').val(),'@sasktel.net'))
		alert(emailWarningMessage);

	return true;
}

function defaultBeforeAjaxSubmitCallback( arr, form, options, submitId )
{
	//add loading image, hide submit button
	$(form).find('#'+submitId).parent().prepend(loadingDiv);
	$(form).find('#'+submitId).hide();
}

function unhideSubmit(formId, submitId)
{
	$('#'+formId + ' .loading').remove();
	$('#'+formId + ' #'+submitId).show();
}

function updateSplitValue(num)
{
	if ($('#allocation-amount-split').length > 0)
	{
		amount = $('#amount').val();
		if ($P.is_numeric(amount))
		{
			$('#allocation-amount-team').text($P.number_format(amount));
			$('#allocation-amount-split').text($P.number_format( amount / num, 2));
		}
	}
}

function toggleCertificateForm()
{
	if ($('#form_element_certificate input:checked').val() == 'no')
	{
		$('#form_element_name').parent().hide();
		$('#fieldset-address_group').parent().hide();
        $('.or').show();
		$('#skipmessage').show();
        $('#formButtons').css('margin-left',0);
	}
	else
	{
		$('#form_element_name').parent().show();
		$('#fieldset-address_group').parent().show();
        $('.or').hide();
		$('#skipmessage').hide();
        $('#formButtons').css('margin-left',161);
	}
}

function updateStateField(country_code, controller)
{
    var postcodeRequired = false;
    if (controller == 'payment')
    {
        if (country_code == 'ca' || country_code == 'us' || country_code == 'gb')
            postcodeRequired = true;
    }
    else if ( country_code == 'ca' || country_code == 'us' || country_code == 'gb' || country_code == 'au' || country_code == 'za' )
        postcodeRequired = true;

	if ( $P.in_array(country_code, countriesWithStates ))
	{
		$('#form_element_stated').show();
		$('#form_element_state').hide();
		updateStateText();
        if (postcodeRequired)
        {
            if ($P.strpos($('#form_element_postcode label').html(),'&nbsp;*') <= 0)
            {
                $('#form_element_postcode label').html($('#form_element_postcode label').html()+'&nbsp;*');
                $( "#form_element_postcode label .sm-js-cmsitem_editable" ).samurize();
            }
        }
        else
        {
            if ($P.strpos($('#form_element_postcode label').html(),'&nbsp;*') > 0)
            {
                $('#form_element_postcode label').html($P.substr($('#form_element_postcode label').html(),0,-7));
                $( "#form_element_postcode label .sm-js-cmsitem_editable" ).samurize();
            }
        }
	}
	else
	{
		$('#form_element_stated').hide();
		$('#form_element_state').show();
		$('#state').val('');

        if ( $P.strpos($('#form_element_postcode label').html(),'&nbsp;*') > 0 && !postcodeRequired )
        {
            $('#form_element_postcode label').html($P.substr($('#form_element_postcode label').html(),0,-7));
            
            $( "#form_element_postcode label .sm-js-cmsitem_editable" ).samurize();
        }
	}

    //ireland suburb not compulsory
    if (country_code == 'ie')
    {
        if ($P.strpos($('#form_element_city label').html(),'&nbsp;*') > 0)
        {
            $('#form_element_city label').html($P.substr($('#form_element_city label').html(),0,-7));
            $( "#form_element_city label .sm-js-cmsitem_editable" ).samurize();
        }

        if ($P.strpos($('#form_element_suburb label').html(),'&nbsp;*') > 0)
        {
            $('#form_element_suburb label').html($P.substr($('#form_element_suburb label').html(),0,-7));
            $( "#form_element_suburb label .sm-js-cmsitem_editable" ).samurize();
        }
    }
    else
    {
        if ($P.strpos($('#form_element_city label').html(),'&nbsp;*') <= 0)
        {
            $('#form_element_city label').html($('#form_element_city label').html()+'&nbsp;*');
            $( "#form_element_city label .sm-js-cmsitem_editable" ).samurize();
        }

        // HACKARAMA: because they want all fields optional on reactivation page, we check that element is not the child of reregister-form -BP
        if ($P.strpos($('#form_element_suburb label').html(),'&nbsp;*') <= 0 && $('#form_element_suburb').parents('#reregister-form').length == 0)
        {
            $('#form_element_suburb label').html($('#form_element_suburb label').html()+'&nbsp;*');
            $( "#form_element_suburb label .sm-js-cmsitem_editable" ).samurize();
        }
    }

}

function updateStateText()
{
    if ($('#stated').val() != '0')
        $('#state').val($('#stated').val());
    else
        $('#state').val('');
}

function Select_Value_Set(SelectId, Value) {
  eval('SelectObject = document.getElementsByName( "' + SelectId + '");');
  for(index = 0; index < SelectObject[0].length; index++)
  {
   if(SelectObject[0][index].value == Value)
     SelectObject[0].selectedIndex = index;
   }
}

function reloadStateField(country_code, secure, controller)
{
    if ( secure != undefined && secure === true )
        bUrl = sBaseUrl;
    else
       bUrl = baseUrl;
    
    if (controller == undefined)
        controller = 'register';

    if (controller == 'receipt' || controller == 'payment' ) {
        var populatedState = $('#state').val();
    }

	updateStateField(country_code,controller)
    if (controller == 'payment')
        controller = 'register';
	if ( $P.in_array(country_code, countriesWithStates ))
	{        
		$('#form_element_stated .form_element_input').append(loadingImage);
		$('#stated').hide();
		$.getJSON(bUrl+controller+'/load-state-by-country',{
			country_code: country_code
		},
		function(jsonObj){
			if (jsonObj.result)
			{
				$('#stated').empty();
				if (!jsonObj.group)
				{
					$.each( jsonObj.states, function(val, text){
						$('#stated').append(                            
							$('<option/>').val(val).html(text)
						);
					});
				}
				else
				{
					var tempOpt = null;
					var tempOptGroup = null;

//					console.log(jsonObj.states);
					$.each( jsonObj.states, function(val, text){
                        if (val != '0')
                        {
                            optgroup = $('<optgroup/>');
                            optgroup.attr('label', val);
                            tempOptGroup = null;
                            $.each( text, function(key, data){
                                tempOpt = $('<option/>').val(key).html(key);
                                tempOptGroup = $(tempOptGroup).add(tempOpt);
                            });

                            $(optgroup).append(tempOptGroup);
                            $('#stated').append(
                                optgroup
                            );
                        }
                        else
                        {                            
                            $('#stated').append(
                                $('<option/>').val('0').html(text)
                            );
                        }
                        
					});
				}

                if (controller == 'receipt' || controller == 'register' ) {
                    Select_Value_Set('stated', populatedState );
                }
                updateStateText();
				$('#form_element_stated .form_element_input img').remove();
				$('#stated').show();
			}
		});
	}
}

function syncPhoneNumber(e)
{
    $('input[name=phone_number]').val(e.value);
    if ($('input[name=phone_number]').length > 1 && val != '')
    {
        if ($(e).parents('#spokesperson_phone').length == 0)
            $('input[name=phone_number]:last').parent().parent().hide();
    }
    else
        $('input[name=phone_number]:last').parent().parent().show();
}

var highlightErrorInputs = function() {
	/* if there are any error, change input box border to red color.
	This can be improved by having input class='error' in markup.
	 */
	$('.form_element_input').each(function(){
		if ( $(this).find('.errors').length > 0 )
			$(this).find('input').css({'border' : 'solid 1px #c00b0f'});
	});
}

function updateAllocation()
{
    if( !numTeamMembers )
        return;
    if ($('#allocation-amount-split').length > 0)
    {
        amount = $('#amount').val();
        if ($P.is_numeric(amount))
        {
            var num = amount / numTeamMembers;
            if (num < 1)
            {
                $('#allocation-team').attr('checked', true);
                $('#allocation-split').parent().hide();
            }
            else
            {
                $('#allocation-split').parent().show();
            }
        }
    }
}

handleEnterKey = function( element ) {
    $(element).keypress(function(event){
        if ( event.keyCode == 13 ) {
            event.preventDefault();
            $(event.currentTarget).parents('form input[type=submit]').trigger('click');
        }
    });
}
