﻿if (typeof(GMI) == 'undefined') {
    var GMI = {};
}

if (typeof (GMI.StarRating == 'undefined')) {
    GMI.StarRating = { CurrentRating: '' };
}

if (typeof (GMI.AjaxConnections == 'undefined')) {
    GMI.AjaxConnections = new Array();
}

GMI.StandardAJAXErrorFunction = function() {
    ModalAlert("There was a problem submitting your request.  Please try to reload the page to try again.");
}

// Note that WCF returns an object that looks like this { d: **actual data** }
// So you access the data like data.d given 'data' is the
// parameter passed to your callback function
GMI.SendXHRToWCF = function(method, json, successCallback, errorCallback) {
    $.ajax({
        url: '/services/RecipeService.svc/' + method,
        cache: false,
        data: json,
        contentType: 'application/json',
        dataType: 'json',
        timeout: 60000, // one minute
        type: 'GET',
        success: successCallback,
        error: errorCallback
    });
}


GMI.SendImageXHRToWCF = function(recipeId, imageCatId, serviceMethod, successCallback, errorCallback) {
    //var xhr = 
    $.ajax({url: '/services/RecipeService.svc/' + serviceMethod + '?recipeID=' + recipeId + '&imageType=' + imageCatId,
        // data: { 'recipeID': recipeId, 'imageType': imageCatId },
        contentType: 'application/json',
        dataType: 'json',
        timeout: 30000, // 30 seconds
        type: 'GET',
        success: successCallback,
        error: errorCallback
    });
    
    //GMI.AjaxConnections[GMI.AjaxConnections.length] = xhr;
}

GMI.LoadImage = function() {
    var imageRef = $(this);
    var recipeId = imageRef.attr('rel').split(':')[0];
    var imageCatId = imageRef.attr('rel').split(':')[1];

    GMI.SendImageXHRToWCF(recipeId,
      imageCatId,
      'GetRecipeImageURL',
      function(data) {
          if (data == null) {
              imageRef.attr('src', '/images/no-recipe-small.jpg');
              return;
          }
          imageRef.attr('src', data.d);
      },
      function() {
        imageRef.attr('src', '/images/no-recipe-small.jpg');
      });
  }

  GMI.LoadImageAndRating = function() {
      var imageRef = $(this);
      var recipeId = imageRef.attr('rel').split(':')[0];
      var imageCatId = imageRef.attr('rel').split(':')[1];

      GMI.SendImageXHRToWCF(recipeId,
    imageCatId,
    'GetRecipeImageAndRatings',
    function(data) {
        if (data == null) {
            imageRef.attr('src', '/images/no-recipe-small.jpg');
            return;
        }

        if (data.d.ThumbRating > 0) {
            if (data.d.ThumbRating == 1)
                imageRef.closest('div.clearcontents').find('.recipe-likeness').addClass('recipe-liked');
            else if (data.d.ThumbRating == 2)
                imageRef.closest('div.clearcontents').find('.recipe-likeness').addClass('recipe-disliked');
        }

        //imageRef.closest('.recipe-tile').find('span.rating-stars').html(data.d.StarRating);
        imageRef.attr('src', data.d.ImageURL);
    },
    function() {
        imageRef.attr('src', '/images/no-recipe-small.jpg');
    });
}


/////// Recipe autocomplete
GMI.RecipeSearchSuggestClose = function() {
    $('ul.search-suggest').hide();
    $('body').unbind('click', GMI.RecipeSearchSuggestClose);
}

GMI.RecipeSearchSuggest = function() {
    $('ul.search-suggest').hide();
    $('body').unbind('click', GMI.RecipeSearchSuggestClose);
    if ($(this).val().length > 2) {
        $('ul.search-suggest').load('/Services/Service.aspx?type=dropdownSearch&count=5&prefixText=' + escape($(this).val()), function() {
            $('ul.search-suggest').show();
        });
        $('body').click(GMI.RecipeSearchSuggestClose);
    }
}

/////// Login prompt
GMI.ResetLoginTimer = function() {
    $('#login-prompt').stop();
    $('#login-prompt').animate({ bottom: '-140px' }, 450, function() { $('#login-prompt').hide(); });
    GMI.StartLoginTimer(60000);
    return false;
}

GMI.RepositionLoginIE6 = function() {
    $('#login-prompt').css({ bottom: '1px' });
    $('#login-prompt').css({ bottom: '0' });
}

GMI.ShowLoginReminder = function() {
    $('#login-prompt').ModalDialog({ title: "Warning! Your work will not be saved", width: 400, height: 175 });
}

GMI.CancelLoginTimer = function() {
    $('body').queue([]);
}

GMI.StartLoginTimer = function(time) {
    $('body').animate({ g: 1 }, time).queue(function() {
        GMI.ShowLoginReminder();
        $(this).dequeue();
    });
}

////// Modal alert
function ModalAlert(message, title) {
    
    if (typeof (title) == 'undefined') {
        title = 'Alert';
    }
    var time = new Date().getMilliseconds();


    $('<div><div class="dialog-content">' + message + '</div><div class="dialog-buttons"><a href="#" class="cancel-button"><img src="/images/buttons/btn-ok.gif" alt="ok" /></a></div></div>').ModalDialog({ id: String(Math.floor(Math.random() * 10000)), 'title': title, height: 200 });
}

////// Date functions

// Date in the format 03-15-10, 3/15/10, 3.15.10,...
// using this since can't get Date.parse() to work with this format
GMI.GetDateFromStandardStringFormat = function(separator, dateString) {
    var dateParts = dateString.split(separator);
    var returnDate = new Date(20 + dateParts[2], dateParts[0] - 1, dateParts[1]);
    return returnDate;
}

GMI.AddDaysToDate = function(numberOfDays, theDate) {
    var dateAsMilliseconds = theDate.getTime();
    dateAsMilliseconds += 86400000 * numberOfDays; // 1000 * 60 * 60 * 24 = 86,400,000 = seconds in a day
    return new Date(dateAsMilliseconds);
}

GMI.GetDateOfCurrentWeekSunday = function() {
    var todaysDate = new Date();
    return GMI.AddDaysToDate(0 - todaysDate.getDay(), todaysDate);
}

GMI.PadWithZeros = function(number, string) {
    if (number > string.length) {
        for (var i = 0; i < number - string.length; i++) {
            string = '0' + string;
        }
        return string;
    } else {
        return string;
    }
}

GMI.GetDateStringFromDate = function(theDate) {
    return GMI.PadWithZeros(2, String(theDate.getMonth() + 1)) + '-' + GMI.PadWithZeros(2, String(theDate.getDate())) + '-' + String(theDate.getFullYear()).substr(2, 2);
}

// Start rating logic
GMI.StarRating.ApplyStarRatingMouseOver = function() {
    var ratingNumber = $(this).attr('class').replace('star', '');
    GMI.StarRating.CurrentRating = $(this).parent().attr('class').replace('star-rating ', '');
    $(this).parent().attr('class', 'star-rating rating-' + ratingNumber);
}

GMI.StarRating.RemoveStarRatingMouseOut = function() {
    $(this).parent().attr('class', 'star-rating ' + GMI.StarRating.CurrentRating);
}

GMI.StarRating.ApplyNewStarRatingClick = function(evt) {
    evt.preventDefault();
    var ratingNumber = $(this).attr('class').replace('star', '');
    var recipeId = $(this).attr('rel');
    var userKey = $('span.uk').text();
    GMI.StarRating.CurrentRating = 'rating-' + ratingNumber;
    GMI.SendXHRToWCF('RateRecipe', { userKey: userKey, recipeId: recipeId, rating: ratingNumber }, function() { }, function() { });
}

GMI.ShowLoginPrompt = function() {
    GMI.CancelLoginTimer();

    if ($(this).hasClass('wizard-login')) {
        $('input.login-redirect-to-plan').val('true');
    }

    $('.secure-login').ModalDialog({ 'title': 'Log In', 'width': 563, 'id': 'SecureLogin', 'attachTo': 'form' });
    $('.secure-login input[type=text]:first').focus();
    return false;
}

GMI.SetRedirectURL = function() {
    $('input.redirect-url').val('/MyPlan/Week.aspx');
}

GMI.ShowPreferencesConfirmation = function() {
    ModalAlert('Your preferences have been saved and will be included in your meal plan calendar going forward.','Confirmation');
    return false;
}

GMI.CheckOrUnCheckAll = function() {
    var isChecked = false;
    var checkedRegex = new RegExp(/uncheck all/i);
    if (!checkedRegex.test($(this).text())) {
        isChecked = true;
    }
    var container = $(this).closest('.preference-box-narrow, .preference-box-full, .wizard-content');
    container.find('input:checkbox').attr('checked', isChecked);

    return false;
}

GMI.ValidRecipeBoxFolder = function(newFolderName, folderListSelector) {
    //10 folders are allowed - there are 2 extra folders for user recipes so 12 folders total
    if ($(folderListSelector).length >= 12) {
        ModalAlert("You are only allowed to add up to 10 folders to your recipe box.");
        return false;
    }

    var exp = new RegExp(/^[0-9a-zA-Z\s]{1,20}$/);
    if (!exp.test(newFolderName)) {
        ModalAlert("Please enter a valid folder name.  The name should only include letters and numbers and have a maximum length of 20 characters.", "Invalid Folder Name");
        return false;
    }

    //duplicate check
    var exists = false;
    $(folderListSelector).each(function() {
        var currentFolder = $(this).text().trim().toLowerCase();

        //trim off the part that shows the recipe count so just have folder name
        var folderEnd = currentFolder.indexOf(' (');
        if (folderEnd > 0)
            currentFolder = currentFolder.substring(0, folderEnd).trim()
        
        if (newFolderName.trim().toLowerCase() == currentFolder)
            exists = true;
    });
    if (exists) {
        ModalAlert("You already have a recipe box folder with the same name.", "Duplicate Folder Name");
        return false;
    }

    return true;
}

GMI.OpenHelpDialog = function(evt) {
    $('#help-dialog').ModalDialog({ title: "Help", width: 700, height: 500 });
    return false;
}

GMI.PreventNavigation = function() {
    if (!GMI.IsLoggedIn) {
        ModalAlert('You must be logged in to access this part of the site.', 'Please login');
        return false;
    }
}

GMI.TrackBuildPlanOptions = function() {
    if ($('.option-choose-recipes input').length > 0) {
        if ($('.option-choose-recipes input').first().attr('checked'))
            trackAction(GMI.BAH.Tracking.BuildPlanChooseForYou);
        else
            trackAction(GMI.BAH.Tracking.BuildPlanSelectOwn);
    }
}

$(document).ready(function() {
    // Recipe search auto suggest init
    $('.autocomplete-searchbox').focus(function() {
        $(this).val('');
    });

    $('img.async').each(GMI.LoadImage);
    $('img.async-rating').each(GMI.LoadImageAndRating);

    $('body').delegate('.checkuncheck a', 'click', GMI.CheckOrUnCheckAll);

    $('a.btn-login').click(GMI.ShowLoginPrompt);
    $('#help-button').click(GMI.OpenHelpDialog);

    $('.autocomplete-searchbox').keyup(GMI.RecipeSearchSuggest);
    $('.star-rating a').hover(GMI.StarRating.ApplyStarRatingMouseOver, GMI.StarRating.RemoveStarRatingMouseOut);
    $('.star-rating a').click(GMI.StarRating.ApplyNewStarRatingClick);

    $('#main-nav ul li:last a').click(GMI.PreventNavigation);
    $('#main-nav ul li:nth-child(3) a').click(GMI.PreventNavigation);
    $('li#tab-menu-shopping a').click(GMI.PreventNavigation);

    $('body').delegate('.btn-next', 'click', GMI.TrackBuildPlanOptions);

});

$(window).load(function() {

    var urlRegex = new RegExp(/MLE=/);
    if (urlRegex.test(window.location.href)) {
        if (window.location.href.replace(/#rld/, '').substr(window.location.href.replace(/#rld/, '').length - 1, 1) != 0) {
            GMI.ShowLoginPrompt();
        }
    }

    var familyCentsRegex = new RegExp(/fc=1/i);
    if (familyCentsRegex.test(window.location.href)) {
        $('#FamilyCentsWelcomeDialog').ModalDialog({ title: 'Welcome, Family-Cents member!',
            height: 220,
            width: 400,
            overlayClass: 'dialog-overlay lighter',
            onClose: function() {
                window.location = window.location.href.replace('?fc=1', '');
            }
        });
    }

    var helpRegexp = new RegExp(/help=1/i);
    if (helpRegexp.test(window.location.href)) {
        GMI.OpenHelpDialog();
    }

});
