﻿/* Confirm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function confirmDelete(i_string) {
    var str = "Do you really want to delete this item?";
    if (i_string != null)
        str = i_string;
    if (confirm(str)) {
        return true;
    } else {
        return false;
    }
}

function fileBrowserCallBack(field_name, url, type) {
    switch (type) {
        case "image":
            url = "/pages/admin/generic/fileManager/default.aspx";
            break;
        case "file":
            url = "/pages/admin/generic/fileManager/default.aspx";
            break;
    }
    imageBrowserWin = window.open(url, "fileBrowser", "width=780,height=440,status=yes,toolbar=no,scrollbars=yes,resizable=yes");
    document.imageWinFieldname = field_name;
    document.imageWinRef = arguments[3];
    imageBrowserWin.focus();
}

function fileBrowserCallBack_return(fileRef) {
    document.imageWinRef.document.forms[0][document.imageWinFieldname].value = fileRef;
}

/* Config tinyMCE and fire callback function: 'saveContent' on save.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function initContentArea() {
    $('textarea.contentArea').tinymce({
        // Location of TinyMCE script
        script_url: '/scripts/tiny_mce/tiny_mce.js',
        // General options
        theme: "advanced",
        width: "614",
        height: "331",
        plugins: "safari,save,advimage,advlink,inlinepopups,contextmenu,paste",
        // Theme options
        theme_advanced_buttons1: "save,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect",
        theme_advanced_buttons2: "pastetext,|,bullist,numlist,|,undo,redo,|,link,unlink,anchor,image,code,|,forecolor,backcolor,removeformat,|,sub,sup",
        theme_advanced_buttons3: "",
        theme_advanced_buttons4: "",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: false,
        // Example content CSS (should be your site CSS)
        content_css: "/css/tiny_mce.css",
        
        // Drop lists for link/image/media/template dialogs
        //template_external_list_url: "lists/template_list.js",
        //external_link_list_url: "lists/link_list.js",
        //external_image_list_url: "lists/image_list.js",
        //media_external_list_url: "lists/media_list.js",
        file_browser_callback: "fileBrowserCallBack",
        relative_urls: false,
        save_onsavecallback: "saveContent"
    });
}

/* Save tinyMCE content, terminate tinyMCE, update content on page and close modal-window
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function saveContent(sender) {
    var mceContent = $('textarea.contentArea').html();
    $.post("/ajax/admin/content/contentAreaInline.aspx", { Key: $("#hiddenKey").val(), content: mceContent }, function(data) {
        var contentarea_content_wrapper = $('.contentarea input[value=' + $("#hiddenKey").val() + ']').parents('.contentarea').find('.contentarea-content-wrapper');
        contentarea_content_wrapper.html(mceContent);
        $close.trigger('click');
    });
    return false;
}




/* #DOM-READY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
jQuery(function () {

    /* Validate forms
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    // Validate Number
    $('.standard-form').delegate('.number', 'keyup focusout', function () {
        if (/^[0-9]*(\.)?[0-9]+$/.test($(this).val()) || $(this).val() == "") {
            $(this).removeClass('validation-error'); //OK
        }
        else {
            $(this).addClass('validation-error'); //BAD
        }
    });

    // Validate IP-ADDRESS
    $('.standard-form').delegate('.ip', 'keyup focusout', function () {
        if (/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/.test($(this).val()) || $(this).val() == "") {
            $(this).removeClass('validation-error'); //OK
        }
        else {
            $(this).addClass('validation-error'); //BAD
        }
    });

    // Validate Email-ADDRESS
    $('.standard-form').delegate('.email', 'keyup focusout', function () {
        if (/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i.test($(this).val()) || $(this).val() == "") {
            $(this).removeClass('validation-error'); //OK
        }
        else {
            $(this).addClass('validation-error'); //BAD
        }
    });

    $('body').addClass('js-enabled');


    /* #DROPDOWN-MENU
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    $('.navigation > ul > li').each(function () {
        var $this = $(this);
        if ($this.find('.submenu').length > 0) {
            $this.append('<a class="arrow" />').addClass('has-submenu').find('.submenu').css({ minWidth: $this.width() });
        }
    });

    $('.has-submenu .arrow').bind('mouseenter', function () {
        $(this).parents('.has-submenu').addClass('sub-visible');
    });

    $('.has-submenu').bind('mouseleave', function () {
        $(this).removeClass('sub-visible');
    });


    /* #SELECT-BOX JS
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    // Add necessary elements for each select-box
    $('.select').each(function () {
        $(this).add('<span class="select-overlay" />')
		.wrapAll('<span class="select-wrapper" />');
    });

    // Set initial text in each overlay
    var parent_select = "";
    $('.select-overlay').each(function () {
        parent_select = $(this).parents('.select-wrapper').find('select');
        $(this)
			.width(parent_select.outerWidth())
			.height(parent_select.outerHeight())
			.text(parent_select.find(':selected').text());
    });

    // Change text in overlay on change
    $('.select').bind('change.value', function () {
        $(this).next().text($(this).find(':selected').text());
    });

    // Add focus-style
    $('.select').bind('focus', function () {
        $(this).parents('.select-wrapper').addClass('focus');
    });
    $('.select').bind('blur', function () {
        $(this).parents('.select-wrapper').removeClass('focus');
    });

    // Let the user use keys to change selectbox-value
    $('.select').bind('keyup', function (e) {
        var key = e.charCode || e.keyCode || 0;
        if (key == 40 || key == 38) {
            $(this).trigger('change.value');
        }
    });

    /* Enable Mark All button
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
    $("#chkAll").click(function () {
        $affectedRows = $(".datatable tbody input:checkbox");
        if ($(this).attr("checked") == true) {
            $affectedRows.attr("checked", true);
            for (i = 0; i < $affectedRows.length; i++) {
                gMarkedIds.push($affectedRows[i].id.substring(3));
            }
        }
        else {
            $affectedRows.removeAttr("checked");
            for (i = 0; i < $affectedRows.length; i++) {
                var idx = gMarkedIds.indexOf($affectedRows[i].id.substring(3)); // Find the index
                if (idx != -1)
                    gMarkedIds.splice(idx, 1);
            }
        }
    });

    /* Enable Mark Single button
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
    $(".datatable tbody input:checkbox").live("click", function () {
        if ($(this).attr("checked") == true) {
            gMarkedIds.push($(this).attr("id").substring(3));
            $affectedRows = $(".datatable tbody input:checkbox:not(:checked)");
            if ($affectedRows.length == 0)
                $("#chkAll").attr("checked", true);
        } else {
            var idx = gMarkedIds.indexOf($(this).attr("id").substring(3)); // Find the index
            if (idx != -1)
                gMarkedIds.splice(idx, 1);
            $("#chkAll").removeAttr("checked");
        }
    });

    /*
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    /* #DISABLE SUBMIT BUTTONS ON FORM SUBMIT, TO PREVENT DOUBLE POST
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    /*$('form').submit(function(){
    $('[type=submit]').attr('disabled', 'disabled');
    });*/
    // The above is commented about because it broke all submits.


    /* #TOGGLE FEEDBACK
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    $('.feedback').hide().each(function () {
        var feedback = $(this);
        var feedback_close = $('<a />', {
            href: '#',
            'class': 'feedback-close',
            html: '&times;',
            click: function () {
                $(this).parents('.feedback').css('visibility', 'hidden');
                return false;
            }
        }).appendTo(feedback);
    });
    $('#toggle-feedback').bind('click', function () {
        $('.feedback').toggle();
    });

    /* #CONTENT AREA EDIT */
    $('.contentarea .button-edit').bind('click', function (e) {
        var contentKey = $(this).parents('.contentarea').find(".contentId").val();
        $.post("/Ajax/Admin/Content/ContentAreaInline.aspx", { key: contentKey }, function (data) {
            $.fn.modalwindow({
                html: data,
                openX: e.pageX,
                openY: e.pageY,
                theme: 'tinymce',
                onOpen: initContentArea
            });
        });
        return false;
    });

    /*
    */
    $(".btn-delete").live("click", function () {
        if (confirmDelete(Language["Generic.ConfirmDelete"])) {
            // cleara selectade ids
            $theTr = $(this).parent().parent();
            theId = $theTr.find("td:eq(1)").html();
            $theTr.addClass("removing");
            idx = gMarkedIds.indexOf(theId);
            if (idx != null)
                gMarkedIds.splice(idx, 1);
            $.post(gAjaxFolder + "delete.aspx", { id: theId }, function (data) {
                $theTr.animate({ backgroundColor: "#ff0000" }, 1000, function () {
                    $(this).removeClass("removing").animate({ backgroundColor: "#ff0000" }, 500, function () {
                        $(this).remove();
                        updatePaging();
                    });
                });
            });
        }
        return false;
    });

    $(".btn-trash").live("click", function () {
        if (confirmDelete(Language["Generic.ConfirmMoveToTrash"])) {
            // cleara selectade ids
            $theTr = $(this).parent().parent();
            theId = $theTr.find("td:eq(1)").html();
            $theTr.addClass("removing");
            idx = gMarkedIds.indexOf(theId);
            if (idx != null)
                gMarkedIds.splice(idx, 1);
            $.post(gAjaxFolder + "trash.aspx", { id: theId }, function (data) {
                $theTr.animate({ backgroundColor: "#ff0000" }, 1000, function () {
                    $(this).removeClass("removing").animate({ backgroundColor: "#ff0000" }, 500, function () {
                        $(this).remove();
                        updatePaging();
                    });
                });
            });
        }
        return false;
    });

    $(".btn-copy").live("click", function () {
        theId = $(this).parent().parent().find("td:eq(1)").html();
        $.post(gAjaxFolder + "copy.aspx", { id: theId }, function (data) {
            $(".datatable tbody").append(data);
            $(".new-copy td").animate({ backgroundColor: "#ff0000" }, 2000, function () {
                $(this).parent().removeClass("new-copy");
            });
        });
        return false;
    });
    $(".trash-bin").click(function () {
        if (confirmDelete(Language["Generic.ConfirmEmptyTrash"])) {
            $theImg = $(this);
            $.post("empty.aspx", function (data) {
                $theTr = $(".datatable tbody tr");
                gMarkedIds = new Array();
                $theTr.addClass("removing");
                $theTr.animate({ backgroundColor: "#ff0000" }, 1000, function () {
                    $(this).removeClass("removing").animate({ backgroundColor: "#ff0000" }, 500, function () {
                        $(this).remove();
                        updatePaging();
                        $theImg.attr("src", "/assets/gfx/admin/icon_trashcan_empty.png");
                    });
                });
            });
        }
    });

    /* Admin page click buttn
    ~~~~~~~~~~~~~~~~~~~~*/
    $("#performMeasure").click(function () {
        var measure = $("#measure").val();
        doMeasure = true;
        if (measure.indexOf("empty") != -1) {
            doMeasure = confirmDelete(Language["Generic.ConfirmEmptyTrash"]);
        }
        else {
            if (gMarkedIds.length == 0) {
                doMeasure = false;
                alert(Language["Generic.NoCheckboxesMarked"]);
            }
            else {
                if (measure.indexOf("delete") != -1) {
                    doMeasure = confirmDelete(Language["Generic.ConfirmDelete"]);
                }
                else if (measure.indexOf("trash") != -1) {
                    doMeasure = confirmDelete(Language["Generic.ConfirmMoveToTrash"]);
                }
            }
        }
        if (doMeasure) {
            // Add loader
            var loader = $('<span class="perform-loader" />').insertAfter('#performMeasure');

            var markedIds = "";
            for (var i = 0; i < gMarkedIds.length; i++) {
                if (i != 0)
                    markedIds += ",";
                markedIds += gMarkedIds[i];
            }

            $.post(measure, { ids: markedIds }, function (data) {
                // cleara selectade ids
                if (measure.indexOf("empty") != -1) {
                    $(".trash-bin").attr("src", "/assets/gfx/admin/icon_trashcan_empty.png");
                    $theTr = $(".datatable tbody tr");
                    $theTr.addClass("removing");
                    $theTr.animate({ backgroundColor: "#ff0000" }, 1000, function () {
                        $(this).removeClass("removing").animate({ backgroundColor: "#ff0000" }, 500, function () {
                            $(this).remove();
                            gMarkedIds = new Array();
                            updatePaging();
                        });
                    });
                }
                else if (measure.indexOf("delete") != -1 || measure.indexOf("trash") != -1) {
                    for (var i = 0; i < gMarkedIds.length; i++) {
                        $theTr = $(".datatable tbody tr#post" + gMarkedIds[i]);
                        $theTr.addClass("removing");
                        $theTr.animate({ backgroundColor: "#ff0000" }, 1000, function () {
                            $(this).removeClass("removing").animate({ backgroundColor: "#ff0000" }, 500, function () {
                                $(this).remove();
                                updatePaging();
                            });
                        });
                    }
                    gMarkedIds = new Array();
                }
                else {
                    $(".datatable tbody").append(data);
                    $(".new-copy td").animate({ backgroundColor: "#ff0000" }, 2000, function () {
                        $(this).parent().removeClass("new-copy");
                        updatePaging();
                    });
                }
                loader.remove();
            });
        }
        return false;
    });
    /*
    $("#flipTrash").click(function () {
    $.getJSON(gPagingPage, { pageSize: gPageSize }, function (data) {
    preparePageing(data.total_pages, data.total_posts, gPostsPage);
    loadData(0, gPostsPage, gPageSize);
    });
    return false;
    });*/
});

function updatePaging() {
    if ($(".datatable tbody tr").length < 1) {
        $("#chkAll").removeAttr("checked");
        $.getJSON(gPagingPage, { pageSize: gPageSize, filter:gFilter }, function (data) {
            preparePageing(data.total_pages, data.total_posts, gPostsPage);
        });
    }
}

function loadData(page_index, in_page, in_pageSize, in_filter) {
    if (in_pageSize == null) {
        in_pageSize = 10;
    }
    if (in_filter == null) {
        in_filter = "";
    }
    if (in_page != null) {
        // Apply loader to the table
        $("fieldset tbody").html('<tr class="pageing-loader"><td colspan="' + $("fieldset thead th").length + '"><img src="/assets/gfx/loader.gif" width="24" height="24" style="display:block;margin:0 auto;" /></td></tr>');

        //alert("loading data" + in_page + " page index: " + page_index + " in_pageSize " + in_pageSize + " filter: " + in_filter);
        $("fieldset tbody").load(in_page, { pageIndex: page_index, pageSize: in_pageSize, filter: in_filter }, function () {
            $affectedRows = $(".datatable tbody input:checkbox");
            allAreChecked = true;
            for (i = 0; i < $affectedRows.length; i++) {
                var idx = gMarkedIds.indexOf($affectedRows[i].id.substring(3));
                if (idx != -1)
                    $affectedRows[i].checked = true;
                else
                    allAreChecked = false;
            }
            $("#chkAll").attr("checked", allAreChecked);
        });
    } else {
        alert("file not found");
    }
}

//var gTotPages = 1;

function showPaging(in_pageIndex, in_totPages) {
    
    paging_container = $('.paging');
    paging_container.html("");
    paging_elements = "";
    if (in_pageIndex != 1) {
        paging_elements += '<a href="#" class="paging-first">' + Language["Paging.First"] + '</a>';
        paging_elements += '<a href="#" class="paging-prev">' + Language["Paging.Previous"] + '</a>';
    }

    var startPage = in_pageIndex - 4; // visa max fyra föregående
    if (startPage < 1)
        startPage = 1;
    

    var stopPage = parseInt(in_pageIndex) + 1 + 5; // visa fem framåt
    if (startPage == 1)
        stopPage = 1 + 10; // visa 10 totalt
    //alert("startpage:" + startPage + " stoppage: " + stopPage);
    // Skriv ut alla paging-länkar
    for (var i = startPage; (i-1 < in_totPages && i < stopPage); i++) {
        if (in_pageIndex != i)
            paging_elements += '<a href="#">' + i + '</a>';
        else
            paging_elements += '<a href="#" class="current">' + i + '</a>';
    }
    if (in_pageIndex != in_totPages && in_totPages > 1) {
        paging_elements += '<a href="#" class="paging-next">' + Language["Paging.Next"] + '</a>';
        paging_elements += '<a href="#" class="paging-last">' + Language["Paging.Last"] + '</a>';
    }

    paging_container.append(paging_elements);
}

function preparePageing(tot_pages, tot_posts, in_page) {
    gTotPages = tot_pages;
    var posts_per_page = Math.ceil(tot_posts / gTotPages);
    paging_container = $('.paging');

    showPaging(1, gTotPages);

    // Binda varje länk till att hämta rätt page
    paging_container.delegate('a', 'click', function () {
        var page_index = $(this).html(); // "1" har page_index 0, "2" har page_index 1 osv... (kan bli lite rörigt)
        if (!isNumeric(page_index)) {
            var theClass = $(this).attr("class");
            if (theClass == "paging-prev") {
                page_index = $(this).parent().find(".current").prev().html();
            }
            else if (theClass == "paging-next") {
                page_index = $(this).parent().find(".current").next().html();
            }
            else if (theClass == "paging-first") {
                page_index = 1;
            }
            else if (theClass == "paging-last") {
                page_index = gTotPages;
            }

        }
        showPaging(page_index, gTotPages);
        loadData(page_index - 1, in_page, gPageSize, gFilter);

        return false;
    });
}

function isNumeric(n) {
    return n && n.constructor === Number;
}

// global vars
var gMarkedIds = new Array();

var gAjaxFolder = "";

var gPagingPage = "";

var gPostsPage = "";

var gPageSize = 10;

var gFilter = "";

var gTotPages = 0;
