﻿var activePopup = null;
if (typeof (onReadyCallbacks) == 'undefined') {
    onReadyCallbacks = [];
}

function initPage() {
    checkBrowser();
    $(".menu table td").hover(
      function () {
          if ($(this).hasClass('selected') == false) {
              $(this).addClass('hover');
          }

          $('.dropdown', this).show();
      }
    , function () {
        $(this).removeClass('hover');

        $('.dropdown', this).hide();
    });

    $(".account_widget .account_menu").hover(
      function () {
          $('.dropdown', this).show();
      }
    , function () {
        $(this).removeClass('hover');

        $('.dropdown', this).hide();
    });


    $(".menu table td").click(function (e) {
       

        var link = $("a:first", this).attr('href');
        if (link.length > 0 && link[0] == '/') {
            window.location.href = link;
        }
    });
   

    $("a.endowment").click(function () {
        openStandardPopup({Title : 'About Jovian Endowment', Width : 650}, 'endowment');
    });

    $('table.form').each(function () {
        $('tr:odd', this).addClass('alternate');
        $('tr:first', this).addClass('first');
        $('tr:last', this).addClass('last');
    });

    $('a.submit').click(function (e) {
        e.preventDefault();

        $(this).parents('form').get(0).submit();
    });

    $('#copyright_year_label').text(new Date().getFullYear());

    $('#search_box').focus(function () {
  
        if ($(this).val() == "search for products") {
            $(this).val('');
        }

        $(this).removeClass('inactive');
    });

    $('#search_box').blur(function () {

        if ($(this).val().trim() == "") {
            $(this).val('search for products');
            $(this).addClass('inactive');
        }
    }).keyup(function (event) {
        if (event.keyCode == 13) {
            $("#search_button").click();
        }
    });

    $('#search_button').click(function (e) {
        e.preventDefault();
        var query = $('#search_box').val().trim();
        if (query == '') return;

        document.location.href = '/Search?term=' + encodeURIComponent(query);
    });

    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('a.submit.default').click();
            return false;
        } else {
            return true;
        }
    });

    if (onReadyCallbacks.length > 0) {

        for (var i = 0; i < onReadyCallbacks.length; i++) {

            try {
                onReadyCallbacks[i]();
            } catch (e) {
            }
        }
    }
}


function setSelectedMenuItem(key) {
    $(".menu td[data-key='" + key + "']").addClass('selected');
}



function openPopup(cfg) {

    if (activePopup != null) closePopup();
    
    var defaults = {

        Title: '',
        Url: null,
        Html : null,
        Modal: false,
        Draggable: false,
        Resizable: true,
        Maximize: false,
        Center: true,
        Width: null,
        Height: null,
        OnClose: null,
        OnLoad: null
    };

    cfg = $.extend(defaults, cfg);
    
    activePopup = $.telerik.window.create({
        title: cfg.Title,
        html: (cfg.Html) ? cfg.Html : '<iframe src="' + cfg.Url + '" frameborder="0" style="width:100%;height:100%"></iframe>',
        modal: cfg.Modal,
        resizable: cfg.Resizable,
        draggable: cfg.Draggable,
        width: cfg.Width,
        height: cfg.Height,
        onClose: function () {

            var data = $(this).data('tWindow');

            if (data.reloadOnClose) {
                window.location.reload();
            }

            if (cfg.OnClose != null) {
                cfg.OnClose($(this));
            }
        },
        onLoad: function () {

            if (cfg.Center) {
                $(this).data('tWindow').center();
            }

            if (cfg.Maximize) {
                $(this).data('tWindow').maximize();
            }

            if (cfg.OnLoad != null) {
                cfg.OnLoad($(this));
            }
        }
    });
}

function openErrorPopup(cfg) {

    openStandardPopup(cfg, 'error');
}

function openAlertPopup(cfg) {

    openStandardPopup(cfg, 'alert');
}

function openInfoPopup(cfg) {

    openStandardPopup(cfg, 'info');
}

function openSuccessPopup(cfg) {

    openStandardPopup(cfg, 'success');
}

function openStandardPopup(cfg, template) {

    var windowCfg = {
        Title: cfg.Title,
        Html: $('.dialog_template.' + template).html(),
        Modal: true,
        Center: true,
        Width: (cfg.Width ? cfg.Width : 300),
        Draggable: false,
        Resizable: false,
        OnLoad: function (popup) {
            $("div.content", popup).html(cfg.Html);

            $("button.close_btn", popup).click(function () {
                closePopup();
            });

            $("a.close_btn", popup).click(function (e) {
                e.preventDefault();
                closePopup();
            });
        }
    };
    
    if (cfg.RedirectUrl) {

        windowCfg.OnClose = function (popup) {
            window.location.href = cfg.RedirectUrl;
        }

    } else if (cfg.OnClose) {

        windowCfg.OnClose = function (popup) {           
            cfg.OnClose();
        }
    }

    openPopup(windowCfg);
}


function closePopup() {
    activePopup.data('tWindow').close();
    activePopup = null;
}

function refreshOnPopupClose() {
    activePopup.data('tWindow').reloadOnClose = true;
}

function redirectOnPopupClose(id) {
    activePopup.data('tWindow').newItemId = id;
    activePopup.data('tWindow').redirectOnClose = true;
}

function getTreeViewSelectedValue(treeViewId) {
    var treeview = $('#' + treeViewId);
    var selectedItem = treeview.find('.t-state-selected').closest('.t-item');
    return treeview.data('tTreeView').getItemValue(selectedItem);
}

function getDropdownListSelectedValue(comboId) {
    var combo = $('#' + comboId);
    return combo.data('tDropDownList').value();        
} 

function convertLineBreaksToParagpraphs(input) {    
    return '<p>' + input.split('\n').join('</p><p>') + '</p>';
}

function launchFile(file) {

    logFileLaunch(file);
    
    if (file.Type == "Video") {
        launchVideoPlayer(file);
    }
    else if (file.Type == "Audio") {
        launchAudioPlayer(file);
    } else {
        downloadFile(file);
    }    
}

function logFileLaunch(file) {

    var fileKey = null;

    if (file.Type == "Video") {
        fileKey = file.Name + ".video";
    }
    else if (file.Type == "Audio") {
        fileKey = file.Name + ".audio";
    } else {
        var name = file.Path;
        name = name.substring(name.lastIndexOf('/') + 1);
        fileKey = name.substring(0, name.indexOf('?'));
    }

    if (fileKey != null) {
        try {
            _gaq.push(['_trackPageview', fileKey]);
        } catch (e) {
        }
    }
}

function launchVideoPlayer(file) {

    var windowCfg;
    var html;

    if (file.IsEmbedCode) {

        html = '<div id="video">' + file.Path + '</div>';

        if (file.EnableFacebookIntegration && file.DirectUrl != null) {
            file.DirectUrl = file.DirectUrl.replace('localhost:56376', 'www.jovianarchive.com');
            html += '<div class="video_player_toolbar"><iframe src="//www.facebook.com/plugins/like.php?href=' + escape(file.DirectUrl) + '&amp;send=false&amp;layout=standard&amp;width=400&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:400px;height:40px" allowTransparency="true"></iframe></div>';
        }
               
        windowCfg = {
            Title: (file.Title != null) ? file.Title : 'Now playing : ' + file.Name,
            Html: html,
            Modal: true,
            Center: true,
            Draggable: false,
            Resizable: false,
            OnClose: function (popup) {
                $('#video').remove();
            }
        };

    } else {

        file.Path = escapeMediaPathForStreaming(file.Path);
        html = '<div id="video" style="display:block;width:640px;height:480px;" href="' + file.Path + '"></div>';

        if (file.EnableFacebookIntegration && file.DirectUrl != null) {
            file.DirectUrl = file.DirectUrl.replace('localhost:56376', 'www.jovianarchive.com');
            html += '<div class="video_player_toolbar"><iframe src="//www.facebook.com/plugins/like.php?href=' + escape(file.DirectUrl) + '&amp;send=false&amp;layout=standard&amp;width=400&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:400px;height:40px" allowTransparency="true"></iframe></div>';
        }

        windowCfg = {
            Title: (file.Title != null) ? file.Title : 'Now playing : ' + file.Name,
            Html: html,
            Modal: true,
            Center: true,
            Width: 640,
            Draggable: false,
            Resizable: false,
            OnLoad: function (popup) {
                $f("video", "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf");
            },
            OnClose: function (popup) {
                $('#video').remove();
            }
        };
    }

    openPopup(windowCfg);
}

function launchAudioPlayer(file) {

    file.Path = escapeMediaPathForStreaming(file.Path);

    var html = '<div id="audio" style="display:block;width:450px;height:30px;" href="' + file.Path + '"></div>';

    if (file.EnableFacebookIntegration && file.DirectUrl != null) {
        file.DirectUrl = file.DirectUrl.replace('localhost:56376', 'www.jovianarchive.com');
        html += '<div class="video_player_toolbar"><iframe src="//www.facebook.com/plugins/like.php?href=' + escape(file.DirectUrl) + '&amp;send=false&amp;layout=standard&amp;width=400&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:400px;height:40px" allowTransparency="true"></iframe></div>';
    }

    var windowCfg = {
        Title: (file.Title != null) ? file.Title : 'Now playing : ' + file.Name,
        Html: html,
        Modal: true,
        Center: true,
        Width: 450,
        Draggable: false,
        Resizable: false,
        OnLoad: function (popup) {
            $f("audio", "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", {

                // fullscreen button not needed here
                plugins: {
                    controls: {
                        fullscreen: false,
                        height: 30,
                        autoHide: false
                    }
                }
            });
        },
        OnClose: function (popup) {
            $('#audio').remove();
        }
    };

    openPopup(windowCfg);
}

function downloadFile(file) {

    document.location.href = file.Path;
}

function escapeMediaPathForStreaming(path) {

    var querySep = path.indexOf('?');

    if (querySep == -1) {
        return path;
    }

    var query = path.substring(querySep+1);
    if (query.length == 0) {
        return path;
    }

    path = path.substring(0, querySep);
    query = encodeURIComponent(query);    

    return path + '?' +query; 
}

function addToCart(cfg) {

    $.ajax({
        url: '/Cart/Add',
        type: 'POST',
        data: JSON.stringify(cfg.product),
        dataType: 'text json',
        contentType: 'application/json; charset=utf-8',
        success: function (result) {

            if (cfg.progressImg) cfg.progressImg.hide();
            if (cfg.btn) cfg.btn.show();

            if (result.Success) {

                updateCartSummary(result.ItemsCount, result.Total, result.Summary);
                showItemAddedPopup(result.ProductQuantityUpdated);

            } else {

                alert('fail');
            }
        }
    });
}


function _addToCart(data, btn, progressImg) {

    $.ajax({
        url: '/Cart/Add',
        type: 'POST',
        data: JSON.stringify(data),
        dataType: 'text json',
        contentType: 'application/json; charset=utf-8',
        success: function (result) {

            if (progressImg) progressImg.hide();
            if (btn) btn.show();

            if (result.Success) {

                updateCartSummary(result.ItemsCount, result.Total, result.Summary);
                showItemAddedPopup(result.ProductQuantityUpdated);

            } else {

                alert('fail');
            }
        }
    });
}


function showItemAddedPopup(productQuantityUpdated) {

    var html;

    if (productQuantityUpdated) {
        html = "This item was already present in your shopping cart and so it's quantity has been incremented";
    } else {
        html = "The item has been added to your shopping cart.";
    }

    html += "<p>You can <a href='/Cart'>proceed to checkout now</a> or close this popup and continue browsing the site.</p>";
    html += "<p>A summary of the items in your shopping cart will continue to be displayed on the top right corner of the page.</p>";

    openSuccessPopup({
        Title: 'Shopping cart updated',
        Html: html,
        Width: 500
    });

}

function hideCartSummary() {

    $('.cart_widget').hide();
}

function updateCartSummary(itemNum, total, summary) {

    if (itemNum < 1) {
        hideCartSummary();
        return;
    }

    var text = itemNum + ' item';
    if (itemNum > 1) text += 's';
    text += ', ' + total;
    
    $('.cart_widget .cart_link').text(text);

    if (summary) {        
        var tooltip = "Cart Total: " + total + "Items in your cart: \n\n " + summary + " \n\n click now to go to the Cart / Checkout page\n";
        $('.cart_widget .cart_link').attr('title', tooltip);
    }

    $('.cart_widget').show();
}

function checkBrowser() {
    
    if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
        
        openAlertPopup({
            Title: 'Browser compatibility alert',
            Width:500,
            Html: '<p>Your browser appears to be outdated and you may encounter some difficulties while browsing this website.</p><p>To enjoy this website as intended we recommend you update your browser to a more recent version.</p>'
        });
    }
}


