﻿//---------------//
//  MODAL POPUP  //


var popupStatus = false;
var modalPopup = $("#modalPopup");
var modalPopupContent = $("#modalPopupContent");
var modalPopupBackground = $("#modalPopupBackground");
var tabsHtml;


$(function()
{
    popupStatus = false;
    modalPopup = $("#modalPopup");
    modalPopupContent = $("#modalPopupContent");
    modalPopupBackground = $("#modalPopupBackground");
});

function showPopup()
{
    if ($.browser.mozilla && !/Win/.test(navigator.platform)) // Fixes Firefox bug where ad covers modal popup
        $(".skyScraperAd").hide();

    centerPopup();
    displayPopup();

    // Closing popup
    $(".modalPopupClose").each(function()
    {
        $(this).unbind("click.modalPopupClose").bind("click.modalPopupClose", function()
        {
            if ($("#btnCancel").length != 0)
                $("#btnCancel").click();
            else
                disablePopup();
        });
    });

    // Pressing Escape
    $(document).unbind("keypress.modalPopupClose").bind("keypress.modalPopupClose", function(e)
    {
        if (e.keyCode == 27 && popupStatus == 1)
        {
            if ($("#btnCancel").length != 0)
                $("#btnCancel").click();
            else
                disablePopup();
        }
    });

    return false;
}

var ie = document.all;
var nn6 = document.getElementById && !document.all;

var isdrag = false;
var x, y;
var dobj;

document.onmousedown = selectmouse;
document.onmouseup = function() { isdrag = false; };

function movemouse(e)
{
    if (!e)
        e = event;

    if (isdrag)
    {
        var top = ty + e.clientY - y;
        var left = tx + e.clientX - x;
        var height = document.documentElement.clientHeight - (modalPopup.height() + 56);
        var width = document.documentElement.clientWidth - (modalPopup.width() + 28);

        modalPopup.css(
        {
            "top": Math.min(Math.max(top, 0), height),
            "left": Math.min(Math.max(left, 0), width)
        });
        return false;
    }
    else
        isdrag = false;
}

function selectmouse(e)
{
    try
    {
        var fobj = nn6 ? e.target : event.srcElement;
        var topelement = nn6 ? "HTML" : "BODY";
        while (fobj.tagName != topelement && $(fobj).is(".dragme") == false)
        {
            fobj = nn6 ? fobj.parentNode : fobj.parentElement;
        }

        if (popupStatus && modalPopup != null && $(fobj).is(".dragme"))
        {
            isdrag = true;
            tx = parseInt(modalPopup.css("left"));
            ty = parseInt(modalPopup.css("top"));
            x = nn6 ? e.clientX : event.clientX;
            y = nn6 ? e.clientY : event.clientY;
            document.onmousemove = movemouse;
            return false;
        }
    }
    catch (err)
    {
        isdrag = false;
    }
}


function displayPopup()
{
    if (!popupStatus)
    {
        modalPopupBackground.css({ "opacity": "0.2" });

        modalPopupBackground.show();
        modalPopup.show();
        popupStatus = true;
    }
}

function centerPopup()
{
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = modalPopup.height();
    var popupWidth = modalPopup.width();

    //centering
    modalPopup.css(
    {
        "position": "fixed",
        "_position": "absolute",
        "top": windowHeight / 3 - popupHeight / 3,
        "left": windowWidth / 2 - popupWidth / 2
    });

    //only need force for IE6
    modalPopupBackground.css({ "height": windowHeight });
}

function disablePopup()
{
    if (popupStatus)
    {
        modalPopupBackground.hide();
        modalPopup.hide();
        modalPopupContent.html("");
        $("#modalPopup").css({ "width": 400 });
        setModalTitle("Loading...");
        popupStatus = false;

        if ($.browser.mozilla && !/Win/.test(navigator.platform)) // Fixes Firefox bug where ad covers modal popup
            $(".skyScraperAd").show();
    }
}

function reviewDestination(id, tabId)
{
    loadModal('Destination', 'ReviewDestination', id, null, null, tabId);
}

function loadModal(controller, action, id, data, width, tabStartIndex)
{
    if (!data)
        data = {};

    if (!data["loginCallback"])
    {
        var lc = "loadModal('" + controller + "','" + action + "'," + id + ",'" + ($.isPlainObject(data) ? $.param(data) : data) + "'," + width + "," + tabStartIndex + ");";
        if ($.isPlainObject(data))
            data["loginCallback"] = encodeURIComponent(lc);
    }

    //var html = "<div class='loaderWrapper'><img class='loaderImg' src='/Resources/Images/Loaders/loader2.gif' alt='Loading..' title='Loading..' /><span class='loader'>Loading, please wait..</span></div>";
    modalPopupContent.html("Loading..");

    if (width)
        $("#modalPopup").css({ "width": width });

    if (popupStatus)
        centerPopup();
    else
        showPopup();

    var partial = "/" + controller + "/" + action + "/";
    if (id != null)
        partial += id + "/";

    $.ajax({
        type: "GET",
        url: partial,
        data: data,
        cache: false,
        success: function(result)
        {
            modalPopupContent.html(result);
            setModalTitle();
            initiateTabs("ModalTabs", tabStartIndex);
            centerPopup();
        },
        error: function(result, err, e)
        {
            alertError('loadModal');
            disablePopup();
        }
    });
}

function setModalTitle(title)
{
    if (!title)
    {
        if ($("#modalPopupContent #ModalTitle").length > 0)
            title = $("#modalPopupContent #ModalTitle").val();
    }

    if (!!title)
    {
        $("#modalPopupTitle").html(title);

        if ($("#modalPopupTitle").width() > ($("#modalPopup").width() - 40))
            $("#modalPopupTitle").addClass("smallTitleFont");
        else
            $("#modalPopupTitle").removeClass("smallTitleFont");
    }
}

function setModalWidth(width)
{
    $("#modalPopup").css({ "width": width });
}

function diceClick(die, value)
{
    var selected = $(die).is(".diceSelected");

    $(die).closest(".modalDiceRow").find(".diceSelected").removeClass("diceSelected");
    $(die).closest(".modalFeatureList").find(".modalReview:visible").hide();

    if (selected)
    {
        value = "";
        toggleFeatureCommentLink($(die).closest(".modalFeatureControl").find(".featureCommentLink"), false);
        $(die).closest(".modalFeatureControl").find(".tabValidationMessage:visible").hide();
    }
    else
    {
        $(die).addClass("diceSelected");
        $(die).children(".diceWatermark").addClass("diceSelected");
        toggleFeatureCommentLink($(die).closest(".modalFeatureControl").find(".featureCommentLink"), true);
        updateCounters();
    }

    $(die).closest(".modalDiceRow").children(":hidden").get(0).value = value;
}

function clearDiceRow(reviewControlId)
{
    $("#" + reviewControlId).find(".modalDiceRow").find(".diceSelected").removeClass("diceSelected");
    toggleFeatureCommentLink($("#" + reviewControlId).find(".featureCommentLink"), false);
    $("#" + reviewControlId).find(".modalFeatureList").find(".modalReview:visible").hide();
    $("#" + reviewControlId).find(".modalDiceRow").children(":hidden").get(0).value = "";
}

function getRating(reviewControlId)
{
    return rating = $("#" + reviewControlId).find(".modalDiceRow :hidden").get(0).value;
}

function featureCommentLinkClick(commentLink)
{
    var show = $(commentLink).closest(".modalFeatureControl").find(".modalReview").is(":hidden");

    $(commentLink).closest(".modalFeatureList").find(".modalReview:visible").hide();

    if (show)
        $(commentLink).closest(".modalFeatureControl").find(".modalReview").show();

    updateCounters();
}

function suggHighComboChange(comboBox, suggBoxID)
{
    var value = $(comboBox).getSetSSValue();

    if (value == "-2")
    {
        $("#" + suggBoxID).closest(".tbWrapper").show();
        $(comboBox).closest(".modalFeatureControl").find(".modalDiceRow").hide();
    }
    else
    {
        if (value != "-1")
            $(comboBox).closest(".modalFeatureControl").find(".modalDiceRow").show();
        else
            $(comboBox).closest(".modalFeatureControl").find(".modalDiceRow").hide();

        $("#" + suggBoxID).closest(".tbWrapper").hide();
        $("#" + suggBoxID).val("");
        watermark($("#" + suggBoxID), false);
    }
}

function suggestKeyUp(suggBox)
{
    if ($(suggBox).val().length > 0)
        $(suggBox).closest(".modalFeatureControl").find(".modalDiceRow").show();
    else
        $(suggBox).closest(".modalFeatureControl").find(".modalDiceRow").hide();
}

function suggHighDiceClick(die, value)
{
    var url = "/Destination/";

    var index = parseInt($("#suggHighIndex").val());
    var sugg = $("#suggHighTitle").val();

    var params = {};
    params["rating"] = value;
    params["index"] = index;

    if (sugg != null && sugg != "" && sugg != $("#suggHighTitle").attr("watermarktext"))
    {
        for (var i = 0; i < $("#RateHighlightsContent .titleField").length; i++)
        {
            if ($("#RateHighlightsContent .titleField").get(i).innerText == sugg)
            {
                showMessage("Highlight already exists!", "Red");
                return;
            }
        };

        var locID = $("#tabsHtml .topBorderContent").attr("params");
        url = url + "SuggestHighlight";
        params["sugg"] = sugg;
        params["locationID"] = locID;
    }
    else
    {
        showMessage("You need to suggest a highlight title!", "Red");
        return;
    }

    $.ajax({
        type: "GET",
        dataType: "json",
        url: url,
        data: params,
        success: function(result)
        {
            if (result != null)
                processFeedback(result);
            else
                showMessage("An error occured while suggesting highlight!", "Red");
        },
        error: function(result, e)
        {
            if (e == 'parsererror' && !!result.responseText)
            {
                if (index == 0 && $("#noHighlights").length > 0)
                    $("#noHighlights").remove();

                $("#suggHighIndex").val(index + 1);

                $("#suggestedHighlights").append(result.responseText).show();
                $("#suggestedHighlights .featureCommentLink:last").click();
                $("#suggestedHighlights").closest(".modalFeatureList").animate({ scrollTop: $("#suggestedHighlights").closest(".modalFeatureList").attr("scrollHeight") }, 1000);
            }
            else
                showMessage("An error occured while suggesting highlight!", "Red");
        }
    });
}

function suggHotDiceClick(die, value)
{
    var url = "/Destination/";
    var params = {};

    var index = parseInt($("#suggHotIndex").val());
    var sugg = $("#suggHotTitle").val();

    if (sugg != null && sugg != "" && sugg != $("#suggHotTitle").attr("watermarktext"))
    {
        for (var i = 0; i < $("#RateHotSpotsContent .titleField").length; i++)
        {
            if ($("#RateHotSpotsContent .titleField").get(i).innerText == sugg)
            {
                showMessage("HotSpot already exists!", "Red");
                return;
            }
        };

        var locID = $("#tabsHtml .topBorderContent").attr("params");
        url = url + "SuggestHotSpot";
        params["index"] = index;
        params["sugg"] = sugg;
        params["rating"] = value;
        params["locationID"] = locID;
    }
    else
    {
        showMessage("You need to suggest a hotspot title.", "Red");
        return;
    }

    $.ajax({
        type: "GET",
        dataType: "json",
        url: url,
        data: params,
        success: function(result)
        {
            if (result != null)
                processFeedback(result);
            else
                showMessage("An error occured while suggesting hotspot!", "Red");
        },
        error: function(result, e)
        {
            if (e == 'parsererror' && !!result.responseText)
            {
                $("#suggHotIndex").val(index + 1);
                $("#suggestedHotSpots").append(result.responseText);
                $("#suggestedHotSpots").closest(".modalFeatureList").animate({ scrollTop: $("#suggestedHotSpots").closest(".modalFeatureList").attr("scrollHeight") }, 1000);
            }
            else
                showMessage("An error occured while suggesting hotspot!", "Red");
        }
    });
}

function updateCounters()
{
    $("#modalPopup .reviewBox").each(function()
    {
        updateCounter(this);
    });
}

function updateCounter(textArea)
{
    var counter = $(textArea).next(".modalReviewCounter");
    var length = $(textArea).val().length;

    if ($(textArea).val() != $(textArea).attr("watermarktext"))
        counter.html(140 - length);
    else
        counter.html(140);

    if ($(textArea).html() != $(textArea).val())
        $(textArea).html($(textArea).val()); // To prevent validation persist-html-bug..

    if ($(textArea).closest(".modalReview").is(":visible"))
        toggleFeatureCommentLink($(textArea).closest(".modalFeatureControl").find(".featureCommentLink"), true, "Hide comment");
    else if ($(textArea).closest("#reviewControl").find(".diceSelected").length > 0)
    {
        if (length > 0 && $(textArea).html() != $(textArea).attr("watermarktext"))
            toggleFeatureCommentLink($(textArea).closest(".modalFeatureControl").find(".featureCommentLink"), true, "View comment");
        else
            toggleFeatureCommentLink($(textArea).closest(".modalFeatureControl").find(".featureCommentLink"), true, "Add comment");
    }

    if (length > 120)
        counter.css({ "color": "Orange" });
    else
        counter.css({ "color": "Silver" });

    if (length > 140)
    {
        counter.css({ "color": "Red" });
        if ($(textArea).closest("#reviewControl").find(".diceSelected").length > 0)
            $(textArea).closest("#reviewControl").find(".tabValidationMessage").show();
    }
    else
        $(textArea).closest("#reviewControl").find(".tabValidationMessage").hide();
}

function toggleFeatureCommentLink(linkControl, visible, title)
{
    if (title)
        linkControl.text(title);

    if (visible)
        linkControl.show();
    else
        linkControl.hide();
}

function actComboChanged()
{
    var actId = getSetSuggActID();

    updateDestCombo();
    setTargetLevel(actId);
}

function ctryComboChanged()
{
    var ctryCode = getSetSuggCtryCode();
    var changed = setBaseCountryCode(ctryCode);
    updateDestCombo(changed);

    if (getSetSuggActID() == "-1" && !!ctryCode)
        callAction("/Destination/GeoQuery/", { "ctryCode": getSetSuggCtryCode() }, setSuggMapCountryCenter);
}

function updateDestCombo(ctryChanged)
{
    var actId = getSetSuggActID();
    var ctryCode = getSetSuggCtryCode();

    if (!actId || !ctryCode)
    {
        $("#modalPopupContent").find("#destSuggest").hide();
        $("#newActSelectDiv").hide();
        $("#comboDestDiv select").html("<OPTION value=0>(select destination)</OPTION>");
        $("#comboDestDiv .dropDownList").resetSS({ ddMaxHeight: '200px' });
        getSetSuggLocID(0);
    }
    else if (actId == "-1")
    {
        $("#newActSelectDiv").show();
        $("#comboDestDiv select").html("<OPTION class='filterOption' value=-1>Other Destination</OPTION>");
        $("#comboDestDiv .dropDownList").resetSS({ ddMaxHeight: '200px' });
        getSetSuggLocID(-1);
    }
    else
    {
        $("#modalPopupContent").find("#destSuggest").hide();
        $("#newActSelectDiv").hide();

        $.ajax({
            type: "GET",
            url: "/Destination/DestinationCombo/",
            data: { "actID": actId, "ctryCode": ctryCode },
            success: function(result)
            {
                $("#comboDestDiv").html(result);
                $("#comboDestDiv .dropDownList").resetSS({ ddMaxHeight: '200px' });

                if (ctryChanged || (getSetSuggLocID() != -1))
                    getSetSuggLocID(0);
                else
                    getSetSuggLocID(-1);
            }
        });
    }
}

function destComboChanged()
{
    setIsSuggestion();

    var locID = getSetSuggLocID();

    if (locID > 0)
    {
        $.getJSON("/Destination/GetDestinationMarker/", { "locID": locID }, function(result)
        {
            $("#suggLatDiv :hidden").get(0).value = result.Latitude.toString().replace(",", ".")
            $("#suggLngDiv :hidden").get(0).value = result.Longitude.toString().replace(",", ".")

            addSuggestMarker(null, true);
        });
    }
}

function setTargetLevel(actId)
{
    if (!actId)
    {
        $("#targetLevel").html("Suggest Destination:");
        return;
    }

    $("#targetLevel").html("");

    $.ajax({
        type: "GET",
        url: "/Destination/GetActivityTargetLevel/",
        data: { "actID": actId },
        cache: false,
        success: function(result)
        {
            $("#targetLevel").html(result);
        },
        error: function(result)
        {
            $("#targetLevel").html("Destination");
        }
    });
}

var alreadyIsSuggestion = false;
function setIsSuggestion(reInit)
{
    var isSuggestion = (getSetSuggLocID() == -1);

    if (!isSuggestion && suggestMarker)
        removeSuggestMarker();

    if (alreadyIsSuggestion == isSuggestion && !reInit)
        return;

    alreadyIsSuggestion = isSuggestion;

    if (isSuggestion)
    {
        $("#modalPopupContent").find("#destSuggest").show();

        if (reInit)
            addSuggestMarker(null, false);
        else
            callAction("/Destination/GeoQuery/", { "ctryCode": getSetSuggCtryCode() }, setSuggMapCountryCenter);
    }
    else
    {
        $("#modalPopupContent").find("#destSuggest").hide();
    }

    centerPopup();
}

function findDestSugg()
{
    var suggestion = getText('postItem_DestSuggestion');
    if (suggestion)
        callAction("/Destination/GeoQuery/", { "ctryCode": getSetSuggCtryCode(), "suggestion": suggestion }, setSuggMapSearch);
}

function checkForFeedback(result)
{
    var json = null;

    try
    {
        json = result.get_response().get_object();

        if (json)
        {
            processFeedback(json);
            return true;
        }
    }
    catch (ex)
    {
        // Result is not Json - do nothing..
    }

    return false;
}

function storeTabs()
{
    tabsHtml = $("#tabsHtml").html();
}

function initReviewDest(title, initiateIndex)
{
    if (popupStatus && $("#ModalTabs").length > 0)
    {
        setModalTitle(title);
        setModalWidth(700);

        if (initiateIndex >= 0)
            initiateTabs("ModalTabs", initiateIndex);

        centerPopup();
    }
}

function reInitReviewDest(result)
{
    if (popupStatus)
    {
        $("#tabsHtml").html(tabsHtml);

        var test = $($(result)[0].$4).find("#reviewExpertsDiv").html();

        $(function()
        {
            $("#tabsHtml").find("#reviewExpertsDiv").html(test);
        });

        initiateTabs("ModalTabs", -1);

        if ($("#uploadMediaWrapper").length > 0)
        {
            $("#uploadMediaWrapper").html("<input id='uploadMedia' name='uploadMedia' type='file' class='fileStyle' onchange='$(this).triggerChange();' />");
            initUploadForm();
        }
        $("#tabsHtml .modalTabContent:visible .dropDownList").resetSS({ ddMaxHeight: '100px' });
        updateCounters();
        centerPopup();
    }
}

function reInitEditProfile(result)
{
    if (popupStatus)
    {
        var gender = $("#Gender").getSetSSValue();
        var residence = $("#Residence").getSetSSValue();
        var yob = $("#YOB").getSetSSValue();

        $("#tabsHtml").html(tabsHtml);

        $("#Gender").getSetSSValue(gender);
        $("#Residence").getSetSSValue(residence);
        $("#YOB").getSetSSValue(yob);
        
        setModalValidation(result);
        initiateTabs("ModalTabs", -1);

        if ($("#uploadMediaWrapper").length > 0)
        {
            $("#uploadMediaWrapper").html("<input id='uploadMedia' name='uploadMedia' type='file' class='fileStyle' onchange='$(this).triggerChange();' />");
            initProfilePictureForm();
        }
        
        $("#tabsHtml .modalTabContent:visible .dropDownList").resetSS();
        centerPopup();
        updateCounters();
    }
}

function setModalValidation(result)
{
    $(".tabValidationMessage").hide();

    $(result.get_data()).find(".modalValidation").each(function()
    {
        if ($("#" + this.id + "ation").length > 0)
            $("#" + this.id + "ation").show();
    });
}

function initSuggestDestination(title)
{
    if (popupStatus)
    {
        if (!title)
            title = "Add Destination";

        setModalTitle(title);
        setModalWidth(710);
        initiateModalMap();

        if ($("#cbAddToWentList :checkbox").attr("checked") == false)
            $("#modalPopupContent").find("#reviewControl").hide();

        alreadyIsSuggestion = (getSetSuggLocID() == -1);
        if (alreadyIsSuggestion)
            setIsSuggestion(true);
        else
        {
            updateDestCombo(false);
            getSetSuggLocID(getSetSuggLocID());
        }

        var actID = getSetSuggActID();
        if (actID)
        {
            setTargetLevel(getSetSuggActID());
            if (actID == "-1")
                $("#newActSelectDiv").show();
        }

        $("#modalPopupContent .dropDownList").resetSS({ ddMaxHeight: '200px' });

        centerPopup();
    }
}

function setPostAction(aksjon)
{
    $("#postAction").val(aksjon);
}

function suggHigh(source)
{
    var sugg = $("#suggHighTitle").val();
    $("#suggHighTitle").val("");

    var index = parseInt($("#suggHighIndex").val());
    if (sugg != null && sugg != "")
        $("#suggHighIndex").val(index + 1);

    $(source).get(0)._request._url = $(source).get(0)._request._url + "&index=" + index + "&sugg=" + sugg;
}

function suggHot(source)
{
    var sugg = $("#suggHotTitle").val();
    $("#suggHotTitle").val("");

    var index = parseInt($("#suggHotIndex").val());
    if (sugg != null && sugg != "")
        $("#suggHotIndex").val(index + 1);

    $(source).get(0)._request._url = $(source).get(0)._request._url + "&index=" + index + "&sugg=" + sugg;
}

function profileChanged(id)
{
    if ($(".posterProfile").length > 0 && $(".posterProfile").attr("userid") == id)
    {
        $.ajax({
            type: "GET",
            url: "/Community/ProfilePoster/",
            cache: false,
            success: function(result)
            {
                $(".posterProfile").html(result);
            },
            error: function()
            {
                showMessage("An error occured while updating profile!", "Red");
            }
        });
    }
}

function updateMembersProfile(category)
{
    $.ajax({
        type: "GET",
        url: "/Community/FeaturedMemberProfilePoster/",
        cache: false,
        data: { userSortOrder: category },
        success: function (result)
        {
            $(".membersPosterPartial").html(result);
        },
        error: function (err)
        {
            showMessage("An error occured while updating featured profile!", "Red");
        }
    });
}

function linkExchangeProfilePoster()
{
    $.ajax({
        type: "GET",
        url: "/Community/LinkExchangeProfilePoster/",
        cache: false,
        data: null,
        success: function (result)
        {
            $(".membersPosterPartial").html(result);
        },
        error: function (err)
        {
            showMessage("An error occured while updating featured profile!", "Red");
        }
    });
}
function initUploadForm()
{
    var settings = {
        autoUpload: true,
        autoUploadCallback: uploadMediaSubmit,
        width: 319,
        defaultText: "b) Click Browse to select & upload file"
    };

    $("#uploadMedia").filestyle(settings);
    
    // Fixes bug in Firefox where the form tag disappears after postback
    if ($.browser.mozilla && $("#UploadMediaForm").length == 0 && $("#uploadFormInner").length == 1)
    {
        var wrapper = "<form id=\"UploadMediaForm\" action=\"/Destination/UploadMedia\" method=\"post\" enctype=\"multipart/form-data\">";
        $("#uploadFormInner").wrap(wrapper);
    }
}

function uploadMediaSubmit(postAction)
{
    $('#mediaPostAction').val(postAction || 9);
    $("#uploadFormInner").closest('form').ajaxSubmit(
    {
        type: "POST",
        iframe: true,
        dataType: "json",
        beforeSubmit: function ()
        {
            var html = "<div id='uploadingMedia' class='uploadedMediaItemWrap'><img src='/Resources/Images/Loaders/loader1.gif' alt='Uploading Media' title='Uploading Media' /><br />Uploading..</div>";
            $("#uploadedMedia").prepend(html);
        },
        success: function (result)
        {
            $("#uploadingMedia").remove();

            if (result.feedback != null)
                processFeedback(result.feedback);

            if (result.media)
            {
                var html = "<div id='uploaded" + result.media.MediaTypeString + result.media.MediaID + "' class=\"uploadedMediaItemWrap\" onclick=\"if (confirm('Are you sure you want to delete this " + result.media.MediaTypeString.toLowerCase() + "?')) { callFeedbackAction('POST', '/Destination/DeleteDestinationMedia/', { 'mediaID': " + result.media.MediaID + ", 'mediaType': '" + result.media.MediaTypeString + "' }, false, 'An error occured while deleting " + result.media.MediaTypeString.toLowerCase() + "!'); }\">";
                html += "<div class='uploadedMediaItemOverlay'></div>";
                html += "<img class='uploadedMediaItem' src='" + result.media.ThumbUrl + "' title='Delete " + result.media.MediaTypeString + "' alt='Delete " + result.media.MediaTypeString + "' />";
                html += "</div>";

                $("#uploadedMedia").prepend(html);
            }
        },
        error: function (xhr, textStatus, errorThrown)
        {
            $("#uploadingMedia").remove();
            showMessage("An error occured while uploading!", "Red");
        }
    });
}

function initProfilePictureForm()
{
    var settings = {
        autoUpload: true,
        autoUploadCallback: function ()
        {
            $('#UploadProfilePicture').ajaxSubmit(
            {
                type: "POST",
                iframe: true,
                dataType: "json",
                beforeSubmit: function ()
                {
                    $("#ModalProfilePicture").hide();
                    $("#ModalNoProfilePicture").hide();
                    $("#ModalUploadProfilePicture").show();
                },
                success: function (result)
                {
                    $("#ModalUploadProfilePicture").hide();

                    if (result.feedback != null)
                        processFeedback(result.feedback);

                    if (result.mediaItem)
                    {
                        $("#DeleteProfilePicture").val(false);
                        $("#ProfilePictureID").val(result.mediaItem.MediaID);

                        var img = $("#ModalProfilePictureImg");
                        img.attr("src", result.mediaItem.Url);
                        img.attr("alt", result.mediaItem.Title);
                        img.attr("title", result.mediaItem.Title);
                        $("#ModalProfilePicture").show();
                    }
                    else
                        $("#ModalNoProfilePicture").show();
                },
                error: function (xhr, textStatus, errorThrown)
                {
                    $("#ModalUploadProfilePicture").hide();
                    $("#ModalNoProfilePicture").show();
                    showMessage("An error occured while uploading!", "Red");
                } 
            });
        },
        width: 212,
        defaultText: "Click Browse to select & upload file"
    };

    $("#uploadMedia").filestyle(settings);
}

function initLinkExchangeModal(zclipPath, badgeReturnUrl)
{
    $("#LinkExchangeForm .dropDownList").resetSS({ ddMaxHeight: '200px' });

    $(function ()
    {
        $("#btnCopyLink").zclip(
        {
            path: zclipPath,
            copy: 'http://www.activitravel.com'
        });
        $("#btnCopyTitle").zclip(
        {
            path: zclipPath,
            copy: 'Activitravel'
        });
        $("#btnCopyText").zclip(
        {
            path: zclipPath,
            copy: 'Activitravel.com is an activity travel community and a guide to the best activity travel destinations in the world!'
        });
        $("#btnCopyBadge").zclip(
        {
            path: '/Flash/ZeroClipboard.swf',
            copy: "<a style='outline: none;' target='_blank' href='" + badgeReturnUrl + "'><img src='http://www.activitravel.com/Resources/Images/Badges/badge.png' style='border: none; height: 50px; width: 160px;' /></a>"
        });
    });
}
