﻿var timers = [];
var timersIndex = [];
var defaultTimerInterval = 6000;

function initiateTabs(tabsID, tabStartIndex)
{
    $(document).ready(function ()
    {
        tabStartIndex = tabStartIndex || 0;

        var tabs = [];
        var tabContainers = [];

        $("#" + tabsID + " .topBorderContent li").each(function ()
        {
            var content = "#" + $(this).attr("panel");
            var parentDiv = $(this).parent().parent("div").get(0);

            tabs.push(parentDiv);
            tabContainers.push($(content).get(0));

            $(this).unbind("click.activitravel").bind("click.activitravel", function ()
            {
                try
                {
                    if ($(parentDiv).is(".tabSelected") && $(this).is(".tabButtonFirst") && $(this).attr("refresh") != 1)
                        return false;

                    var id = $(this).get(0).id;
                    content = "#" + $(this).attr("panel");

                    if ($("#" + tabsID).find(".tabValidationMessage:visible:.critical").length > 0)
                    {
                        showMessage("Please correct errors before continuing!", "Red");
                        return false;
                    }

                    $("#emptyAd").hide();

                    if ($(this).is(".tabButtonLast"))
                    {
                        var firstText = $(this).prev(".tabButtonFirst").text();
                        var firstPanel = $(this).prev(".tabButtonFirst").attr("panel");
                        var prevID = $(this).prev(".tabButtonFirst").attr("id");

                        $(this).prev(".tabButtonFirst").attr({ "panel": $(this).attr("panel"), "id": id });
                        $(this).prev(".tabButtonFirst").text($(this).text());
                        $(this).attr({ "panel": firstPanel, "id": prevID });
                        $(this).text(firstText);
                    }

                    $(tabs).removeClass("tabSelected");
                    $(parentDiv).addClass("tabSelected");

                    $(tabContainers).hide();
                    $(content).show();

                    var params = $("#" + tabsID + " .topBorderContent").attr("params");
                    var loadParams = [];

                    if ($("#" + tabsID + " .topBorderContent").attr("detailsID"))
                        loadParams = { "pageNo": 0, "detailsID": parseInt($("#" + tabsID + " .topBorderContent").attr("detailsID")), "reloadFilterPanel": true };
                    else if ($("#" + tabsID + " .topBorderContent").attr("destination"))
                        loadParams = { "pageNo": 0, "reloadFilterPanel": true, "destination": $("#" + tabsID + " .topBorderContent").attr("destination") };

                    if ($("#" + tabsID + " .topBorderContent").attr("search"))
                        loadParams["search"] = $("#" + tabsID + " .topBorderContent").attr("search");

                    if ($(content).is(".showEmptyAd"))
                        $("#emptyAd").show();


                    if ($(content).html() == '' || $(content).html() == 'Loading...' || $(content).find("#loader").length > 0 || $(this).attr("refresh") == 1)
                    {
                        var partial = "/" + $("#" + tabsID + " .topBorderContent").attr("controller") + "/" + id + "/" + params;
                        loadTab(partial, loadParams, content);
                        $(this).attr("refresh", 0)
                    }
                    else if ($(this).attr("activatedCallback") != null)
                    {
                        eval($(this).attr("activatedCallback"));
                    }
                    else if ($(content + " .destinationList").length > 0)
                    {
                        var listID = $(content + " .destinationList").get(0).id;
                        var row = $("#" + listID + " .listItemRowSelected").get(0);

                        if (listID && row)
                        {
                            initListMap(listID);
                            destListSelect(listID, row, true, true);
                        }
                    }

                    return false;
                }
                catch (err)
                {
                    alertError('initiateTabs');
                }
            });
        });

        if (tabStartIndex != -1)
        {
            var startTab;

            if (isNaN(tabStartIndex))
                startTab = $("#" + tabsID + " .topBorderContent").find("#" + tabStartIndex);
            else
            {
                if ((tabs.length - 1) < tabStartIndex)
                    tabStartIndex = (tabs.length - 1);

                startTab = $("#" + tabsID + " .topBorderContent li:eq(" + tabStartIndex + ")");
            }

            if (startTab.length > 0)
                startTab.click();
            else if ($("#" + tabsID + " .topBorderContent li:eq(0)").length > 0)
                $("#" + tabsID + " .topBorderContent li:eq(0)").click();
        }
    });
}

function loadTab(partial, params, panel)
{
    if (partial != null && panel != null)
    {
        if (panel.substr(0, 1) != "#")
            panel = "#" + panel;

        if ($(panel + " .timer").length > 0)
            killTimer($(panel + " .timer").get(0).id);

//        var html = "<div class='loader'><img class='loaderImg' src='/Resources/Images/Loaders/loader2.gif' alt='Loading..' title='Loading..' /><div class='loader'>Loading, please wait..<div></div>";
        $(panel).html("Loading..");
        //        $(panel).ajaxStart(function()
        //        {
        //            $(this).html("Loading...");
        //        });

        if (!params || params.length == 0)
            params = { "pageNo": 0, "reloadFilterPanel": true };

        $.ajax({
            type: "GET",
            url: partial,
            data: params,
            cache: false,
            success: function (result)
            {
                $(panel).html(result);

                if ($(panel + " .slideList").length > 0 || $(panel).is(".slideList"))
                {
                    var slideList = $(panel).is(".slideList") ? $(panel).get(0) : $(panel + " .slideList").get(0);

                    if ($(slideList).is(".destinationList"))
                    {
                        var pageNo = parseInt($(slideList).attr("pageNo"));
                        params["pageNo"] = pageNo;

                        initListMap(slideList.id, pageNo);
                        initDestList(slideList.id, pageNo);

                        if ($(slideList).closest(".tabContent").find(".destListFilterWrapper").length > 0)
                        {
                            var filterPanelID = $(slideList).closest(".tabContent").find(".destListFilterWrapper").attr("id");

                            initFilterForm(filterPanelID + "Form");

                            if ($(slideList).closest(".tabContent").find(".destListFilterWrapper").attr("initiated") != "1")
                            {
                                $("#" + filterPanelID + " :visible :first .dropDownList").sSelect({ ddMaxHeight: '200px' });
                                $(slideList).closest(".tabContent").find(".destListFilterWrapper").attr("initiated", "1")
                            }
                        }
                    }
                    else if ($(slideList).is(".reviewList"))
                    {
                        var infoDiv = $("#destinationInfoDiv");
                        var id = $(infoDiv).children("#locID").val();
                        var lat = $(infoDiv).children("#lat").val().replace(",", ".");
                        var lng = $(infoDiv).children("#lng").val().replace(",", ".");

                        var mapID = $(panel).find(".map").get(0).id;
                        initiateMap(mapID, false);
                        addDestMarker(mapID, id, lat, lng, null);

                        reviewListSelect(slideList.id, parseInt($(slideList).find(".slideListItem:first").attr("detailsid")));
                    }
                    else if ($(slideList).is(".featureList"))
                    {
                        var item = $(slideList).find(".slideListItem:first");
                        scrollToReviews(item, item.attr("detailsid"));
                    }

                    initiateSlideList(slideList.id, partial, params);
                }
                if ($(panel).is(".centerPopup"))
                    centerPopup();

                if ($(panel).attr("loadedCallback") != null)
                    eval($(panel).attr("loadedCallback"));

                preventBubbling(panel);
                roundCorners(panel);
            },
            error: function (result)
            {
                alertError('loadTab');
            }
        });
    }
}

function tabMoreClick(partial, params, panel)
{
    if (partial != null && panel != null)
    {
        $("#" + panel + " .tabsMoreButton").hide();
        $("#" + panel).append("<div class='loadingDiv'>Loading...</div>");

        $.ajax({
            type: "GET",
            url: partial,
            data: params,
            success: function(result)
            {
                var scroll = $("#" + panel + " .loadingDiv:last").position().top + $("#" + panel).closest(".scrollPanel").scrollTop();
                $("#" + panel).closest(".scrollPanel").animate({ scrollTop: scroll }, 500)
                $("#" + panel + " .loadingDiv").hide();
                $("#" + panel).append(result);
            },
            error: function(result)
            {
                $("#" + panel + " .loadingDiv").hide();
                alertError('tabMoreClick');
            }
        });
    }
}

function changeMenuTab(menu, index)
{
    $("#" + menu + " li").get(index).click();
}
function prevMenuTab(menu)
{
    var selected = $("#" + menu + " .tabSelected");
    if (selected.prev(".tabButton") != null)
        selected.prev(".tabButton").find("li").click();
}
function nextMenuTab(menu)
{
    var selected = $("#" + menu + " .tabSelected");
    if (selected.next(".tabButton") != null)
        selected.next(".tabButton").find("li").click();
}

function preventBubbling(topElement)
{
    $(topElement).find(".bubbleBurst").each(function()
    {
        $(this).click(function(e)
        {
            e.cancelBubble;

            if (e.stopPropagation)
                e.stopPropagation();
        });
    });
}

function showMessage(html, color)
{
    if (!color)
        color = "Blue";

    $("#messageDiv").html(html)
                    .css({ "color": color })
                    .slideDown("slow").animate({ color: "black" }, 4000, function() { $(this).slideUp("fast") });
    //.animate({ backgroundColor: "white" }, 3000, function() { $(this).slideUp("fast") });
}

function showHelp(helpPanel)
{
    if ($("#helpDiv").length > 0)
    {
        $('#helpDiv').find('#helpDivContent').html("<div style='padding: 10px;'>Loading...</div>");
        $('#helpDiv').show();

        $.ajax({
            type: "GET",
            url: '/Help/ShowHelpPanel/',
            cache: false,
            data: { "helpPanel": helpPanel },
            success: function (result)
            {
                $('#helpDiv').find('#helpDivContent').html(result);
            },
            error: function (result)
            {
                $('#helpDiv').hide();
            }
        });
    }
}

function alertError(caller)
{
    alert("Oops - an unknown error ocurred! Please make sure your last changes were saved.");
}

// DESTINATION LISTS  *** START *** //

function initDestList(listID, pageNo)
{
    $(function()
    {
        var list = $("#" + listID);

        if (list && list.is(".destinationList"))
        {
            try
            {
                if (list.find("#page" + pageNo + " .listItemRow").length == 0)
                {
                    var thumb = list.closest(".tabContent").find("#EmptyListPictureUrl").val();
                    var alt = list.closest(".tabContent").find("#EmptyListPictureTitle").val();
                    var mediaID = list.closest(".tabContent").find("#EmptyListPictureMediaID").val();
                    var picture = list.closest(".tabContent").find(".mapModulePicture");
                    picture.attr("src", thumb);
                    picture.attr("alt", alt);
                    picture.attr("title", alt);
                    picture.attr("mediaID", mediaID);
                }
                else
                {
                    var btnDiv = list.parent().find(".gearButtonDiv");

                    list.find("#page" + pageNo + " .listItemRow").bind("mouseenter", function()
                    {
                        pauseTimer(listID);
                        destListSelect(listID, this, true, true);
                        $(this).find(".actionButtonsHidden").show();
                    });
                    list.find("#page" + pageNo + " .listItemRow").bind("mouseleave", function()
                    {
                        if (btnDiv.is(":hidden"))
                            $(this).find(".actionButtonsHidden").hide();

                        resumeTimer(listID, defaultTimerInterval);
                    });

                    btnDiv.bind("mouseenter", function()
                    {
                        pauseTimer(listID);
                    });
                    btnDiv.bind("mouseleave", function()
                    {
                        resumeTimer(listID, defaultTimerInterval);
                    });

                    if (list.is(".timer"))
                        startDestListFlipper(listID, pageNo);
                    else
                    {
                        var row = list.find("#page" + pageNo + " .listItemRow").get(0);
                        destListSelect(listID, row, true, true);
                    }
                }
            }
            catch (err)
            {
                alertError('initDestList');
            }
        }
    });
}

function startDestListFlipper(listID, pageNo)
{
    try
    {
        var mapID = $("#" + listID).attr("mapid");

        killTimer(listID);
        timersIndex[listID] = 0;

        timers[listID] = $.timer(0, function(timer)
        {
            if ($("#" + listID).find("#page" + pageNo + " .listItemRowSelected").length > 0)
            {
                var selectedRow = $("#" + listID).find("#page" + pageNo + " .listItemRowSelected").get(0);
                timersIndex[listID] = parseInt($(selectedRow).attr("index")) + 1;

                if (timersIndex[listID] > ($("#" + listID).find("#page" + pageNo + " .listItemRow").length - 1))
                    timersIndex[listID] = 0;
            }
            else
                timersIndex[listID] = 0;

            if ($("#" + listID).find("#page" + pageNo + " .listItemRow").length > timersIndex[listID])
            {
                var row = $("#" + listID).find("#page" + pageNo + " .listItemRow").get(timersIndex[listID]);
                destListSelect(listID, row, true, true);
            }
            else
                killTimer(listID);
        });

        destListSelect(listID, $("#" + listID).find("#page" + pageNo + " .listItemRow").get(0), true, true);

        timers[listID].reset(defaultTimerInterval);
    }
    catch (err)
    {
        var row = $("#" + listID).find("#page" + pageNo + " .listItemRow").get(timersIndex[listID]);
        destListSelect(listID, row, true, true);
    }
}

function destListSelect(listID, row, clearSelections, highlight)
{
    try
    {
        if (clearSelections)
            destListClearSelections(listID);

        var list = $("#" + listID);
        var mapID = list.attr("mapid");
        var locID = $($(row)).find("#locID").val();

        list.find(".actionButtonsHidden").hide();
        $(row).addClass("listItemRowSelected");

        if (highlight)
            highlightMapMarker(mapID, locID, true);

        var thumb = $(row).find("#thumb").val();
        var alt = $(row).find("#alt").val();
        var credit = $(row).find("#credit").val();
        var creditLink = $(row).find("#creditLink").val();
        var picture = list.closest(".tabContent").find(".mapModulePicture");
        var link = list.closest(".tabContent").find("#mapModuleCreditLink");

        picture.attr({ src: thumb, alt: alt, title: alt });
        link.attr("href", creditLink).html(credit);
    }
    catch (err)
    {
        alertError('destListSelect');
    }
}

function reviewListSelect(listID, userID)
{
    var infoDiv = $("#" + listID).find("#user" + userID);
    
    if (infoDiv.length == 0)
        infoDiv = $("#destinationInfoDiv");
    
    var picture = $("#" + listID).closest(".tabContent").find(".mapModulePicture");
    var link = $("#" + listID).closest(".tabContent").find("#mapModuleCreditLink");

    var addMedia = $(infoDiv).children("#addMedia").val();
    var locID = $(infoDiv).children("#locationID").val();
    var thumb = $(infoDiv).children("#thumb").val();
    var alt = $(infoDiv).children("#alt").val();
    var credit = $(infoDiv).children("#credit").val();
    var creditLink = $(infoDiv).children("#creditLink").val();
    var mediaID = $(infoDiv).children("#mediaID").val();

    picture.attr({ src: thumb, alt: alt, title: alt, addMedia: addMedia, locID: locID, mediaID: mediaID });
    link.attr("href", creditLink).html(credit);
}

function adjustCorners(img)
{
    var div = $(img).closest("#mediaImageCorners");
    var topVal = (div.parent().height() - $(img).height()) / 2;
    div.css({ height: $(img).height(), width: $(img).width(), top: topVal });
}

function destListClearSelections(listID)
{
    var selectedItems;

    if ($("#" + listID).is(".selectableList"))
    {
        selectedItems = $(".selectableListItem");
    }
    else
    {
        selectedItems = $("#" + listID + " .listItemRow");
    }

    $(selectedItems).each(function()
    {
        if ($(this).is(".listItemRowSelected"))
        {
            var list = $(this).closest(".destinationList").get(0);
            var mapID = $(list).attr("mapid");

            $(this).removeClass("listItemRowSelected");
            highlightMapMarker(mapID, $(this).find("#locID").val(), false);

            toggleGearButtonDiv($(this).find(".btnGear"), false);
        }
    });
}

function clickSelectedDest(control, addmedia)
{
    if ($(".tabContent:visible").find(".listItemRowSelected").length == 1)
    {
        var item = $(".tabContent:visible").find(".listItemRowSelected");

        if (!!control && item.attr("addmedia") == "True" && addmedia)
            loadModal('Destination', 'ReviewDestination', item.attr('detailsid'), { tab: 1 }, null, 1);
        else
            $(".tabContent:visible").find(".listItemRowSelected").click();

        return true;
    }
    else if (!!control && $(".tabContent:visible").find(".listItemRow").length == 0)
    {
        loadModal('Destination', 'SuggestDestination', null, { 'actID': $('#actID').val(), 'ctryCode': $('#ctryCode').val(), 'listType': $(control).closest('.listType').attr('listType') }, 660);
        return true;
    }
    else if (addmedia && !!control && $(control).attr("addMedia") == "True")
    {
        loadModal('Destination', 'ReviewDestination', $(control).attr('locID'), { tab: 1 }, null, 1);
        return false;
    }
    else
        return false;
}

function gotoDest(locID)
{
    $.ajax({
        type: "POST",
        url: "/Destination/GetDestinationUrl/",
        data: { locationID: locID },
        success: function(result)
        {
            if (result)
                window.top.location.href = result;
        },
        error: function(result)
        {
            showMessage("An error occured while opening location.", "red");
        }
    });
}

function gotoUrl(url, newWindow)
{
    newWindow = newWindow || false;

    if (newWindow)
        window.open(url);
    else
        window.top.location.href = url;
}

function scrollToReviews(item, id)
{
    var box = $(item).closest("#features").next("#featureReviews");
    var title = box.find("#" + id);

    $(item).parent().children().removeClass("featureReviewTitleSelected");
    $(item).addClass("featureReviewTitleSelected");
    box.children().removeClass("featureReviewTitleSelected");
    title.addClass("featureReviewTitleSelected");

    if (title.length > 0)
    {
        var scroll = title.position().top + box.scrollTop();
        $(box).animate({ scrollTop: scroll }, 500)
    }
}

// DESTINATION LISTS  *** END *** //


// TIMERS  *** START *** //

function pauseTimer(timerID)
{
    if (timers[timerID])
        timers[timerID].stop();
    else if ($(timerID).closest(".timer").length > 0)
    {
        var timerID = $(timerID).closest(".timer").get(0).id;
        timers[timerID].stop();
    }
}

function resumeTimer(timerID, interval)
{
    interval = interval || defaultTimerInterval;

    if (timers[timerID] && !getSlideListIsDetailsMode(timerID))
        timers[timerID].reset(interval);
    else if ($(timerID).closest(".timer").length > 0)
    {
        var timerID = $(timerID).closest(".timer").get(0).id;
        timers[timerID].reset(interval);
    }
}

function killTimer(timerID)
{
    if (timers[timerID])
    {
        try { timers[timerID].stop(); }
        catch (ex) { }

        timers[timerID] = null;
    }
}

jQuery.timer = function(interval, callback)
{
    var interval = interval || 100;

    if (!callback)
        return false;

    _timer = function(interval, callback)
    {
        this.stop = function()
        {
            clearInterval(self.id);
        };

        this.internalCallback = function()
        {
            callback(self);
        };

        this.reset = function(val)
        {
            if (self.id)
                clearInterval(self.id);

            var val = val || 100;
            this.id = setInterval(this.internalCallback, val);
        };

        this.interval = interval;
        this.id = setInterval(this.internalCallback, this.interval);

        var self = this;
    };

    return new _timer(interval, callback);
};

// TIMERS  *** END *** //

function callAction(url, data, success, error, method, type)
{
    if (!data)
        data = {};

    if (!data["loginCallback"])
    {
        var lc = "callAction('" + url + "','" + ($.isPlainObject(data) ? $.param(data) : data) + "','" + success + "','" + error + "','" + method + "','" + type + "');"
        if ($.isPlainObject(data))
            data["loginCallback"] = encodeURIComponent(lc);
    }

    $.ajax({
        type: "GET",
        cache: false,
        url: url,
        data: data,
        success: success || function (result)
        {
            disablePopup();

            if (result.IsJson)
                processFeedback(result);
            else
            {
                showPopup();
                modalPopupContent.html(result);
                setModalTitle();
                centerPopup();
            }
        },
        error: function (result, err, e)
        {
            alertError('callAction');
        }
    });
}

function callFeedbackAction(method, url, data, closePopup, errMsg)
{
    if (!data)
        data = {};

    if (!data["loginCallback"])
    {
        var lc = "callFeedbackAction('" + method + "','" + url + "','" + ($.isPlainObject(data) ? $.param(data) : data) + "'," + closePopup + ",'" + errMsg + "');";
        if ($.isPlainObject(data))
            data["loginCallback"] = encodeURIComponent(lc);
    }

    $.ajax({
        type: method,
        cache: false,
        url: url,
        data: data,
        success: function (result)
        {
            if (result.IsJson)
            {
                processFeedback(result);

                if (typeof (closePopup) === 'undefined' || closePopup === true)
                    disablePopup();
            }
            else
            {
                showPopup();
                modalPopupContent.html(result);
                setModalTitle();
                centerPopup();
            }
        },
        error: function (result)
        {
            if (!errMsg)
                alertError('callFeedbackAction');
            else
                alert(errMsg);
        }
    });
}

function processFeedback(json)
{
    if (json.Callback)
    {
        try
        {
            eval(json.Callback);
        }
        catch (ex)
        {

        }
    }

    if (json.RefreshTabs)
    {
        for (var i = 0; i < json.RefreshTabs.length; i++)
            setRefreshTab(json.RefreshTabs[i]);

        refreshTabs();
    }

    if (json.Description && json.Color)
        showMessage(json.Description, json.Color);

    if (json.Validation)
    {
        var summary = $("#modalValidationSummary");
        $(summary).html("");

        for (var i = 0; i < json.Validation.ErrorList.length; i++)
            $(summary).append("<li>" + json.Validation.ErrorList[i].Message + "</li>");

        $(summary).show();
    }
}

function actionButtonToggle(btn, select)
{
    var selected = select || $(btn).is(".actionButtonSelected");
    resetDetailButtons($(btn).parent());

    if (selected)
    {
        $(btn).removeClass("actionButtonSelected");
        $(btn).attr({ src: "http://" + document.location.host + "/Resources/Images/Buttons/" + ($(btn).is(".btnParent") ? "parent.png" : "comment.png"), alt: ($(btn).is(".btnParent") ? "Associated Destinations" : "My Review"), title: ($(btn).is(".btnParent") ? "Associated Destinations" : "My Review") });
    }
    else
    {
        $(btn).addClass("actionButtonSelected");
        $(btn).attr({ src: "http://" + document.location.host + "/Resources/Images/Buttons/close.png", alt: "Close", title: "Close" });
    }

    return !selected;
}

function resetDetailButtons(btnPanel)
{
    $(btnPanel).find(".detailsButton").each(function ()
    {
        $(this).removeClass("actionButtonSelected");
        $(this).attr({ src: "http://" + document.location.host + "/Resources/Images/Buttons/" + ($(this).is(".btnParent") ? "parent.png" : "comment.png"), alt: ($(this).is(".btnParent") ? "Associated Destinations" : "My Review"), title: ($(this).is(".btnParent") ? "Associated Destinations" : "My Review") });
    });
}

function btnGearClick(btn, locID, listed)
{
    toggleGearButtonDiv(btn, !$(btn).is(".actionButtonSelected"), locID, listed);
}

function toggleGearButtonDiv(btn, selected, locID, listed)
{
    var div = $(btn).closest(".tabContent").find(".gearButtonDiv");

    if (!locID)
        selected = false;

    if (selected)
    {
        var offset = $(btn).offset();
        var height = $(btn).height() + parseInt($(btn).css("padding-top")) + parseInt($(btn).css("padding-bottom"));

        div.offset({ "left": offset.left, "top": (offset.top + height) });
        div.attr({ "locid": locID });

        if (listed == "True")
            $(div).find(".gearButtonUnlisted").hide();
        else
            $(div).find(".gearButtonUnlisted").show();
        
        div.show();

        if ($(btn).closest(".slideListItem").attr("index") >= 8)
        {
            var top = (offset.top - parseInt($(div).height()));
            div.offset({ "top": top });
        }
        
        $(btn).addClass("actionButtonSelected");
    }
    else
    {
        div.hide();
        $(btn).removeClass("actionButtonSelected");
    }
}

function detailsButtonClick(btn, listID, itemNo, detailsPanel)
{
    actionButtonToggle(btn, true);
    toggleGearButtonDiv($(btn).parent().find(".btnGear:first"), false)
    slideToggleDetails(listID, itemNo, detailsPanel);
}

function setRefreshTab(tabButtonId)
{
    $("#" + tabButtonId).attr("refresh", 1);
}

function refreshTabs()
{
    var button = $(".tabSelected .tabButtonFirst");
    if (button.length == 1 && button.attr("refresh") == 1 && (button.attr("unrefreshable") == null || button.attr("unrefreshable") == "False"))
        $(".tabSelected .tabButtonFirst").click();
}


// MEDIA START

function playVideo(control)
{
    var path = $(control).attr("videoUrl");
    var uploaded = $(control).attr("uploaded");

    $("#mainDestinationVideo").html("<input type='hidden' id='VideoUrl' name='VideoUrl' value='" + path + "' />"
                            + "<object id='video' width='495' height='330'>"
                            + "<param name='movie' value='" + path + "' />"
                            + "<param name='allowscriptaccess' value='always' />"
                            + "<param name='allowFullScreen' value='true' />"
                            + "<param name='wmode' value='opaque' />"
                            + "<embed src='" + path + "&autoplay=1'"
                                   + "type='application/x-shockwave-flash'"
                                   + "allowscriptaccess='always'"
                                   + "allowfullscreen='true'"
                                   + "wmode='opaque'"
                                   + "width='495'"
                                   + "height='330'"
                            + "</embed>"
                        + "</object>").show();

    if (uploaded == "True")
        initiateVideo(path, "true");

    $("#mainDestinationVideo").show();
    $(control).closest(".videoPanel").find("#mediaImageCorners").hide();
}

function initiateVideo(url, autoPlay)
{
    if (!!url || $("#videoPlayerDiv").length != 0)
    {
        url = url || $("#VideoUrl").val();
        var so = new SWFObject("../../Flash/mpw_player.swf", "swfplayer", "495", "330", "9", "#000000"); // Player loading
        so.addVariable("flv", "../.." + url); // File Name
        so.addVariable("autoplay", autoPlay || "true");
        so.addParam("wmode", "opaque");
        so.addParam("allowFullScreen", "true");

        if ($("#videoPlayerDiv").length != 0)
            so.write("videoPlayerDiv"); // This needs to be the name of the div id
        else
            so.write("mainDestinationVideo"); // This needs to be the name of the div id
    }

    if (popupStatus)
        centerPopup();
}

// MEDIA END

function suggestDestination(listType)
{
    loadModal('Destination', 'SuggestDestination', null, { 'actID': $('#actID').val(), 'ctryCode': $('#ctryCode').val(), 'listType': listType }, 660);
}

function updateLoginStatus()
{
    $.ajax({
        type: "GET",
        dataType: "html",
        url: "/Account/LoginStatus/",
        cache: false,
        success: function (result) { $("#loginStatus").html(result); },
        error: function (result) { }
    });

    $.ajax({
        type: "GET",
        dataType: "html",
        url: "/Account/MainMenu/",
        cache: false,
        success: function (result) { $("#mainMenuDiv").html(result); },
        error: function (result) { }
    });
}

function initFilterForm(formID)
{
    if ($("#" + formID).length > 0)
    {
        $("#" + formID).ajaxForm(
        {
            beforeSubmit: function()
            {
                $("#" + formID).attr("disabled", "disabled");
            },
            success: function(result)
            {
                if (result)
                {
                    if ($("#" + formID).find("#filter\\.Activity\\.ActivityID").length > 0 && $(result).find("#filter\\.Activity\\.ActivityID").length > 0)
                        $("#" + formID).find("#filter\\.Activity\\.ActivityID").html($(result).find("#filter\\.Activity\\.ActivityID").html()).resetSS();

                    if ($("#" + formID).find("#filter\\.Country\\.CountryCode").length > 0 && $(result).find("#filter\\.Country\\.CountryCode").length > 0)
                        $("#" + formID).find("#filter\\.Country\\.CountryCode").html($(result).find("#filter\\.Country\\.CountryCode").html()).resetSS();

                    if ($("#" + formID).find("#filter\\.Destination\\.LocationID").length > 0 && $(result).find("#filter\\.Destination\\.LocationID").length > 0)
                        $("#" + formID).find("#filter\\.Destination\\.LocationID").html($(result).find("#filter\\.Destination\\.LocationID").html()).resetSS();
                }

                $("#" + formID).removeAttr("disabled");
            },
            error: function(xhr, textStatus, errorThrown)
            {
                $("#" + formID).removeAttr("disabled");
            }
        });
    }
}

function updateSearchPanel(actID, ctryCode, filterItemType)
{
    if (actID == -1)
    {
        loadModal('Destination', 'SuggestActivity', null, null, 500);
        $("#SearchPanelForm").find("#actID").val(0);
        return false;
    }

    $("#SearchPanelForm").attr("disabled", "disabled");

    $.ajax({
        type: "GET",
        dataType: "html",
        url: "/Guide/SearchPanel/",
        data: { actID: actID, ctryCode: ctryCode, filterItemType: filterItemType },
        cache: false,
        success: function(result)
        {
            if (result)
            {
                if ($("#SearchPanelForm").find("#actID").length > 0 && $(result).find("#actID").length > 0)
                    $("#SearchPanelForm").find("#actID").html($(result).find("#actID").html()).resetSS();

                if ($("#SearchPanelForm").find("#ctryCode").length > 0 && $(result).find("#ctryCode").length > 0)
                    $("#SearchPanelForm").find("#ctryCode").html($(result).find("#ctryCode").html()).resetSS();
            }

            $("#SearchPanelForm").removeAttr("disabled");
        },
        error: function(result)
        {
            $("#SearchPanelForm").removeAttr("disabled");
        }
    });
}

function updateUserSearchPanel(actID, ctryCode, filterItemType)
{
    $("#userSearchPanel").attr("disabled", "disabled");

    $.ajax({
        type: "GET",
        dataType: "html",
        url: "/Community/UserSearchPanel/",
        data: { actID: actID, ctryCode: ctryCode, filterItemType: filterItemType },
        cache: false,
        success: function (result)
        {
            if (result)
            {
                if ($("#allMembersActID").length > 0 && $(result).find("#allMembersActID").length > 0)
                    $("#allMembersActID").html($(result).find("#allMembersActID").html()).resetSS();

                if ($("#allMembersCtryCode").length > 0 && $(result).find("#allMembersCtryCode").length > 0)
                    $("#allMembersCtryCode").html($(result).find("#allMembersCtryCode").html()).resetSS();
            }

            $("#userSearchPanel").removeAttr("disabled");
        },
        error: function (result)
        {
            $("#userSearchPanel").removeAttr("disabled");
        }
    });
}

function updateFilterPanel(panel, actID, ctryCode, userID, filterItemType, listType)
{
    $(panel).attr("disabled", "disabled");

    $.ajax({
        type: "GET",
        dataType: "html",
        url: "/Community/FilterPanel/",
        data: { actID: actID, ctryCode: ctryCode, userID: userID, filterItemType: filterItemType, listType: listType },
        cache: false,
        success: function (result)
        {
            if (result)
            {
                if ($(panel).find("#filterActID").length > 0 && $(result).find("#filterActID").length > 0)
                    $(panel).find("#filterActID").html($(result).find("#filterActID").html()).resetSS();

                if ($(panel).find("#filterCtryCode").length > 0 && $(result).find("#filterCtryCode").length > 0)
                    $(panel).find("#filterCtryCode").html($(result).find("#filterCtryCode").html()).resetSS();

                if ($(panel).find("#filterLocID").length > 0 && $(result).find("#filterLocID").length > 0)
                    $(panel).find("#filterLocID").html($(result).find("#filterLocID").html()).resetSS();
            }

            $(panel).removeAttr("disabled");
        },
        error: function (result)
        {
            $(panel).removeAttr("disabled");
        }
    });
}

(function($)
{

    $.fn.extend({

        /**
        * Stores the original version of offset(), so that we don't lose it
        */
        _offset: $.fn.offset,

        /**
        * Set or get the specific left and top position of the matched
        * elements, relative the the browser window by calling setXY
        * @param {Object} newOffset
        */
        offset: function(newOffset)
        {
            return !newOffset ? this._offset() : this.each(function()
            {
                var el = this;

                var hide = false;

                if ($(el).css('display') == 'none')
                {
                    hide = true;
                    $(el).show();
                };

                var style_pos = $(el).css('position');

                // default to relative
                if (style_pos == 'static')
                {
                    $(el).css('position', 'relative');
                    style_pos = 'relative';
                };

                var offset = $(el).offset();

                if (offset)
                {
                    var delta = {
                        left: parseInt($(el).css('left'), 10),
                        top: parseInt($(el).css('top'), 10)
                    };

                    // in case of 'auto'
                    if (isNaN(delta.left))
                        delta.left = (style_pos == 'relative') ? 0 : el.offsetLeft;
                    if (isNaN(delta.top))
                        delta.top = (style_pos == 'relative') ? 0 : el.offsetTop;

                    if (newOffset.left || newOffset.left === 0)
                        $(el).css('left', newOffset.left - offset.left + delta.left + 'px');

                    if (newOffset.top || newOffset.top === 0)
                        $(el).css('top', newOffset.top - offset.top + delta.top + 'px');
                };
                if (hide) $(el).hide();
            });
        }

    });

})(jQuery);


function doIfKey(e, key, doWhat)
{
    var keyCode;
    if (window.event)
        keyCode = window.event.keyCode; // IE
    else
        keyCode = e.which; // Firefox

    if (keyCode == key)
    {
        eval(doWhat);
        return false;
    }
}
