﻿var photoPath;
var photoFileName;
var photoDetailX;
var photoDetailY;
var photoWidth;
var photoHeight;
var fullSizePhotoWidth;
var fullSizePhotoHeight;
var uploader;

recipeDetailTabs = function() {
	$("ul#cookbook-tabs li").click(function() {
		var tab = ($(this).attr('id')).replace("tab-", "");
		//switch active tab
		$("ul#cookbook-tabs li a").removeClass("active");
		$("ul#cookbook-tabs li#tab-" + tab + " a").addClass("active");
		//switch active content
		$(".cookbook-tab-content").hide();
		$("#tab-content-" + tab).show();
		$("#tab-content-video").css("visibility", "");
		Cufon.refresh();
	});
};

enableMainIngredientDropdown = function() {
	$('td.main-ingredient input:checkbox').live("click", function() {
		if (!$(this).closest('tr').hasClass('example')) {
			if ($(this).attr('checked')) {
				$(this).closest('tr').find('td.ingredient-type select').attr('disabled', false);
			} else {
				$(this).closest('tr').find('td.ingredient-type select').attr('disabled', true).val("");
			}
		}
	});
};

var formattedTime;

formatRecipeTime = function(minutes) {
	var totalTimeInMinutes = parseInt(minutes);
	var totalHours = Math.floor(totalTimeInMinutes / 60);
	var totalMins = totalTimeInMinutes - (totalHours * 60);
	var formattedTime;
	if (totalHours == 0) {
		formattedTime = totalMins + " min";
	} else {
		if (totalMins == 0) {
			formattedTime = totalHours + " hr ";
		} else {
			formattedTime = totalHours + " hr " + totalMins + " min";
		}
	}
	return formattedTime;
}

populatePreview = function() {
    var jsonString = (JSON.stringify($('#recipeSubmitForm').serializeObject()));
    var jsonObj = $.parseJSON(jsonString);

    var descriptionText = jsonObj['Description'].replace(/\r\n/g, '<br />');
    var notesText = jsonObj['PrepNotes'].replace(/\r\n/g, '<br />');

    $('.recipe-header-content h3').html(jsonObj['Title']);
    $('.recipe-header-content p.description span.preview').html(descriptionText);
    $('.recipe-header-content li#prep-time span.preview').html(formatRecipeTime(jsonObj['PrepTime']));
    $('.recipe-header-content li#cook-time span.preview').html(formatRecipeTime(jsonObj['CookingTime']));
    $('.recipe-header-content li#total-time span.preview').html(formatRecipeTime(parseInt(jsonObj['PrepTime']) + parseInt(jsonObj['CookingTime'])));
    $('.recipe-header-content li#servings span.preview').html(jsonObj['Servings']);
    $('#tab-content-recipe #description .text').html(descriptionText);
    $('#sidebar #abstract p#course').html(jsonObj['Course']);

    var tags = "";
    if ($.isArray(jsonObj['Tags'])) {
        for (var i in jsonObj['Tags']) {
            if (String(jsonObj['Tags'][i]).indexOf("function") == -1) {
                tags = tags + jsonObj['Tags'][i] + ", ";
            }
        }
        tags = tags.substring(0, tags.length - 2);
    } else {
        tags = jsonObj['Tags'];
    }
    $('#sidebar #abstract p#tags').html(tags);

    var totalIngredientsAddedToList = 0;
    if (jsonObj['Ingredients.Index'] != undefined) {
        var totalIngredients = jsonObj['Ingredients.Index'].length;
    } else {
        var totalIngredients = 0;
    }
    var ingredientListItems = "";
    var mainIngredientArray = new Array();
    var mainIngredientArrayIndexCounter = 0;
    var mainIngredientList = "";
    for (i = 0; totalIngredientsAddedToList <= totalIngredients; i++) {
        if (jsonObj['Ingredients[' + i + '].Amount']) {
            if (i == 0) { //if required jif product ingredient
                ingredientListItems = ingredientListItems + "<li>" + jsonObj['Ingredients[0].Amount'] + " " + jsonObj['Ingredients[0].Units'] + " " + $('#Ingredients_0__Ingredient option:selected').text() + "</li>";
            } else { //if ingredient other than the required jif product ingredient
                ingredientListItems = ingredientListItems + "<li>" + jsonObj['Ingredients[' + i + '].Amount'] + " " + jsonObj['Ingredients[' + i + '].Units'] + " " + jsonObj['Ingredients[' + i + '].Name'] + "</li>";

                if ((jsonObj['Ingredients[' + i + '].MainIngredientType']) && (jsonObj['Ingredients[' + i + '].MainIngredientType'] != 'Select')) { //if valid main ingredient selection exists
                    mainIngredientArray[mainIngredientArrayIndexCounter] = jsonObj['Ingredients[' + i + '].MainIngredientType'];
                    mainIngredientArrayIndexCounter++;
                }
            }
            totalIngredientsAddedToList++;
        }
    }
    //create string of main ingredients, without dups, for the Main Ingredients abstract box
    for (var i = 0; i < mainIngredientArray.length; i++) {
        if (!(mainIngredientList.indexOf(mainIngredientArray[i]) != -1)) {
            if (mainIngredientList != "") { mainIngredientList = mainIngredientList + ", "; }
            mainIngredientList = mainIngredientList + mainIngredientArray[i];
        }
    }
    $('#tab-content-recipe #ingredients .text ul').html(ingredientListItems);
    if (mainIngredientList == "") {
        $('#sidebar #abstract h6#main-ingredients-header').hide();
        $('#sidebar #abstract p#main-ingredients').hide();
    } else {
        $('#sidebar #abstract h6#main-ingredients-header').show();
        $('#sidebar #abstract p#main-ingredients').show().html(mainIngredientList);
    }

    var totalStepsAddedToList = 0;
    var totalPrepSteps = jsonObj['Instructions.Index'].length;
    var prepStepListItems = "";
    for (i = 0; totalStepsAddedToList < totalPrepSteps; i++) {
        if (jsonObj['Instructions[' + i + '].Description']) {
            prepStepListItems = prepStepListItems + "<li>" + jsonObj['Instructions[' + i + '].Description'].replace(/\r\n/g, '<br />') + "</li>";
            totalStepsAddedToList++;
        }
    }
    $('#tab-content-recipe #instructions .text ol').html(prepStepListItems);

    if ((jsonObj['PrepNotes']) != "") {
        $('#notes-content').html(notesText);
    }

    var recipePhoto = $('#recipe-preview-modal #recipe-detail-content .recipe-header #photo-wrapper img');
    var photoData = $('#photo-upload').data('preview');
    if (photoPath) {
        recipePhoto.attr('src', photoPath);
        recipePhoto.css({ 'top': photoData.top + 'px', 'left': photoData.left + 'px', 'width': photoData.width + 'px' });
    }

    if ($('#VideoKey').val().length > 0) {
        $('ul#cookbook-tabs li#tab-video').show();
        $('#recipe-preview-modal #recipe-detail-content #tab-content-video').css("visibility", "");
    } else {
        $('ul#cookbook-tabs li#tab-video').hide();
        $('#tab-content-video').hide();
    }
}

$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

$(document).ready(function () {

	//Prevent enter key from submitting recipe form prematurely
	$('#recipeSubmitForm input').keydown(function (e) {
		if (e.keyCode == 13) {
			e.preventDefault();
			return false;
		}
	});

	$('#tab-content-video').css("visibility", "hidden");

	// Add VideoJS to all video tags on the page when the DOM is ready

	try {
		VideoJS.setupAllWhenReady();
	} catch (e) { }

	recipeDetailTabs();

	enableMainIngredientDropdown(); /* Change ingredient type's select box disable state and value based on whether or not 'Main Ingredient' checkbox is selected */

	//Data for autocomplete
	var source = "/SocialCookbook/IngredientAutoComplete"

	//Adding autocomplete to ingredient input
	$("td.ingredient input").autocomplete(source, {
		//Minimum number of characters a user has to type before the autocompleter activates
		minChars: 0,
		//The number of items in the select box
		max: 10,
		//Fill the input while still selecting a value
		autoFill: true,
		//Only suggested values are valid
		mustMatch: false,
		//The comparison doesn't looks inside
		matchContains: false
	});

	/* Show Photo Upload Modal Window */
	$('a#photo-upload-button').click(function () {
		$('#photo-upload-modal').jqm({ modal: true }).jqmShow();
		$('html, body').animate({ scrollTop: 0 }, 200);
		return false
	});

	/* Submit Photo Upload Modal Window */
	$('#photo-upload-modal a.submit-button').click(function () {
		$('#Photo').val(photoFileName);

		var jcropPreviewBoxWidth = $('.jcrop-holder').width();
		var jcropPreviewBoxHeight = $('.jcrop-holder').height();

		var photoWidthRatio = fullSizePhotoWidth / jcropPreviewBoxWidth;
		var photoHeightRatio = fullSizePhotoHeight / jcropPreviewBoxHeight;

		var photoCroppedWidth = ($('#coordX2').val() - $('#coordX1').val()) / photoWidthRatio;
		var photoCroppedHeight = ($('#coordY2').val() - $('#coordY1').val()) / photoHeightRatio;

		var widthForDave = Math.round(photoWidthRatio * photoCroppedWidth);
		var heightForDave = Math.round(photoHeightRatio * photoCroppedHeight);

		var photoOffsetTop = parseInt($('#coordY1').val(), 10);
		var photoOffsetLeft = parseInt($('#coordX1').val(), 10);

		var ratio = parseInt($('#photo-wrapper').css('width'), 10) / parseInt($('#preview').css('width'), 10);
		var photoData = {
			"width": parseInt($('#preview img').css('width'), 10) * ratio
            , "top": parseInt($('#preview img').css('margin-top'), 10) * ratio
            , "left": parseInt($('#preview img').css('margin-left'), 10) * ratio
		};

		$('#PhotoX').val(photoOffsetLeft);
		$('#PhotoY').val(photoOffsetTop);
		$('#PhotoWidth').val(widthForDave);
		$('#PhotoHeight').val(heightForDave);

		$('#photo-upload').data('preview', photoData);
		$('#photo-upload-modal').jqm({ modal: true }).jqmHide();
	});



	$.validator.addMethod("regex", function (value, element, regexp) {
		return this.optional(element) || regexp.test(value);
	}, "Invalid word");

	$.validator.addMethod("greaterThanZero", function (value, element) {
		return this.optional(element) || (parseFloat(value) > 0);
	}, "Amount must be greater than zero.");

	$.validator.addMethod("fractional", function (value, element) {
		var regexp = new RegExp('^[0-9]+$|^[0-9]+\/[0-9]+$|^([0-9]* )?[0-9]+\/[0-9]+$');
		//var regexp = new RegExp('^(:?\d+ )?\d+/\d+$');
		return this.optional(element) || regexp.test(value);
	}, "Amount must be a valid whole number or fraction.");


	/* Show Recipe Preview Modal Window */
	$('a#preview-button').click(function () {

		// validate the recipe form when it is submitted
		if (!$("#recipeSubmitForm").validate({
			rules:
            {
            	"Tags": { required: "div#step-four input", minlength: 1 }
            },
			messages:
            {
            	"Tags": 'Please check at least one option.'
            },
			errorPlacement: function (error, element) {
				var errorPlaceholder = element;
				if (element.attr('name') == 'Tags') {
					errorPlaceholder = $("#occassionHeader span")
				}

				if (element.attr('name').indexOf('Ingredients') != -1) {
					errorPlaceholder = element.parent().next('td.error-cell').find('span');
				}

				if ((errorPlaceholder.nextAll(".error-icon").length == 0) && ($(error[0]).text().length > 0)) {
					$("<img src='/images/cookbook/error_icon.jpg' title='" + $(error[0]).text() + "' class='error-icon' />").insertAfter(errorPlaceholder);
				} else if ((errorPlaceholder.nextAll(".error-icon").length > 0) && ($(error[0]).text().length == 0)) {
					errorPlaceholder.nextAll(".error-icon").remove();
				}
			},
			success: function (label) {
				label.remove();
			}
		}).form()) {
			return;
		}

		populatePreview();
		$('#recipe-preview-modal').jqm({ modal: true, onLoad: function () { recipeDetailTabs() } }).jqmShow();
	});

	/* Submit Recipe Preview Modal Window */
	$('#recipe-preview-modal a.submit-button').click(function () {
		// validate the recipe preview form when it is submitted
		if (!$("#recipePreviewForm").validate({
			rules:
                {
                	"Terms": { required: "div#preview-options #Terms", minlength: 1 }
                },
			messages:
                {
                	"Terms": 'You must agree to the Terms of Use by checking this box.'
                },
			errorPlacement: function (error, element) {
				var errorPlaceholder = element;
				if (element.attr('name') == 'Terms') {
					errorPlaceholder = $("#preview-options p span")
				}

				if ((errorPlaceholder.nextAll(".error-icon").length == 0) && ($(error[0]).text().length > 0)) {
					$("<img src='/images/cookbook/error_icon.jpg' title='" + $(error[0]).text() + "' class='error-icon' />").insertAfter(errorPlaceholder);
				} else if ((errorPlaceholder.nextAll(".error-icon").length > 0) && ($(error[0]).text().length == 0)) {
					errorPlaceholder.nextAll(".error-icon").remove();
				}
			},

			success: function (label) {
				label.remove();
			}
		}).form()) {
			return;
		}
		$('#btnSubmitRecipe').click();
	});

	/* Recipe Detail Write a Review button in the recipe header (with the other tools) */
	$('#recipe-detail-content #recipe-tools a#write-review-button').live("click", function () {
		$('ul#cookbook-tabs li#tab-reviews').click();
	});

	/* Recipe Preview Modal - Edit and Close buttons */
	$('#recipe-preview-modal a.close-button').click(function () {
		$('ul#cookbook-tabs li#tab-recipe').click();
		$('#recipe-preview-modal').jqmHide();
	});

	/* Submit Recipes - Step 2 - remove ingredient */
	$('a.remove-ingredient').live("click", function () {
		$(this).closest('tr').remove();
	});

	/* Submit Recipes - Step 2 - add ingredient */
	$('a#add-ingredient').click(function () {
		var maxIngredientNumber = parseInt($("#ingredient-table tr.ingredient").last().attr('data-ingredientNumber')) + 1;
		var myData = { ingredientNumber: maxIngredientNumber };
		var templateContainer = $("#ingredient-table tr#add-ingredient-row");
		$("#addIngredientTemplate").tmpl(myData).insertBefore(templateContainer).find('td.ingredient input').autocomplete(source);
	});

	/* Submit Recipes - Step 2 - show/hide remove button for ingredient on hover */
	$("tr.ingredient:not(.jif-product)").live('hover', function (ev) {
		if (ev.type == 'mouseover') {
			$(this).find("td.button-remove a.remove").css("visibility", "visible");
		}
		if (ev.type == 'mouseout') {
			$(this).find("td.button-remove a.remove").css("visibility", "hidden");
		}
	});

	/* Submit Recipes - Step 3 - remove prep step */
	$('a.remove-prep-step').live("click", function () {
		$(this).closest('.prep-step-row').remove();
		var stepCounter = 1;
		$(".prep-step-row .instruction-step span").each(function () {
			$(this).html(stepCounter);
			stepCounter++;
		});
	});

	/* Submit Recipes - Step 3 - add prep step */
	$('a#add-prep-step').click(function () {
		if ($(".prep-step-row").length > 0) {
			var maxPrepStepId = parseInt($(".prep-step-row").last().attr('data-prepStepId')) + 1;
			var maxPrepStepNumber = $(".prep-step-row .instruction-step span").last().html();
			var newPrepStepNumber = parseInt(maxPrepStepNumber) + 1;
		} else {
			var maxPrepStepId = 0;
			var newPrepStepNumber = 1;
		}
		var myData = { prepStepId: maxPrepStepId, prepStepNumber: newPrepStepNumber };
		var templateContainer = $("#add-prep-step-row");
		$("#addPreparationTemplate").tmpl(myData).insertBefore(templateContainer);
	});

	/* Submit Recipes - Step 3 - show/hide remove button for prep step on hover */
	$("#instructions .row").live('hover', function (ev) {
		if (ev.type == 'mouseover') {
			$(this).find(".delete a.remove").css("visibility", "visible");
		}
		if (ev.type == 'mouseout') {
			$(this).find(".delete a.remove").css("visibility", "hidden");
		}
	});

});

ImageCrop = {};

ImageCrop.Crop = function(config) {
	this.config = config;

	this.init();
};

ImageCrop.Crop.prototype = {
	init: function() {
		//cache config
		this.$fullsize = this.config.fullsize;
		this.$previewPane = this.config.previewPane;
		this.$previewPane2 = this.config.previewPane2;
		this.imageSrc = "";

		//cache dom elements
		this.fullsizeImg = ""
		this.previewPaneImg = ""
		this.previewPaneImg2 = ""
		this.x = $('input[name=x]')
		this.x2 = $('input[name=x2]')
		this.y = $('input[name=y]')
		this.y2 = $('input[name=y2]')

		//setup
		this.runJcrop();
	},
	runJcrop: function() {

		testFullSizeSourceId = 0;

		testFullSizeSourceId = setInterval($.proxy(this.testFullSizeSource, this), 500);

	},
	testFullSizeSource: function() {
		if (this.$fullsize.children('img').attr('src') != null) {
			this.imageSrc = this.$fullsize.children('img').attr('src');
			this.fullsizeImg = this.$fullsize.children('img');
			clearInterval(testFullSizeSourceId);
			$.proxy(this.setJcrop(), this)
		}
	},

	setJcrop: function() {

		$('#loader').hide();
		previewImg = $('<img>').attr('src', this.imageSrc);
		previewImg2 = $('<img>').attr('src', this.imageSrc);

		this.$previewPane.children().remove();
		this.$previewPane.append(previewImg);
		this.previewPaneImg = this.$previewPane.children('img');

		this.$previewPane2.children().remove();
		this.$previewPane2.append(previewImg2);
		this.previewPaneImg2 = this.$previewPane2.children('img');

		photoPath = this.imageSrc;
		photoFileName = photoPath.substring(photoPath.lastIndexOf('/') + 1);

		this.fullsizeImg.onImagesLoad({
			itemCallback: $.proxy(function(img) {
				$(img).Jcrop({
					onSelect: $.proxy(this.showPreview, this),
					onChange: $.proxy(this.showPreview, this),
					allowSelect: false,
					sideHandles: false,
					boxWidth: 400,
					minSize: [150, 97],
					setSelect: [0, 0, 1000, 1000],
					aspectRatio: 335 / 216
				})

				$("#previews h3").show();
				$("#mask2").show();
				this.$previewPane.show();
				this.$previewPane2.show();

			}, this)
		})
	},

	showPreview: function(coords) {
		var resizedImgW = this.fullsizeImg.width();
		var resizedImgH = this.fullsizeImg.height();

		fullSizePhotoWidth = this.fullsizeImg.width();
		fullSizePhotoHeight = this.fullsizeImg.height();

		var rx = this.$previewPane.width() / coords.w;
		var ry = this.$previewPane.height() / coords.h;

		this.previewPaneImg.css({
			width: Math.round(rx * resizedImgW) + "px",
			height: Math.round(ry * resizedImgH) + "px",
			marginLeft: -1 * Math.round(rx * coords.x) + "px",
			marginTop: -1 * Math.round(ry * coords.y) + "px"
		});

		this.previewPaneImg2.css({
			width: Math.round(rx * resizedImgW) + "px",
			height: Math.round(ry * resizedImgH) + "px",
			marginLeft: -1 * Math.round(rx * coords.x) + "px",
			marginTop: -1 * Math.round(ry * coords.y) + "px"
		});

		this.x.val(coords.x);
		this.x2.val(coords.x2);
		this.y.val(coords.y);
		this.y2.val(coords.y2);
	}
}
