var challengeProducts = {};
challengeProducts.currentDay = 0; // passing in zero so back end can derive current day from date

challengeProducts.setup = function() {
    challengeProducts.populateCurrentDay(); // ajax request to obtain current day of promotion
	challengeProducts.handle(); // handle click events on arrows
};

challengeProducts.populateCurrentDay = function() {
    $.getJSON('/my-challenge/builduserlanding/' + challengeProducts.currentDay, function(data) {
        if (data.Hold && data.ReturnCode == 1) {
            challengeProducts.updateCurrentDay(data.Hold); // data.Hold contains currentDay
        }
    });
};

challengeProducts.handle = function() {
    $("#challenge-menu-header a.previous").live('click', function(e) {
        if (!(challengeProducts.currentDay < 2)) { // constrained to not go below day 1
            challengeProducts.currentDay--;
            $('#challenge-daily-selections').css('visibility', 'hidden');
            challengeProducts.loadContent(challengeProducts.currentDay);
        }
        e.preventDefault();
    });
    $("#challenge-menu-header a.next").live('click', function(e) {
        if (!(challengeProducts.currentDay > 13)) { // constrained to not go above day 14
            challengeProducts.currentDay++;
            $('#challenge-daily-selections').css('visibility', 'hidden');
            challengeProducts.loadContent(challengeProducts.currentDay);
        }
        e.preventDefault();
    });
};

challengeProducts.loadContent = function(day) {
    $.getJSON('/my-challenge/builduserlanding/' + day, function(data) {
        $(this).ajaxStart(function() {
            $('#challenge-menu-nav').before('<img id="challenge-loader" class="loader" src="/_res/i/site/ajax-loader.gif" alt="">');
        });
        $(this).ajaxComplete(function() {
            challengeProducts.display(data);
            $('#challenge-loader').remove();
            productDetailModal();
        });
    });
};

challengeProducts.display = function(data) {
    if (data.ResultStr != null && data.ReturnCode == 1 && data.Hold) {
        challengeProducts.updateCurrentDay(data.Hold);
        $('#challenge-daily-selections').html(data.ResultStr);
        $('#challenge-daily-selections').css('visibility', 'visible');
    }
};

challengeProducts.updateCurrentDay = function(day) {
	challengeProducts.currentDay = parseInt(day, 10);
};

$(document).ready(function() {
    // Disable ajax cache
    $.ajaxSetup({ cache: false });

    toggleFacebookLinks();

    // Rotate Touts
    $('#touts').cycle({ fx: 'fade' });

    // Set email variable
    $('#email-form-validate').data('allowSend', false);
    $('#email-buddy-form').data('allowSend', false);

    // Call Modal Functions
    findABuddyModal();
    emailPlanModal();
    thankYouModal();
    printPlanModal();
    printShoppingListModal();

    productDetailModal();

    challengeProducts.setup();

    // Replace Rev Attribute Values on Links in Tips for Success for Google Tracking
    $('#my-challenge #tip-overview-tabs li#fitness-tab a').attr('rev', 'your-plan.fitness.tips.clicked');
    $('#my-challenge #tip-overview-tabs li#lifestyle-tab a').attr('rev', 'your-plan.lifestyle-tips.clicked');
    $('#my-challenge #tip-overview-tabs li#nutrition-tab a').attr('rev', 'your-plan.nutrition-tips.clicked');
    $('#my-challenge #fitness-tips a#fitness-tips-btn').attr('rev', 'your-plan.all-fitness.tips.clicked');

    // Motif switcher
    if ($('.m-wrap').length) {
        var $div = $('.m-wrap');
        var currentMotif = parseInt($div.attr("class").replace("motif-", ""), 10);
        var FIRST = 1;
        var LAST = 4;
        $('#next-motif').click(function(e) {
            e.preventDefault();
            $div.removeClass("motif-" + currentMotif);
            if (currentMotif != LAST) {
                currentMotif++;
            } else {
                currentMotif = FIRST;
            }
            var motifClass = "motif-" + currentMotif;
            $div.addClass(motifClass);
            updateUserMotif(motifClass);
        });
        $('#previous-motif').click(function(e) {
            e.preventDefault();
            $div.removeClass("motif-" + currentMotif);
            if (currentMotif != FIRST) {
                currentMotif--;
            } else {
                currentMotif = LAST;
            }
            var motifClass = "motif-" + currentMotif;
            $div.addClass(motifClass);
            updateUserMotif(motifClass);
        });
    }

    // Print modal windows
    $('button.print-modal').click(function() {
        window.print();
        return false;
    });
    $('.close-product-modal').click(function(e) {
        e.preventDefault();

        $('#product-recipe-modal').dialog('close');
    });

    $('#product-recipe-modal').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'product-recipe-modal-popup'
    }).parents(".ui-dialog:first").find(".ui-dialog-titlebar").hide();
});

function updateUserMotif(className){
	//#challenge-logged-in
	//#challenge-countdown
	var endpoint = "user/preferences/%STATE%/%CLASS%";
	var state = "mycountdownchallenge";
	if($('#challenge-logged-in').length) state = "myactivechallenge";
	var parsedEndpoint = endpoint.replace("%STATE%", state).replace("%CLASS%", className);
	$.ajax({
	  url: parsedEndpoint,
	  success: function(data){
		// doing nothing
		}
	});
}

function getMyCalendarState()
{
    //Get the client machine's date to be used for the calendar state ajax call
    var localTime = new Date();
    var year= localTime.getFullYear();
    var month= localTime.getMonth() +1;
    var date = localTime.getDate();
    
    var dateParam = year+"-"+month+"-"+date;
    
    $.getJSON('/my-challenge/getCalendarState/' + dateParam + '', displayCalendarState);     
                  
}

function setCalendarDate()
{
    //Get the client machine's date to be used for the calendar state ajax call
    var localTime = new Date();
    var year= localTime.getFullYear();
    var month= localTime.getMonth() +1;
    var date = localTime.getDate();
    
    var dateParam = year+"-"+month+"-"+date;
    
    $.getJSON('/my-challenge/setCalendarDate/' + dateParam + '', function(){});                    
}

function displayCalendarState(data)
{
    if(data.Result.ResultStr != null && data.Result.ReturnCode == 1)
    {
        $('#calendar').html(data.Result.ResultStr);
     	
        calendarScroll();
        savePlan();
        
        $('.slideshow').cycle({ fx: 'fade' });
    }
}

function calendarScroll(){
	
	var calDates = $('.populated-plan');
	var totalCount = calDates.length;
	var currentPosition = 0;
	
	calDates.each(function(i)
	{
	    if(this.style.display == 'block')
	    {
	        currentPosition = i + 1;
	        
	        if(currentPosition == 1)
			{
				$('#prev-day').css({ display: 'none' });
			}
	    }
	});
	
	$('#prev-day').bind("click", function(e){
		e.preventDefault();
		
		if(currentPosition > 0)
		{
			currentPosition --;
			$('#prev-day').css({ display: 'block' });
			$('#next-day').css({ display: 'block' });
		}
		
		if(currentPosition == 1)
		{
			$('#prev-day').css({ display: 'none' });
		}
		
		$('.populated-plan').hide();
		$('.populated-plan:nth-child(' + currentPosition + ')').show();
	});
	
	$('#next-day').bind("click", function(e){
		e.preventDefault();
		
		if(currentPosition < totalCount)
		{
			currentPosition ++;
			$('#prev-day').css({ display: 'block' });
			$('#next-day').css({ display: 'block' });
		}
		
		if(currentPosition == totalCount)
		{
			$('#next-day').css({ display: 'none' });
		}
		
		$('.populated-plan').hide();
		$('.populated-plan:nth-child(' + currentPosition + ')').show();
	});	
}

function toggleFacebookLinks()
{
	$('#toggle-fans-btn').click(function(e)
	{
		e.preventDefault();
		
		$('#fb-frame-1').hide();
		$('#fb-frame-2').show();
	});
	
	$('#toggle-community-btn').click(function(e)
	{
		e.preventDefault();
		
		$('#fb-frame-2').hide();
		$('#fb-frame-1').show();
	});
}

function savePlan()
{
	$('#btn-notsaved').click(function(e)
	{
		e.preventDefault();
		
		$.getJSON('/Challenge/SaveCalendar', function(data)
		{
			var returnObject = data;
			
			// If a user is not logged in, show the login page
			if(returnObject.Result['ReturnCode'] == 12)
			{
				window.location = '/register/my-challenge/';
			}
			// If a user is already logged in
			else if(returnObject.Result['ReturnCode'] == 1)
			{
				window.location.reload(true);
			}
		});
	});
}

// Modal for allowing users to share their calendar
// by email or by facebook
function findABuddyModal()
{
	// Find A Buddy Modal
	$('#find-buddy-modal').dialog({
        autoOpen: false,
        close: function(event, ui)
        {
	    	$('#find-buddy-modal .validation .error p').hide();
	    	$('#email-buddy-form div.submit a').remove();
	    	$('#submit-buddy-form-btn').show();
	    	$('#email-buddy-form label.error').remove();
	    	$('#email-buddy-form input.error').removeClass('error');
        },
		modal: true,
        dialogClass: 'buddy-modal-popup'
    });
    
    // Facebook Buddy Modal
    $('#facebook-buddy-modal').dialog({
    	autoOpen: false,
    	close: function()
    	{
    		$('#invitations-have-sent').hide();
    		$('#send-facebook-invites-btn').show();
    	},
    	dialogClass: 'facebook-buddy-modal',
    	height: 512,
    	modal: true,
    	width: 404
    });
    
    // Invite a Buddy Thank You Modal
    $('#close-buddy-thank-you-modal').click(function(e)
    {
        e.preventDefault();
        
        $('#find-a-buddy-thank-you').dialog('close');
    });
    
    $('#find-a-buddy-thank-you').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'modal-popup png-fix'
    });
	
	// Listening to click event on invite a friend buddy
	$('#invite-friend-btn, #invite-a-friend-btn').click(function(e)
	{
		e.preventDefault();
		
		// Reset buddy modal back to welcome page
		$('#find-buddy-modal .email-form').hide();
		$('#find-buddy-modal .welcome').show();
		
		// Open the find a buddy modal
		$('#find-buddy-modal').dialog('open');
	});
	
	$('#facebook-search-form').submit(function()
	{
		var searchTerm = $('#facebook-search-input').val();
		
		SearchCurrentUsersFriends(searchTerm);
		
		return false;
	});
	
	$('#send-facebook-invites-btn').click(function(e)
	{
		e.preventDefault();
		
		SetInvitedFriends();
	});
	
	$('#send-invite-btn').click(function(e)
	{
		e.preventDefault();
		
		// Hide welcome screen and show email form
		$('#find-buddy-modal .welcome').hide();
		$('#find-buddy-modal .email-form').show();
	});
    
    // Attaching valifation to find buddy form
    $('#email-buddy-form').validate({
    	rules: {
    		yourNameInput: { required: true },
    		yourEmailInput: {
    			required: true,
    			email: true
    		},
    		yourFriendNameInput1: { required: true },
    		yourFriendEmailInput1: {
    			required: true,
    			email: true
    		}
    	},
    	messages : {
    		yourNameInput: { required: false },
    		yourEmailInput: {
    			required: false,
    			email: false
    		},
    		yourFriendNameInput1: { required: false },
    		yourFriendEmailInput1: {
    			required: false,
    			email: false
    		}
    	},
    	submitHandler: function(form)
    	{
    		$('#email-buddy-form').data('allowSend', true);
    	}
    });
    
    // Preventing form from refreshing the page
    $('#email-buddy-form').submit(function()
    {
    	if($('#email-buddy-form').data('allowSend') == true)
    	{
    		// Creating email object
    		emailObj = {};
    		
    		emailObj.yourName = $('#email-buddy-form input[name="yourNameInput"]').val();
    		emailObj.yourEmail = $('#email-buddy-form input[name="yourEmailInput"]').val();
    		emailObj.friendsNames = $('#email-buddy-form input[name="yourFriendNameInput1"]').val();
    		emailObj.friendsEmails = $('#email-buddy-form input[name="yourFriendEmailInput1"]').val();
    		emailObj.yourMessage = '';
    		
    		// Start validation on other buddy fields before sending off
    		var friendName2 = $.trim($('#yourFriendNameInput2').val());
    		var friendEmail2 = $.trim($('#yourFriendEmailInput2').val());
    		var friendName3 = $.trim($('#yourFriendNameInput3').val());
    		var friendEmail3 = $.trim($('#yourFriendEmailInput3').val());
    		var friendName4 = $.trim($('#yourFriendNameInput4').val());
    		var friendEmail4 = $.trim($('#yourFriendEmailInput4').val());
    		var allowSend = false;
    		
    		// Create regular expression for testing emails
    		var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
			var regex = new RegExp(emailReg);
    		
    		if(friendName2 != '')
    		{
    			if(!regex.test(friendEmail2))
    			{
    				$('#yourFriendEmailInput2').addClass('error').blur(function()
    				{
    					if(regex.test($(this).val()))
    					{
    						$(this).removeClass('error');
    						
    						emailObj.friendsNames += friendName2 + ',';
    						emailObj.friendsEmails += friendEmail2 + ',';
    					}
    				});
    				
    				return false;
    			}
    		}
    		
    		if(friendName3 != '')
    		{
    			if(!regex.test(friendEmail3))
    			{
    				$('#yourFriendEmailInput3').addClass('error').blur(function()
    				{
    					if(regex.test($(this).val()))
    					{
    						$(this).removeClass('error');
    						
    						emailObj.friendsNames += friendName3 + ',';
    						emailObj.friendsEmails += friendEmail3 + ',';
    					}
    				});
    				
    				return false;
    			}
    		}
    		
    		if(friendName4 != '')
    		{
    			if(!regex.test(friendEmail4))
    			{
    				$('#yourFriendEmailInput4').addClass('error').blur(function()
    				{
    					if(regex.test($(this).val()))
    					{
    						$(this).removeClass('error');
    						
    						emailObj.friendsNames += friendName4 + ',';
    						emailObj.friendsEmails += friendEmail4 + ',';
    					}
    				});
    				
    				return false;
    			}
    		}
    		
    		// Building email object to send off
    	    var email = new Array(emailObj.yourEmail, emailObj.yourName, emailObj.friendsEmails, emailObj.friendsNames, emailObj.yourMessage);
    	    email = $.toJSON(email);
    	    
    	    // Send email to backend for inviting friends
    	    $.ajax({
	                url: '/my-challenge/invite-a-friend/',
	                type: 'POST',
	                data: email,
	                dataType: 'JSON',
	                contentType: "application/json; charset=utf-8",
	                beforeSend: function(){
	                	$('#email-buddy-form').data('allowSend', false);
	                },
	                success: function(data)
	                {
	                	var returnObject = $.evalJSON(data);
	                	
	            	    // Double checking to make sure everything went through
	            	    if(returnObject.Result['ReturnCode'] == 0)
	            	    {
	            	    	// Clear out object and form
	            	    	$('#email-buddy-form input').val('');
	            	    	emailObj.yourName = '';
	    					emailObj.yourEmail = '';
	    					emailObj.yourMessage = '';
	    					emailObj.friendsNames = '';
	    					emailObj.friendsEmails = '';
	    					
	    					// Hide send button and replace with my challenge link
				    		$('#find-buddy-modal').dialog('close');
				    		
				    		// Show thank you modal
				    		$('#find-a-buddy-thank-you').dialog('open');
	            	    }
	            	    else
	            	    {
	            	    	$('#find-buddy-modal .validation .error p').show();
	            	    }
	                }
	        	});
    	}
    	
    	return false;
    });
}

// Handles when a user clicks the email my plan button
function emailPlanModal()
{
	$('#email-my-plan-btn').click(function(e)
    {
        e.preventDefault();
        $('#email-my-plan-form').dialog('open');
    });
        
    // Listening to when the email form is submitted
    $('#email-form-validate').submit(function() {
        var emailObj = {};
        var error = false;

        emailObj.yourEmail = $(this).find('input[name=youremail]').val();
        emailObj.friendsEmails = jQuery.trim($(this).find('input[name=friendsemail]').val()).replace(/ /g,"");

        // Validate emails
        $(".formError").remove();
        if(emailObj.friendsEmails != ""){
            var friends = emailObj.friendsEmails.split(",");
            $(friends).each(function(i,f){
                if(f.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) == null && f != ""){
                    error = true;
                }
            });
            if(error == true){
                $(this).find('input[name=friendsemail]').css("border-color","#ff0000").parent().append("<div class=\"formError\">Please enter one or more valid emails seperated by commas.</div>");
            } else {
                $(this).find('input[name=friendsemail]').css("border-color","");
            }
        } else {
            $(this).find('input[name=friendsemail]').css("border-color","");
        }
        if(emailObj.yourEmail.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) == null){
            $(this).find('input[name=youremail]').css("border-color","#ff0000").parent().append("<div class=\"formError\">Please enter a valid email address.</div>");;
            error = true;
        } else {
            $(this).find('input[name=youremail]').css("border-color","");
        }
        if(error == true){
            return false;
        }

        emailObj.yourName = jQuery.trim($(this).find('input[name=yourname]').val());
        emailObj.yourMessage = jQuery.trim($(this).find('textarea[name=yourmessage]').val());

        /*if (emailObj.friendsEmails == '') {
            emailObj.friendsEmails = 'Your Friend';
        }*/ //edited out on 8.12.10 due to backend issues

        // Building email object to send off
        var email = new Array(emailObj.yourEmail, emailObj.friendsEmails, emailObj.yourName, emailObj.yourMessage);
        email = $.toJSON(email);

        // Sending email object to backend for emailing
        $.ajax({
            url: '/Challenge/EmailMyPlan',
            type: 'POST',
            data: email,
            dataType: 'JSON',
            contentType: "application/json; charset=utf-8",
            // Preventing users from triggering the email event until finished
            beforeSend: function() {
                $('#email-form-validate').data('allowSend', false);
            },
            // After email object has been sent successfully
            success: function(data) {
                var returnObject = $.evalJSON(data);

                // Double checking to make sure everything went through
                if (returnObject.Result['ReturnCode'] == 1) {
                    $('#email-form-validate').find('input[name=youremail]').val('');
                    $('#email-form-validate').find('input[name=friendsemail]').val('');
                    $('#email-form-validate').find('input[name=yourname]').val('');
                    $('#email-form-validate').find('textarea[name=yourmessage]').val('');

                    $('#email-my-plan-form').dialog('close');
                    $('#email-thank-you').dialog('open');

                    $('#email-form-validate').data('allowSend', true);
                }
                else {
                    //handle error
                    $("#email-your-plan").after("<div style=\"font-size: 13px; margin-bottom: 10px;\" class=\"formError\">An error has occured while submitted your request. Please try again.</div>");
                }
            }
        });

        // Preventing the form from refreshing the page
        return false;
    });
    
    $('#email-my-plan-form').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'contact-modal-popup png-fix'
    });
    
    // Show character count for email modal
    $('#email-plan-textarea').limit('400','#email-plan-textarea-counter');
}

// Modal for when a user has emailed their plan
function thankYouModal()
{
	// Email Thank You Modal
	$('#close-thank-you-modal').click(function(e)
    {
        e.preventDefault();
        
        $('#email-thank-you').dialog('close');
    });
    
    $('#email-more-friends').click(function(e)
    {
        e.preventDefault();
        
        $('#email-thank-you').dialog('close');
        $('#email-my-plan-form').dialog('open');
        
    });
    
    $('#email-thank-you').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'modal-popup png-fix'
    });
    
    // Invite a Buddy Thank You Modal
    $('#close-buddy-thank-you-modal').click(function(e)
    {
        e.preventDefault();
        
        $('#find-a-buddy-thank-you').dialog('close');
    });
    
    $('#find-a-buddy-thank-you').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'modal-popup png-fix'
    });
}

// Modal for printing user plan
function printPlanModal()
{
	$('#print-my-plan-btn').click(function(e)
    {
        e.preventDefault();
        $('#print-my-plan-modal').dialog('open');
    });

    $('#print-my-plan-modal').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'print-modal-popup png-fix'
    });

	$('#print-my-plan-wrapper').load('/Challenge/PrintChallenge/');
}

// Modal for printing shopping list
function printShoppingListModal()
{
	$('#shopping-list-btn').click(function(e)
    {
        e.preventDefault();
        $('#print-shopping-list-modal').dialog('open');
    });

    $('#print-shopping-list-modal').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'print-modal-popup png-fix'
    });

	$('#print-shopping-list-modal #shopping-list-content').load('/my-challenge/shopping-list/');
}

// When a user clicks on a product or recipe
// in the calendar. Returns HTML to populate
// overlay modal
function getOverlayProduct(id, type) {
    $.getJSON('/Products/GetProductItemOverLay/' + id + '/' + type, populateProductRecipeOverlay);
}

// Uses return object from getOverlayProduct and
// populates modal with returned HTML
function populateProductRecipeOverlay(data) {
    $('#product-recipe-modal').children('.content').children('.grid').html(data.ResultStr);

    var pTipContent = $('#product-recipe-modal').find('#protein-disclosure').html();

    // Rebind simpletip to dynamic content
    $('#product-recipe-modal').find('.p-disclosure').simpletip({
        content: pTipContent,
        position: [231, 255]
    });

    $('#product-recipe-modal').dialog('open');
}
function productDetailModal() {

    $('.product-overlay-link').click(function(e) {
        e.preventDefault();

        var productObj = {};
        var product = $(this).attr('rev');

        product = product.split(',');

        productObj.id = parseInt(product[0]);
        productObj.type = parseInt(product[1]);

        getOverlayProduct(productObj.id, productObj.type);
    });
}
