var end4HungerActions = {
    logAction: function(actionId) {
        jQuery.post('/wp-content/themes/end4hunger/lib/logAction.php', {actionId: actionId}, function(data) {}, 'json');
    },
    
    updateActions: function() {
        jQuery('#actions_number').load('/wp-content/themes/end4hunger/lib/getActions.php', '', function(responseText, textStatus, XMLHttpRequest) {
            // Get the current count of actions.
            var currentCount = jQuery('#actions_number').text();
            currentCount = currentCount.replace(/,/g, '');
            
            // Get the number of actions taken and convert it to a percent.
            var actionsCount = ((currentCount/20000) * 100);
            
            // Update the progress bar.
            jQuery('#scale_progress_percent').animate({width: actionsCount+'%'}, 1000); 
        });
    },
    
    actionSlide: function(index) {
        switch(index) {
            case 1:
                jQuery('.sections #action_join').animate({left: '45px'}, 550);
                break;
            
            case 2:
                jQuery('.sections #action_share').animate({left: '90px'}, 550);
                break;
            
            case 3:
                jQuery('.sections #action_tweet').animate({left: '135px'}, 550);
                break;
            
            case 4:
                jQuery('.sections #action_ecard').animate({left: '180px'}, 550);
                break;
        }
    }
};


jQuery(document).ready(function() {
    // Setup Accordion
    jQuery('.sections').hAccordion();    
    
    // Load the nuber of actions taken.
    end4HungerActions.updateActions();
    
    /** Email Signup Action **/
    jQuery('#email_signup_form').submit(function(e) {
        // Prevent default action.
		e.preventDefault();
        
        // Validate the name.
        if(jQuery('#email_signup_name').val() == '') {
            alert('Please enter your name.');
            jQuery('#email_signup_name').focus();
            return false;
        }
        
        // Validate the email.
        if((jQuery('#email_signup_email').val() == '') || (!validEmail(jQuery('#email_signup_email').val()))) {
            alert('You\'ve entered and invalid Email.');
            jQuery('#email_signup_email').focus();
            return false;
        }
        
        // Disable the submit button.
        jQuery('#email_signup_submit').attr('disabled', 'disabled');
        
        // Display the AJAX Loader.
        jQuery('#ajax_indicator').css('height', '16px');
        
        // Post the data via AJAX
        jQuery.post(jQuery(this).attr('action'), {
                name: jQuery('#email_signup_name').val(),
                email: jQuery('#email_signup_email').val()
            },
            
			function(data) {
				if(data.added) {
				    jQuery('#ajax_indicator').css('height', '0px');
				    end4HungerActions.logAction(1);
				    end4HungerActions.actionSlide(2);
				}
				else {
				    jQuery('#ajax_indicator').css('height', '0px');
                    jQuery('#email_signup_submit').attr('disabled', '');
				    jQuery('#action_join_message').html('We could not sign you up at this time! Please continue with completing the steps to help End World Hunger. Thanks!');
				}
			},
			
			'json'
		);    
    });
    
    
    /** E-card Form Submission **/
    jQuery('#ecard_send_form').submit(function(e) {
        // Validate the name.
        if(jQuery('#your_name').val() == '') {
            alert('Please enter your name.');
            jQuery('#your_name').addClass('required_field');
            jQuery('#your_name').focus();
            return false;
        }
        
        // Validate the email.
        if((jQuery('#your_email').val() == '') || (!validEmail(jQuery('#your_email').val()))) {
            alert('You\'ve entered and invalid Email.');
            jQuery('#your_email').addClass('required_field');
            jQuery('#your_email').focus();
            return false;
        }
        
        // Validate the recipient's name.
        if(jQuery('#email_recipient_name_1').val() == '') {
            alert('Please enter the recipient\'s name.');
            jQuery('#email_recipient_name_1').addClass('required_field');
            jQuery('#email_recipient_name_1').focus();
            return false;
        }
        
        // Validate the email.
        if((jQuery('#email_recipient_email_1').val() == '') || (!validEmail(jQuery('#email_recipient_email_1').val()))) {
            alert('You\'ve entered and invalid Email for your recipient.');
            jQuery('#email_recipient_email_1').addClass('required_field');
            jQuery('#email_recipient_email_1').focus();
            return false;
        }
        
        // Loop through all of the recipient fields and check for errors.
//        for(i=2; i<=5; i++) {
//            if(jQuery('#email_recipient_name_'+i).val() != '' && jQuery('#email_recipient_email_'+i).val() != '') {
//                if((jQuery('#email_recipient_name_'+i).val() != '' && jQuery('#email_recipient_email_'+i).val() == '') || (jQuery('#email_recipient_name_'+i).val() == '' && jQuery('#email_recipient_email_'+i).val() != '') || (!validEmail(jQuery('#email_recipient_email_'+i).val()))) {    
//                    jQuery('#ecard_send_form .set_'+i).addClass('required_field');
//                    return false;
//                }
//                else {
//                    jQuery('#ecard_send_form .set_'+i).removeClass('required_field');
//                }       
//            }
//        }
        
        // Disable the submit button.
        jQuery('#email_signup_submit').attr('disabled', 'disabled');
        return true;    
    });
    
    /** Check to see if the required field has changed with some content **/
    jQuery('#ecard_send_form .input_field').keyup(function() {
        if(jQuery(this).hasClass('required_field') && jQuery(this).val() != '') {
            jQuery(this).removeClass('required_field');
        }
    });
    
    /** Facebook Share Action **/
    jQuery('#share_facebook_action').click(function() {
        end4HungerActions.logAction(2);
        
        var url = 'http://www.end4hunger.org/index.php';
        var message = 'This year alone, nearly 9 million children will die needlessly from hunger-related causes. Please "Share" this so we can raise awareness and be a voice for change.  Then visit www.end4hunger.org to join me!  It only takes four minutes to help save lives!';
        
        newWindow('http://www.facebook.com/sharer.php?u='+url+'&t='+message, 'facebook_sharer', 800, 400, '');
        end4HungerActions.actionSlide(3);
    });
    
    
    /** Twitter Share Action **/
    jQuery('#tweet_action').click(function() {
        end4HungerActions.logAction(3);
        
        var message = 'text=A child dies from hunger every 6 seconds. Visit our website and take action to help end world hunger Pls RT!';
        var url = 'url=http://www.end4hunger.org';

        newWindow('http://twitter.com/intent/tweet?'+message+'&'+url, 'twitter_sharer', 800, 400, '');
        end4HungerActions.actionSlide(4);
    });
    
    // Next buttons
    jQuery('.sections #action_why .content .next_slide a').click(function() {
        end4HungerActions.actionSlide(1);
    });
    
    jQuery('.sections #action_join .content .next_slide a').click(function() {
        end4HungerActions.actionSlide(2);
    });
    
    jQuery('.sections #action_share .content .next_slide a').click(function() {
        end4HungerActions.actionSlide(3);
    });
    
    jQuery('.sections #action_tweet .content .next_slide a').click(function() {
        end4HungerActions.actionSlide(4);
    });
    
    // Tooltip for Facebook Share button
    //jQuery('#share_facebook_action').qtip({
//        content: 'This year alone, over five million children will die needlessly from hunger-related causes. Please "Share" this so we can raise awareness and be a voice for change.  Then visit www.end4hunger.org to join me!  It only takes four minutes to help save lives!',
//        style: { 
//            padding: 10,
//            border: {
//                width: 2,
//                radius: 8
//            },
//            tip: 'topLeft',
//            width: 200,
//            name: 'light'
//        }
//    });
    
    // Tooltip for Twitter Share button
    //jQuery('#tweet_action').qtip({
//        content: 'A child dies from hunger every 6 seconds. Visit http://www.end4hunger.org and take action to help end world hunger. #endhunger Please RT!',
//        style: { 
//            padding: 10,
//            border: {
//                width: 2,
//                radius: 8
//            },
//            tip: 'topLeft',
//            width: 200,
//            name: 'light'
//        }
//    });
    
    // Change the selected ecard when clicked
    jQuery('#ecard_wrapper [name="ecard_choices"]').click(function() {
        var element = jQuery('#ecard_wrapper [name="ecard_choices"]:checked').attr('id');
        jQuery('#ecard_wrapper .ecard_container').css('background-color', '#000000');
        jQuery('#'+element+'_container').css('background-color', '#F26522');
    });
    
    // Load the number of actions taken every 10 seconds.
    var refreshId = setInterval(end4HungerActions.updateActions, 10000);
});


// Validates email address of course.
function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search (filter) != -1;
}

// Opens a new window as one would expect.
function newWindow(url, title, width, height, scroll) {
    var left = (screen.width/2)-(width/2);
    var top = (screen.height/2)-(height/2);
    
    if(scroll == '') {
        scroll = 'yes';
    }
    var targetWin = window.open (url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars='+scroll+', resizable=yes, copyhistory=no, width='+width+', height='+height+', top='+top+', left='+left);
} 
