// Pixorial Admin Scripts
// Built on the jQuery Library
// Author: Miroslav Wiesner
// Date: December 14th, 2007
// Version: 0.1b

function searchLink() {
    $("#search-form input.textfield").after("<a href='' class='search-submit'>Search</a>");
    $("#search-form a").click(function() {
        this.parentNode.submit();
        return false;
    });
}

// For all forms replace the submit and reset buttons with anchor tags so we can stylize across all browsers.
// For forms you don't want this to work wth use the settings.exceptions array in your call.

$.fn.extend({
    reset: function() {
        return this.each(function() {
            $(this).is('form') && this.reset();
        })
    }
});

( function() {
    jQuery.fn.formButtons	= function(options) {
        var forms		= this;
        var settings	= {
            exceptions: []
        };
        $.extend(settings, options);
        var e		= settings.exceptions;
        var eLen	= e.length;
        for(var i = 0; i < eLen; i++) {
            $("#" + e[i]).addClass("except");
        }
        return forms.not(".except").each(function() {
            $(this).find("input[@type=submit]").each(function() {
                $(this).before("<a href='' class='submit'>" + $(this).val() + "</a>");
            });
            $(this).find("input[@type=reset]").each(function() {
                $(this).before("<a href='' class='reset'>" + $(this).val() + "</a>");
            });
            $(this).find("a.submit").click(function(e) {
                e.preventDefault();
                var onsubmit = $(this).parents("form").attr('onsubmit');
                if(onsubmit) {
                    switch(typeof onsubmit) {
                        case "string":
                            eval(onsubmit);
                            break;
                        case "function":
                            onsubmit();
                            break;
                    }
                }
                else {
                    $(this).parents("form").submit();
                }
            });
            $(this).find("a.reset").click(function(e) {
                e.preventDefault(); $(this).parents("form").reset();
            });
        });
    }
}) (jQuery);


// Return the value of all textfields to their default in the case where a they are blank onBlur
// call the function with the class of the inputs you wish to affect ie. swapDefault("my_class")
function swapDefault(clss) {
    $("input." + clss).each(
        function() {
            $(this).focus(
                function() {
                    if(this.defaultValue && this.value == this.defaultValue) this.value = "";
                }
                ).blur(function() {
                if(this.defaultValue && !this.value.length) this.value = this.defaultValue;
            }
            );
        });
}

// Open a new window for links with the attribute rel="external"
function targetLinks() {
    $("a[@rel=external]").click(function() {
        window.open(this.href);
        return false;
    });
}

// Remove useless whitespace from all unordered lists in a page
function cleanLists() {
    $("ul").each(function() {
        var node	= this.firstChild;
        while(node) {
            var nextNode	= node.nextSibling;
            if(node.nodeType == 3 && !/\S/.test(node.nodeValue))
                this.removeChild(node);
            node	= nextNode;
        }
        return this;
    });
}

// Allow carriage return to work in IE7
function focusField() {
    $("input[@type=text]").each(function() {
        var onsubmit = $(this).parents("form").attr('onsubmit');
        $(this).focus(function() {
            $(this).addClass("focus");
            // make the Enter/Return key submit the form in IE7
            $(this).keydown(function(e) {
                if(e.keyCode == 13) {
                    if(onsubmit) {
                        eval(onsubmit);
                    }
                    else {
                        $(this).parents("form").submit();
                    }
                    return false;
                }
            });
        }).blur(function() {
            $(this).removeClass("focus");
        });
    });
    $("input[@type=password]").each(function() {
        var onsubmit = $(this).parents("form").attr('onsubmit');
        $(this).focus(function() {
            $(this).addClass("focus");
            // make the Enter/Return key submit the form in IE7
            $(this).keydown(function(e) {
                if(e.keyCode == 13) {
                    if(onsubmit) {
                        eval(onsubmit);
                    }
                    else {
                        $(this).parents("form").submit();
                    }
                    return false;
                }
            });
        }).blur(function() {
            $(this).removeClass("focus");
        });
    });
}

// Table Plugin
// Interactions for our Generic Table Behaviour in Pixorial Admin

( function() {
    jQuery.fn.tableMagic	= function(options) {
        var tables		= this;
        var settings	= {
            type : 0, // 0 = default, 1 = messages, type: 2 = news, type 3 = contacts etc etc
            sortable : true,
            sortColumn : 0,
            sortOrder : 0,
            hasState : false,
            hasText : false,
            stateColumn : null,
            expText : "read more",
            colText : "hide detail",
            expandable : true
        };

        $.extend(settings, options);

        return tables.each(function() {

            // define a TR with content
            var row	= $(this).not(".empty").children("tbody").children("tr");

            // define the number of columns by counting TH tags
            var ln	= $(this).find("th").length;

            // create our row icons
            $(this).find("td:first-child").addClass("icon");

            if(settings.sortable == true) {
                $(this).tablesorter({
                    sortList:[[settings.sortColumn,settings.sortOrder]]
                });
                $(this).find("th").click(function() {
                    $(this).parents("table").find("tr").removeClass("active");
                    $(this).parents("table").find("tr.detail").remove();
                });
            }

            // if the table uses read/unread status
            if(settings.hasState == true) {
                row.each( function() {
                    $(this).children("td:eq(" + settings.stateColumn + ")").addClass("status");
                });
            }

            // if the table has supporting text for expanding/collapsing
            if(settings.hasText == true) {
                row.each( function() {
                    $(this).children("td:eq(" + settings.stateColumn + ")").append("<span>[ " + settings.expText + " ]</span>");
                });
            }

            row.hover(function() {
                $(this).addClass("hover");
            },
            function() {
                $(this).removeClass("hover");
            });

            if(settings.expandable) {
                row.not(".detail").click(function() {

                    // define a callBack in order to queue effects
                    var killDetail	= function() {
                        $(this).parents("tr.detail").remove()
                    };

                    if( this.className.match("active") ) {
                        $(this).next("tr.detail").find("div:eq(0)").css("backgroundColor","#f4f4f4").animate({
                            height: 'hide',
                            opacity: 'hide'
                        }, killDetail )

                        $(this).removeClass("active").addClass("hover");

                        // if the table has supporting text for expanding/collapsing
                        if(settings.hasText == true)
                            $(this).children("td:eq(" + settings.stateColumn + ")").children("span").text("[ " + settings.expText + " ]");

                    }
                    else {
                        var detail	= $(this).find("div:eq(0)").html();

                        var content	= "<tr class='detail'><td colspan='" + ln + "'><div style='display:none'><div class='clfx'>" + detail + "</div></div></td></tr>";
                        $(this).removeClass("hover").addClass("active").after(content);

                        // type specific functions HERE AS PLACEHOLDERS FOR NOW

                        // messages
                        if(settings.type == 1) { /* insert custom functions for the messages table */ }

                        // news
                        if(settings.type == 2) { /* insert custom functions for the news table */ }

                        // contacts
                        if(settings.type == 3) {
                            contactsControls($(this).next("tr.detail"));
                        }

                        // masters
                        if(settings.type == 4) {
                            mastersControls($(this).next("tr.detail"));
                        }

                        // shows
                        if(settings.type == 5) {
                            showsControls($(this).next("tr.detail"));
                        }

                        // distributions
                        if(settings.type == 6) {  }

                        // customers
                        if(settings.type == 7) {  }


                        $(this).next("tr").find("div:eq(0)").animate({
                            height: 'show',
                            opacity: 'show'
                        })

                        // if the table uses read/unread status +++ this is also where you would send "READ" the flag back to the DB
                        if(settings.hasState == true) {
                            if(this.className.match("unread")) {
                                $.ajax({
                                    type: "GET",
                                    url: "/home/mark_as_read/" + $(this).attr("id")
                                });
                            }
                            $(this).removeClass("unread").children("td:eq(" + settings.stateColumn + ")").children("span").text("[ " + settings.colText + " ]");
                        }
                    }
                });
            }
        });
    }
} )(jQuery);

// Modal Dialogs

function contactsControls(detail) {
    rowID = detail.find("address:eq(0)").parents("tr").prev("tr").find("div:eq(0)").attr("id");
    if(rowID == "0") {
        detail.find("address:eq(0)").after("<ul class='ctrl'><li><strong>Account Owner</strong><br/>For alternate shipping address<br/>click on Add Address below.</li><li><a href='' id='edit_customer_info'>Edit Address</a></li><li><a id='view' href='' class='view_shares'>View Shares</a></li></ul>");
        detail.find("ul.ctrl").find("a.view_shares").modalDialog({
            uniqueID: rowID,
            width: 400,
            type: "view_shares",
            controller: "shop"
        }).end().find("#edit_customer_info").modalDialog({
            controller: "account",
            params: {
                requirement : contact_requirement,
                no_select : false
            }
        });
    }
    else {
        detail.find("address:eq(0)").after("<ul class='ctrl'><li><a id='edit_contact' href='' class='edit'>Edit Address</a></li><li><a href='' class='destroy'>Delete Address</a></li><li><a id='view' href='' class='view_shares'>View Shares</a></li></ul>");
        detail.find("ul.ctrl").find("a").each(function() {
            // var rowID     = $(this).parents("tr").prev("tr").find("div:eq(0)").attr("id");
            var formType  = $(this).attr("class");
            if(formType == "edit") {
                $(this).modalDialog({
                    uniqueID: rowID,
                    width: 212,
                    type: formType,
                    controller: "contacts",
                    params: {
                        requirement : contact_requirement,
                        no_select : $('#addresses_table').hasClass('no_select')
                    }
                });
            }
            else if(formType == "view_shares") {
                $(this).modalDialog({
                    uniqueID: rowID,
                    width: 400,
                    type: formType,
                    controller: "shop"
                });
            }
            else if(formType == "send_any_show") {
                $(this).modalDialog({
                    uniqueID: rowID,
                    width: 400,
                    type: formType,
                    controller: "shop"
                });
            }
            else {
                $(this).modalDialog({
                    uniqueID: rowID,
                    width: 400,
                    type: formType,
                    controller: "contacts"
                });
            }
        });
    }
}

function mastersControls(detail) {
    detail.find("a.rename").each(function() {
        var rowID = $(this).attr("id");
        $(this).modalDialog({
            uniqueID: rowID,
            width: 500,
            type: "rename_media",
            controller: "media"
        });
    });
}

function showsControls(detail) {
    detail.find("a.rename").each(function() {
        var rowID = $(this).attr("id");
        $(this).modalDialog({
            uniqueID: rowID,
            width: 500,
            type: "rename_media",
            controller: "shows"
        });
    });
    detail.find("a.facebook").each(function() {
        var rowID = $(this).attr("id");
        $(this).modalDialog({
            uniqueID: rowID,
            width: 500,
            type: "facebook",
            controller: "shows"
        });
    });
    detail.find("a.show_dist").each(function() {
        var rowID = $(this).attr("id");
        $(this).modalDialog({
            uniqueID: rowID,
            width: 500,
            type: "show_distributions",
            controller: "shows"
        });
    });
}

( function() {
    jQuery.fn.modalDialog	= function(options) {
        var lnks		= this;
        var settings	= {
            width: 500,
            uniqueID: null,
            type: null,
            params: null
        }
        $.extend(settings, options);
        if(settings.mode != null) {
            if(settings.params == null) {
                settings.params = {
                    mode:settings.mode
                };
            }
            else {
                settings.params.mode = settings.mode;
            }
        }
        return lnks.each(function() {
            $(this).bind("click", function(e) {
                e.preventDefault();
                var id		= ( settings.uniqueID == null ) ? "" : settings.uniqueID;
                var type	= ( settings.type == null ) ? $(this).attr("id") : settings.type;
                var controller  = ( settings.controller == null ) ? $("body").attr("id") : settings.controller;
                var params      = ( settings.params == null ) ? "" : "?" + $.param(settings.params);
                $.get("/" + controller + "/" + type + "/" + id + params, function(data) {
                    // create a modal dialog with the data
                    $(data.replace(/\n/g, "")).modal({
                        close: false,
                        closeClass: 'closeDialog',
                        onOpen: modals.open,
                        onShow: modals.show,
                        onClose: function(dialog) {
                            $("[id^='flash']").show();
                            $.modal.remove(dialog)
                        },
                        modalWidth: settings.width
                    });
                });
            });
        });
    }
}) (jQuery);

var modals = {
    open:
    function(dialog) {
        dialog.overlay.fadeIn(200, function () {
            dialog.container.fadeIn(200, function () {
                dialog.content.fadeIn(200)
            });
        });
    },
    show:
    function(dialog) {
        $("[id^='flash']").hide();
        $('#notice').empty();
        PIXORIAL.browserCheck();
        // since Ajax loaded content ignores previously triggered JS
        // we must re-trigger the JS for the loaded content
        dialog.content.find("form:eq(0)").formButtons();
        roundButton($("#modalContainer a.submit, #modalContainer a.cancel"));
        focusField();
    }
};

// Button Rounding

function roundButton(cls) {
    if(!($.browser.msie && $.browser.version == 6)) {
        var button;
        if(typeof cls == "string") {
            button = $("a." + cls);
        }
        else {
            button = cls;
        }
        button.each(function() {
            $(this).corner({
                tl : {
                    radius: 6
                },
                tr : {
                    radius: 6
                },
                bl : {
                    radius: 6
                },
                br : {
                    radius: 6
                }
            });
        });
    }
}
