// Pixorial namespace
var PIXORIAL = function() {
    function sortCloudByAttribute(index){
        return function (x,y){
            if (x[index] < y[index]){
                return -1;
            }
            else if (x[index] > y[index]){
                return 1;
            }
            else {
                return 0;
            }
        }
    }
    function setErrorClass(fieldsArray) {
        for(var i = 0; i < fieldsArray.length; i++) {
            $('#'+fieldsArray[i]).addClass('error');
        }
    }
    return {
        "resizePanes" : function(min_width, min_height, max_width, max_height) {
            $('div#flash_div').css('clear', 'both');
            var flash_div = $('div#flash_div');
            var main_div =  $('div#main');
            var global_menu = $('div#global_menu');
            var global_bar = $('div#global_bar');
            var notice = $('div#notice');
            var footer = $('div#footer');
            if(min_width == null) min_width = 900;
            if(min_height == null) min_height = 600;
            if(max_width == null) max_width = 2000;
            if(max_height == null) max_height = 2000;
            if(max_width == -1) max_width = $(window).width();
            if(max_height == -1) max_height = $(window).height();
            
            if(flash_div.length > 0) {
                var new_height = $(window).height() - global_bar.outerHeight() - notice.outerHeight() - footer.outerHeight() - 10;
                if($('#notice div').length == 0) {
                    $('#flash_div object, div#footer').addClass('negative_flash_margin');
                }
                else {
                    $('#flash_div object, div#footer').removeClass('negative_flash_margin');
                }
                if(new_height >= min_height && new_height <= max_height) {
                    flash_div.height(new_height);
                }
                else if(new_height < min_height) {
                    flash_div.height(min_height);
                }
                else {
                    flash_div.height(max_height);
                }
            }
            else {
                if(typeof main_div_height == "undefined") {
                    main_div_height = main_div.outerHeight();
                }
                var margin_height = global_bar.outerHeight() + notice.outerHeight() + footer.outerHeight();
                if($(window).height() >= main_div_height + margin_height) {
                    main_div.height($(window).height() - margin_height);
                }
                else if($(window).height() <= $('body').height()) {
                    main_div.height(main_div_height);
                }
            }

            var new_width = $(window).width()-30; // so there is slight margin on both sides

            if(new_width < min_width) {
                new_width = min_width;
            }
            else if(new_width > max_width) {
                new_width = max_width;
            }

            // we'll use global_menu.width since that is always present.
            var margin = ($(window).width() - new_width) / 2;
            if(margin < 5) {
                margin = 10;
                new_width -= 20;
            }
            
            if(flash_div.length > 0) {
                flash_div.width(new_width);
                if(BrowserDetect.browser.toLowerCase().indexOf('explorer') != -1) {
                    main_div.css('text-align', 'center');
                    if(BrowserDetect.version != 7) {
                        flash_div.css('margin-left', ($(window).width() - new_width) / 2);
                    }
                }
                else {
                    main_div.css('text-align', 'inherit');
                }
                global_menu.width(Math.max(flash_div.outerWidth(), 900));
                global_menu.css('margin-left', (global_bar.width() - global_menu.outerWidth()) / 2);
            //                notice.width(global_bar.outerWidth());
            }
            else {
                //global_menu.width(new_width);
                //global_menu.css('margin-left', (global_bar.width() - global_menu.outerWidth()) / 2);
                //                notice.width(global_bar.outerWidth());
                main_div.width(min_width);
                var main_margin = ($(window).width() - main_div.outerWidth()) / 2;
                if(main_margin < 0) {
                    main_margin = 0;
                }
            }
            //            $('#alert, #success, #failure').css('position', 'relative').css('top', "-3px").css('z-index', '0').css('background-position', ($(window).width() - global_menu.outerWidth()) / 2 + "px", '50%').css('padding-left', ($(window).width() - global_menu.outerWidth()) / 2 + 26 + "px");

            $('div.install_flash').css('display', 'block')
        },
        "showAlert" : function(message, useTimeout) {
            if(message && ($('#alert').length == 0 || $('#alert').html().indexOf(message) == -1)) {
                if(useTimeout) {
                    var timeout = function() {
                        $("#alert").html($("#alert").html().replace(new RegExp(message.replace(/&/,"&amp;").replace(/</,"&lt;").replace(/>/,"&gt;") + "\\s?(<br>)?"), ""));
                        if($("#alert").html() == "") {
                            $("#alert").remove();
                        }
                        try {
                        //                            resize();
                        }
                        catch(e) {}
                    }
                    setTimeout(timeout,8000);
                }
                
                if($('#alert').length > 0) {
                    $("#alert").remove();
                    $('#notice').prepend('<div id="alert">' + message + '</div>');
                }
                else {
                    $('#notice').prepend('<div id="alert">' + message + '</div>');
                }
                try {
                //                    resize();
                }
                catch(e) {}
                var _iframe = window.parent.frames.length;
                if (_iframe > 0){
                    var _notice = document.getElementById('notice');
                    _notice.scrollIntoView();
                }
                setTimeout(PIXORIAL.clearNotice, 8000);  
            }
        },
        "showSuccess" : function(message, useTimeout) {
            if(message && ($('#success').length == 0 || $('#success').html().indexOf(message) == -1)) {
                if(useTimeout) {
                    var timeout = function() {
                        $("#success").html($("#success").html().replace(new RegExp(message.replace(/&/,"&amp;").replace(/</,"&lt;").replace(/>/,"&gt;") + "\\s?(<br>)?"), ""));
                        if($("#success").html() == "") {
                            $("#notice").empty();
                        }
                        try {
                        //                            resize();
                        }
                        catch(e) {}
                    }
                    setTimeout(timeout,8000);
                }

                if($('#success').length > 0) {
                    $("#success").remove();
                    $('#notice').prepend('<div id="success">' + message + '</div>');
                }
                else {
                    $('#notice').prepend('<div id="success">' + message + '</div>');
                }
                try {
                //                    resize();
                }
                catch(e) {}
                var _iframe = window.parent.frames.length;
                if (_iframe > 0){
                    var _notice = document.getElementById('notice');
                    _notice.scrollIntoView();
                }
                setTimeout(PIXORIAL.clearNotice, 8000);
            }
        },
        "showFailure" : function(message, useTimeout) {
            if(message && ($('#failure').length == 0 || $('#failure').html().indexOf(message) == -1)) {
                if(useTimeout) {
                    var timeout = function() {
                        $("#failure").html($("#failure").html().replace(new RegExp(message.replace(/&/,"&amp;").replace(/</,"&lt;").replace(/>/,"&gt;") + "\\s?(<br>)?"), ""));
                        if($("#failure").html() == "") {
                            $("#failure").remove();
                        }
                        try {
                        //                            resize();
                        }
                        catch(e) {}
                    }
                    setTimeout(timeout,8000);
                }
                PIXORIAL.showErrors('', message);
            }
        },
        "showErrors" : function(fields, message) {
            var notice = $('#notice');
            if(fields || message) {
                message = message || "Fields are invalid.  Please double check what you have entered.";
                //                var y = $(window).scrollTop();
                if(fields.length > 0) {
                    setErrorClass(fields.split(','));
                }
                if(notice.length == 1 && ($('#failure').length == 0 || $('#failure').html().indexOf(message) == -1)) {
                    if($('#failure').length > 0) {
                        $('#failure').append('<br/>' + message);
                    }
                    else {
                        notice.append('<div id="failure">' + message + '</div>');
                    }
                }
                try {
                //                    resize();
                }
                catch(e) {}
                var _iframe = window.parent.frames.length;
                if (_iframe > 0){
                    var _notice = document.getElementById('notice');
                    _notice.scrollIntoView();
                }
                setTimeout(PIXORIAL.clearNotice, 8000); 
            }
        },
        "clearNotice" : function() {
            $('#notice').empty();
            try {
                resize();
            }
            catch(e) {}
        },
        "showErrorsModal" : function(fields) {
            $('#notice').empty();
            setErrorClass(fields.split(','));
            $('div#error_message').html('<div id="failure">Fields are invalid.  Please double check what you have entered.</div>');
        },
        "clearErrorClass" : function() {
            $('div#error_message').empty();
            $('.error').removeClass('error');
        },
        "updateCustomer" : function() {
            PIXORIAL.showSuccess("Your personal information has been successfully updated.");
        },
        "updateMaster" : function(data, index) {
            $('#masters_table tr#' + index).find('label').html(data);
            $('#masters_table').trigger('update');
            PIXORIAL.showSuccess("Master successfully renamed.");
        },
        "updateShow" : function(data, index) {
            $('#shows_table tr#' + index).find('label').html(data);
            $('#shows_table').trigger('update');
            PIXORIAL.showSuccess("Show successfully renamed.");
        },
        "refreshSort" : function(data) {
            var ln	= $(data).find("th").length;
            for (i=0;i<=ln;i++) {
                if ( $(data + ' thead th:eq(' + i + ')').hasClass('headerSortDown') ) {
                    $(data).trigger("sorton", [[[ i, 0]]]);
                    i=ln;
                }
                if ( $(data + ' thead th:eq(' + i + ')').hasClass('headerSortUp') ) {
                    $(data).trigger("sorton", [[[ i, 1]]]);
                    i=ln;
                }
            }
        },
        "updateContact" : function(data, index) {
            var updatedContact = $('#addresses_table div#' + index).parents('tr').click().html(data).removeClass("hover");
            $('updatedContact').find('td:first-child').addClass("icon");
            $('#addresses_table').trigger('update');
            $(updatedContact).find('a:not(".disabled")').each(function () {
                $(this).click(function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleContactToDistributionList($(this).parents('tr').find('div').attr('id'), $(this).attr('id'));
                });
            });
            // make sure a disabled item is not listed in the array, in case it was previously selected and then erased
            if ( $(updatedContact).find('td.dvd a').hasClass('disabled') ) {
                dvd_to_send_to_array.remove(index);
                $('#send_to_dvd:hidden').val(dvd_to_send_to_array.join(","));
            }
            if ( $(updatedContact).find('td.online a').hasClass('disabled') ) {
                download_to_send_to_array.remove(index);
                $('#send_to_download:hidden').val(download_to_send_to_array.join(","));
            }
            if(typeof setupDistributionLists != 'undefined')
                setupDistributionLists();
            PIXORIAL.refreshSort('#addresses_table');
            $('#addresses_table div#' + index).parents('tr').click();
            PIXORIAL.showSuccess("Contact successfully updated.");
        },
        "addContact" : function(data) {
            if ( $("#no_contacts").length > 0 ) {
                var contacts_table =
                '<a href="" id="create_contact" class="submit">Add Contact</a>' +
                '<table class="no_select empty" id="groups_table"></table>' +
                '<table id="addresses_table" class="' + (contacts_no_select ? 'no_select ' : '') + 'empty">' +
                '<thead><tr><th class="first sorted">First</th><th class="last">Last</th><th class="email">Email</th><th class="city">City</th><th class="state">State</th></tr></thead>' +
                '<tbody></tbody>' +
                '</table><br/>';
                $('#contacts_table').empty().html(contacts_table);
                $('#no_contacts').remove();
                $('#search_contacts').show();
                $('#address_link').html('<a href="" id="create_contact">Add Contact</a>');
                $('#create_contact').click(function() {
                    $("#addresses_table tr.active").click();
                }).modalDialog({
                    type: "new",
                    controller: "contacts",
                    params: {
                        requirement : contact_requirement,
                        no_select : contacts_no_select
                    },
                    width: 212
                });
                $('#create_contact.submit').corner({
                    tl : {
                        radius: 6
                    },
                    tr : {
                        radius: 6
                    },
                    bl : {
                        radius: 6
                    },
                    br : {
                        radius: 6
                    }
                });
                $('#create_group').modalDialog({
                    type: "new",
                    controller: "contacts",
                    params: {
                        requirement : contact_requirement,
                        no_select : contacts_no_select
                    },
                    width: 212
                });
                $('#import_contacts').modalDialog({
                    type: "new",
                    controller: "contacts",
                    params: {
                        requirement : contact_requirement,
                        no_select : contacts_no_select
                    },
                    width: 212
                });
            }
            $('#addresses_table').append('<tr class="">' + data + '</tr>');
            var addedContact = $('#addresses_table tbody tr:last')
            var ln	= $('#addresses_table').find("th").length;
            $(addedContact).find('td:first-child').addClass("icon");

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

            $(addedContact).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");

                }
                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);

                    contactsControls($(this).next("tr.detail"));

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

            $('#addresses_table').trigger('update');
            $(addedContact).find('a:not(".disabled")').each(function () {
                $(this).click(
                    function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        toggleContactToDistributionList($(this).parents('tr').find('div').attr('id'), $(this).attr('id'));
                    }
                    );
            });
            if(typeof setupDistributionLists != 'undefined')
                setupDistributionLists();
            PIXORIAL.refreshSort('#addresses_table');
            $(addedContact).click();
            $('#create_contact').click(function(e) {
                e.preventDefault();
                $('#addresses_table tr.active').click();
            });
            PIXORIAL.showSuccess("Contact created successfully.");
        },
        "deleteContact" : function(id) {
            $('#' + id).parents('tr').next().remove();
            $('#' + id).parents('tr').remove();
            $('#addresses_table').trigger('update');
            if($("#addresses_table tbody tr:not(.detail)").length == (contacts_no_select ? 0 : 1)) {
                var no_addresses =
                '<div class="emptytable contacts" >' +
                '  <div>' +
                '    <h3>You currently have no other addresses! </h3>' +
                '    <p>You can send DVDs and links of your videos to anyone in your Address Book.</p>' +
                //                '    <p>Click the Add Contact button below to enter a new contact or Import Contacts to import from your email.</p>' +
                '    <p>Click the Add Contact button below to enter a new contact.</p>' +
                '    <a href="" id="create_contact" class="submit">Add Contact</a>' +
                //                '    <a href="" id="import_contacts" class="submit">Import Contacts</a>' +
                '  </div>' +
                '</div>';
                $("#search_contacts").hide();
                $('#create_contact').remove();
                if($('#contacts_table').length > 0) {
                    $('#contacts_table').html('<div id="no_contacts"></div>');
                }
                else {
                    $('#addresses_table').after('<div id="no_contacts"></div>');
                }
                $("#no_contacts").html(no_addresses);
                $('#create_contact').click(function() {
                    $("#addresses_table tr.active").click();
                }).modalDialog({
                    type: "new",
                    controller: "contacts",
                    params: {
                        requirement : contact_requirement,
                        no_select : contacts_no_select
                    },
                    width: 212
                }).corner({
                    tl : {
                        radius: 6
                    },
                    tr : {
                        radius: 6
                    },
                    bl : {
                        radius: 6
                    },
                    br : {
                        radius: 6
                    }
                });
            }
            // remove this contact from any distribution arrays
            send_to_array.remove(id);
            $('#send_to:hidden').val(send_to_array.join(","));
        },
        "removeTableRow" : function(tr, emptyText) {
            var table = $(tr).parents('table');
            if($(table).find('tr:not(":first"):not(".detail")').length > 1) {
                $(tr).click().remove();
            }
            else {
                $(table).find("td:first").parents("tr").click().unbind().removeAttr("id").removeAttr("class").end().html(emptyText).siblings().html("").parents("table").addClass("empty");
            }
        },
        "setSessionID" : function(sessionID, uniqueID) {
            $.cookie("_pixorial_session", sessionID);
            $.cookie("unique_id", uniqueID);
        },
        "flash" : function(id) {
            var isIE = navigator.appName.indexOf("Microsoft") != -1;
            return (isIE) ? window[id] : document[id];
        },
        "browserCheck" : function() {
            browserHelp = "/help?context=browser_support";
            helpMessage = "For additional information, please see <a href='" + browserHelp + "'>help</a>.";
            var valid = true;
            switch(BrowserDetect.browser) {
                case "Firefox":
                    if(BrowserDetect.version < 2) {
                        valid = false;
                        PIXORIAL.showFailure(BrowserDetect.browser + " " + BrowserDetect.version + " is not supported at this time. Please upgrade to <a href='http://www.getfirefox.com/' target='_blank'>Firefox 3</a>. " + helpMessage);
                    }
                    break;
                case "Explorer":
                    if(BrowserDetect.version < 7) {
                        PIXORIAL.showFailure("Internet Explorer " + BrowserDetect.version + " is not supported at this time. Please upgrade to <a href='http://www.microsoft.com/windows/downloads/ie/getitnow.mspx' target='_blank'>Internet Explorer 7</a>. " + helpMessage);
                        valid = false;
                    }
                    break;
            }
            return valid;
        },
        "tags" : [],
        "populateTagCloud" : function(search_string, id, destination) {
            var tags = PIXORIAL.tags.sort(sortCloudByAttribute("name"))
            var tag_cloud_string = "";
            for(tagIndex in tags) {
                //alert(tag.name + " : " +  search_string + " : " + );
                if(tags[tagIndex].id == id && tags[tagIndex].name.toLowerCase().indexOf(search_string.toLowerCase()) > -1){
                    tag_cloud_string += "<a href='/media/scene_maker/" + id + "?scene=" + tags[tagIndex].group_id + "' class='cloud_" + tags[tagIndex].type + "'>" + tags[tagIndex].name + "</a> &nbsp;";
                }
            }
            if(tag_cloud_string != "") {
                destination.innerHTML = tag_cloud_string;
            }
        },
        "number_to_currency" : function(amount) {
            amount = amount.toString();
            if(amount.indexOf(".") != -1) {
                var amount_array = amount.split(".");
                var dollars = amount_array[0];
                var cents = amount_array[1];
                if(cents.length <= 3) {
                    cents = cents + Array(3 - cents.length).join("0");
                }
                else {
                    cents = cents.substring(0, 2);
                }
                amount = dollars + "." + cents;
            }
            else {
                amount += ".00";
            }
            return amount;
        },
        "showFlashModal" : function() {
            $('#container').addClass("modal");
        },
        "hideFlashModal" : function() {
            $('#container').removeClass("modal");
        },
        "forbidden_extensions" : ["ai", "amr", "bmp", "bup", "converted", "dmv", "dvd", "exe", "gif", "htm", "idx", "ifo", "ini", "itl", "jpg", "jpeg", "m3u", "m4a", "mht", "mid", "mod", "mp3", "mp9a8", "mswmm", "pbr", "pdf", "piv", "png", "pptx", "prel", "psd", "qtz","rm", "swf", "tdt", "thm", "tif", "tiff", "txt", "veg", "vep", "vi", "vob", "vsp", "vwp", "wav", "webarchive", "webloc", "wimp", "wma", "wpl", "zip"]
    };
}();

//
// Browser Dectect Code for workarounds
//
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
        || this.searchVersion(navigator.appVersion)
        || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)	{
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
    {
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    },
    {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari"
    },
    {
        prop: window.opera,
        identity: "Opera"
    },
    {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    },
    {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    },
    {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
    },
    {
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Google Chrome"
    },
    {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    },
    {		// for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    },
    {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
    },
    {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    },
    { 		// for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }
    ],
    dataOS : [
    {
        string: navigator.userAgent,
        subString: "Windows NT 6.0",
        identity: "Windows Vista"
    },
    {
        string: navigator.userAgent,
        subString: "Windows NT 5.1",
        identity: "Windows XP"
    },
    {
        string: navigator.userAgent,
        subString: "Windows NT 5.0",
        identity: "Windows 2000"
    },
    {
        string: navigator.userAgent,
        subString: "Win 9x 4.90",
        identity: "Windows Millennium Edition"
    },
    {
        string: navigator.userAgent,
        subString: "Windows 98",
        identity: "Windows 98"
    },
    {
        string: navigator.userAgent,
        subString: "Windows 95",
        identity: "Windows 95"
    },
    {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    },
    {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }
    ]
};
BrowserDetect.init();
