﻿//TODO: convert to plugin
//should be param with insaration mode: replace, before, after
var createItemOptions = {
    success: function(responseText, statusText, xhr, $form) {
        $form.resetForm();
        var divTarget = $('#divItems .music_item_container:first');
        divTarget.before(responseText);
		wireUpElements();
    },
    error: submitError
};

function createItemFormSubmit(form) {
    $(form).validate({
        submitHandler: function(form) {
            var artist = form.txtCreateItemArtist.value.toUpperCase();
            var title = form.txtCreateItemTitle.value.toUpperCase();
            var matchArtist = 0;
            var matchTitle = 0;
            var themeId = $.deparam.querystring(form.action)["ID"];
            var returnValue = true;
            var videoId = form.CreateItemYtLink.value.replace('tag:youtube.com,2008:video:', 'http://www.youtube.com/watch?v=').replace('http://www.youtube.com/watch?v=', '');
            var isEmbeddable = false;
            var youtubeFeedUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?alt=json';

            $.ajax({
                url: youtubeFeedUrl,
                dataType: 'json',
                async: false,
                success: function(data, textStatus, XMLHttpRequest) {
                    isEmbeddable = data["entry"]["media$group"]["media$content"][0]["yt$format"] == 5;
                }
            });

            $.ajax({
                url: '/themes/items?ThemeId=' + themeId,
                async: false,
                success: function(data, textStatus, XMLHttpRequest) {
                    for (key in data["Items"]) {
                        var a = data["Items"][key]["Artist"];
                        var t = data["Items"][key]["Title"];
                        var d0 = fuzzy_match_ld(a.toUpperCase(), artist);
                        var d1 = fuzzy_match_ld(t.toUpperCase(), title);
                        if (d0 <= 5 && d1 <= 5) {
                            matchArtist = a;
                            matchTitle = t;
                            returnValue = false;
                            break;
                        }
                    }
                }
            });

            if (returnValue == false || isEmbeddable == false) {
                var message = '';

                if (returnValue == false)
                    message = '<div>This theme already has: <span style="text-transform:capitalize">' + matchTitle + ' by ' + matchArtist + '</span></div>';

                if (isEmbeddable == false)
                    message += '<div style="margin-top:12px"><B>Note: the video you selected can not be played outside of youtube, use the youtube search feature to find a different video</B></div>';

                $('<div Title="Meltinpop Notification"><div style="margin-top:auto; margin-bottom:auto">' +
					message + '<div style="margin-top:12px">Are you sure you would like to add this?</div></div></div>').dialog({
					    resizable: false,
					    height: 250,
					    width: 400,
					    modal: true,
					    buttons: {
					        "Yes": function() {
					            $(form).ajaxSubmit(createItemOptions);
					            $(this).dialog("close");
					        },
					        Cancel: function() {
					            returnValue = false;
					            $(this).dialog("close");
					        }
					    }
					});
            }
            else {
				$("#divCreateNewItem").hide();
				$("#video_short_search").show();
				$("#txt_video_title").focus();
                $(form).ajaxSubmit(createItemOptions);
            }
            return false;
        }
    });
}

var createCommentOptions = {
    success: function(responseText, statusText, xhr, $form) {
        $form.resetForm();
		
        $(responseText).appendTo($form.closest('#divItemComments').children('[id^="divPreviousComments_"]'));

        var counter = parseInt($form.closest('#divItemComments').find('.comments_counter').html());
        if (!isNaN(counter)) {
            $form.closest('#divItemComments').find('.comments_counter').html(counter + 1);
        }
		
		$form.find(".avatarpic").css('display','none');
		$form.find(".add_comment_btn").css('display','none');
		$form.find('.comment_field').textboxhelp({help:comment_field_textbox_help});
		
	},
    error: submitError
};

var userSettingsOptions = {
    success: function(responseText, statusText, xhr, $form) {
        settingsDialogClose();
    },
    error: submitError


};

var inviteOptions = {
    success: function(responseText, statusText, xhr, $form) {
        $form.html(responseText);
    },
    error: submitError
};

var createThemeOption = {
    success: function(responseText, statusText, xhr, $form) {
        //&form is null!!! since it  wizard - need to check way
        $("form:#createThemeForm").html(responseText);

    },
    resetForm: true,
    error: submitError
};

var reportOptions = {
    success: function(responseText, statusText, xhr, $form) {
        $form.closest('#divReportContent').html(responseText);
    },
    error: submitError
};

var searchOptions = {
    success: function(responseText, statusText, xhr, $form) {
        $("#divContentMain").html(responseText);
		document.title = "Search Results";
    },
    resetForm: true,
    error: submitError
};

function createCommentSubmit(form) {
    $(form).validate({
        submitHandler: function(form) {
            $(form).ajaxSubmit(createCommentOptions);
        }
    });
    return false;
}
function userSettingsSubmit(form) {
    $(form).validate({
        submitHandler: function(form) {
            $(form).ajaxSubmit(userSettingsOptions);
        }
    });
    return false;
}
function inviteSubmit(form) {
    $(form).ajaxSubmit(inviteOptions);
    return false;
}

function createThemeWizardInit() {
    $("form:#createThemeForm").formwizard({
        formPluginEnabled: true,
        historyEnabled: false,
        validationEnabled: true,
        focusFirstInput: true,
        formOptions: createThemeOption
    });
}

function reportFormSubmit(form) {
    $(form).ajaxSubmit(reportOptions);
    return false;
}

function searchSubmit(form) {
    $(form).validate({
        submitHandler: function(form) {
            $(form).ajaxSubmit(searchOptions);
        }
    });
    return false;
}
function submitError(result) {
    alert('Error(MPF53):Could not add content.');
}




