/*
 * MoboVivo methods
 */

// setup limited debugging
function handleError(msg, url, linenumber) {
    // steal our message box to render an error message
    if (DJANGO_DEBUG) {
        var err="Javascript error: '" + msg + "'\nline: " + linenumber + "\nURL:  " + url + '\n';
        var errDiv = document.getElementById('mv-message-dialog');
        var theNewParagraph = document.createElement('pre');
        var theTextOfTheParagraph = document.createTextNode(err);
        theNewParagraph.appendChild(theTextOfTheParagraph);
        errDiv.appendChild(theNewParagraph);
        errDiv.style.display = 'block';
    }
    return true;
}
// window.onerror = handleError;

/* Cookie methods based upon work of Peter-Paul Koch http://www.quirksmode.org/js/cookies.html */
function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    var value=getCookie(name);
    setCookie(name,"",-1);
    return value;
}

function removeAccents(input) {
    var acc = 'Ã€Ã?Ã‚ÃƒÃ„Ã…Ã Ã¡Ã¢Ã£Ã¤Ã¥Ã’Ã“Ã”Ã•Ã•Ã–Ã˜Ã²Ã³Ã´ÃµÃ¶Ã¸ÃˆÃ‰ÃŠÃ‹Ã¨Ã©ÃªÃ«Ã°Ã‡Ã§Ã?ÃŒÃ?ÃŽÃ?Ã¬Ã­Ã®Ã¯Ã™ÃšÃ›ÃœÃ¹ÃºÃ»Ã¼Ã‘Ã±Å Å¡Å¸Ã¿Ã½Å½Å¾';
    var rep = ['A','A','A','A','A','A','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z'];
    var output = [];
    output.length = input.length;
    for (var y = 0; y < input.length; y++) {
        var ich = input.charAt(y), ndx = acc.indexOf(ich);
        output[y] = ( ndx == -1 ? ich : rep[ndx] );
    }
    return output.join('');
}


// Stuff I have given up on :(
function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
        var thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    // adjust the last kids of interested columns
    group.each(function() {
        var $kid = $(this).children(".mv-stretcher");
        var delta = tallest - $(this).height();
        alert("setting height delta: " + delta);
        $(this).height(tallest);
        $kid.height($kid.height() + delta);
    });
}

/******************************/
/*        Widgety Bits        */
/******************************/

function preload_image(path) {
    var loader = new Image();
    loader.src = path;
}

function create_radio_button(buttonId, upImg, dnImg, toggleCallback) {
    // find button holder and add two images to toggle between
    var $button = $("#" + buttonId);
    $button.empty();
    $button.append('<img class="mv-radio-up" src="' + upImg + '" />');
    $button.append('<img class="mv-radio-dn" src="' + dnImg + '" />');
    // hide appropriate image based on default selection
    var selected = $button.hasClass('mv-selected');
    var offImg = ((selected)?".mv-radio-up":".mv-radio-dn");
    $button.find(offImg).hide();
    // setup behaviors
    $button.click(function() {
        // ignore if we are already selected
        var $this = $(this);
        if ($this.hasClass('mv-selected')) {
            return;
        }
        // else turn of existing selection(s)
        var $oldSelection = $(this).parent().children('.mv-selected');
        $oldSelection.children('.mv-radio-dn').hide();
        $oldSelection.children('.mv-radio-up').show();
        $oldSelection.removeClass('mv-selected');
        // set new selection to us
        $this.addClass('mv-selected');
        $this.children('.mv-radio-up').hide();
        $this.children('.mv-radio-dn').show();
        toggleCallback(buttonId);
    });
}


/******************************/
/*  Page-load time operations */
/******************************/

var message_callbacks = [];
function view_messages() {
    $('#mv-message-dialog').dialog({
        buttons: {
            "Close": function() {
                $(this).dialog("close");
            }
        },
        close: function() {
            messages = false;
            for (var i = 0; i < message_callbacks.length; i++) {
                try {
                    message_callbacks[i]();
                }
                catch(err) { /* just ignore failures and let dialog close */ }
            }
        },
        closeOnEscape: true,
        draggable: false,
        modal: true,
        resizable: false,
        width: 400,
        title: "Notifications"
    });
}

function after_messages(callback) {
    if (messages) {
        message_callbacks.push(callback);
    }
    else {
        if (callback) {
            callback();
        }
    }
}

// Facebook support
function fbEnsureInit(callback) {
    if (!FB_API_KEY || FB_API_KEY == '') return;

    // if unloaded
    if (!window.fbAsyncInit) {
        // start loading
        (function() {
            var fbs = document.createElement('script');
            fbs.async = true;
            fbs.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(fbs, s);
        }());

        window.fbAsyncInit = function() {
            FB.init({
                appId: FB_API_KEY,
                status: true,
                cookie: true,
                xfbml: true
            });
            window.fbApiInitialized = true;
        };
    }

    if (!window.fbApiInitialized) {
        setTimeout(function() {
            fbEnsureInit(callback);
        }, 50);
    } else {
        if (callback) {
            callback();
        }
    }
}

/******************************/
/*    Post-load operations    */
/******************************/

$(document).ready(function() {
    // note that images may still be downloading

    // repository images fade-in
    function loadImage() {
        if (!$(this).attr('MoboLoaded')) {
            $(this).attr('MoboLoaded', true).css({
                opacity: '0.0',
                visibility: 'visible'
            }).animate({
                opacity:1.0
            }, 1000, function() {
                $(this).trigger('MoboLoad', [this]);
            });
        }
    }
    $('.mv-repo-img').load(loadImage);

    // handle image loading for broken onload/complete from browsers
    var finish_pass = 10;
    function finishImages() {
        var done = true;
        $('.mv-repo-img').each(function () {
            if (finish_pass < 1 || this.complete) {
                $(this).trigger('load');
            }
            else {
                done = false;
            }
        });
        // if (finish_pass == 0) { alert("FAILED");}
        finish_pass--;
        if (!done) { setTimeout(finishImages, 500); }
        // else {alert("Done loading count-down: " + finish_pass);}
    }
    finishImages();

    // fixup last-items, so css can style in all browsers
    $('li:last-child').addClass('last-item');

    // show users messages if present
    if (messages) {
        // launch dialog
        view_messages();
    }

    // turn on our 'buttons'
    $("button").button();

    // setup default button handling
    $('form input, form select').live('keypress', function (e) {
        var defButton = $(this.form).find('button[type=submit].mv-default, input[type=submit].mv-default');
        // if no default or not the enter key -> propagate keypress
        if ((defButton.length <= 0) || !((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) )
        {
            return true;
        }
        // else trigger default submit and do not propagate
        defButton.click();
        return false;
    });

    // turn on fancy date selection
    $(".mv-date-field").datepicker({
        dateFormat: 'yy-mm-dd',
        changeYear: true
    }).keydown(function(ev) {
        if (ev.keyCode == 8) {
            $.datepicker._clearDate(ev.target);
        }
    });

    // add hover actions to standard ui 'buttons'
    $(".ui-state-default").hover(
        function(){
            $(this).addClass("ui-state-hover");
        },
        function(){
            $(this).removeClass("ui-state-hover");
        });

    // some old IE hooks
    if ($("html").hasClass("ie6") || $("html").hasClass("ie7")) {
        $(".mv-table-col").each(function() {
            // set the column to be as css-wide as it appears to be, allowing children to be full width
            // for ie6: must be done before enabling accordions or jquery changes will make them 100% first
            var col = $(this);
            var wd = col.width();
            col.width(wd + 40);
        });
    }

    // turn on tabs
    $(".ui-tabs").tabs();

    // turn on sub-menus
    $(".mv-hover-menu > li").hoverIntent({
        timeout: 500,
        over: function() {
            // display the sub-menu
            var $this = $(this);
            $this.siblings().find(".mv-subnav-options").stop(true,true).hide();
            var $submenu = $this.find(".mv-subnav-options");
            var slide_direction = (($submenu.hasClass('mv-slide-right'))?'left':'up');
            $submenu.stop(true, true).show("slide", {
                direction: slide_direction
            }, 'fast');
        },
        out: function() {
            var $this = $(this);
            var $submenu = $this.find(".mv-subnav-options:visible");
            var slide_direction = (($submenu.hasClass('mv-slide-right'))?'left':'up');
            $submenu.stop(true,true).hide("slide", {
                direction: slide_direction
            }, 'fast');
        }
    });

    // setup the options menus to hide when mouse leaves them
    $(".mv-cart-add-options-menu").mouseleave( function () {
        $(this).slideUp();
    });

    // turn on our 'slideshow' if present
    // DCDC TBD: move these into settings sometime, somehow
    var slide_buttons_hide = true;
    var slide_buttons_normally_on = false;
    $("#mv-slideshow").each(function() {
        // init
        var $slider = $(this);
        var slide_loading = true;
        var manual = $slider.hasClass('mv-manual');
        // get size for slider, necesarry to allow slides to be larger then the viewport, used for spacing
        var curWidth = $slider.width();
        var curHeight = $slider.children().height();
        // setup cycle plugin
        $slider.cycle({
            fx:     'scrollHorz',
            // by forcing the size we allow the child slides to be larger then the viewport
            containerResize: false,
            width:  curWidth,
            height:  curHeight,
            prev:   $slider.siblings('#mv-slide-left').get(0),
            next:   $slider.siblings('#mv-slide-right').get(0),
            timeout: (manual?0:15000),
            before: function() {
                if (slide_loading) {
                    slide_loading = false;
                    return;
                }
                $slider.siblings('.mv-feature-label').fadeOut(50);
                if (slide_buttons_normally_on && slide_buttons_hide) $slider.siblings(".mv-slide-button").fadeOut('fast');
            },
            after: function() {
                $slider.siblings('.mv-feature-label').fadeIn('fast');
                if (slide_buttons_normally_on && slide_buttons_hide) $slider.siblings(".mv-slide-button").fadeIn('fast');
            }
        });
    });
    if (!slide_buttons_normally_on && slide_buttons_hide) {
        // enable hover buttons for slider
        $(".mv-slide-button").children().animate({
            opacity:0.0
        }, 1000);
        $(".mv-slide-button").hoverIntent(function() {
            $(this).children().stop(true,true).animate({
                opacity:1.0
            }, 500);
        }, function() {
            $(this).children().stop(true,true).animate({
                opacity:0.0
            }, 500);
        });
    }

    // turn on accordions
    $(".ui-accordion").each(function() {
        var $selected_child = $(this).children('.ui-state-active');
        if ($selected_child.length == 0)
        {
            $(this).accordion();
        }
        else
        {
            $selected_child.removeClass('ui-state-active');
            $(this).accordion( {
                active: $selected_child[0]
            });
        }
    });

    // justify elements
    $(".mv-justify").each(function() {
        // set the left margins so as to divide up the width
        var $div = $(this);

        // clear existing margins
        $div.children().each(function() {
            $(this).css({
                marginLeft: 0,
                marginRight: 0
            });
        });

        // setup offsets
        var width = $div.width();
        var childCount = $div.children().length;
        var $last = $div.children().last();
        var $first = $div.children().first();
        var childWidth = $last.position().left - $first.position().left + $last.width();
        var first = true;
        // subtract one for stuborn browsers handling of spaces between tags
        var offset = Math.floor(( width - childWidth ) / ( childCount - 1) - 1);
        //alert("Width: " + width + " offset: " + offset + " childCount: " + childCount);
        $div.children().each(function() {
            $(this).css({
                marginLeft: (first ? 0 : offset)
            });
            first = false;
        });
    });

    // fixup table height
    $(".mv-table").each(function() {
        // set the table to be as css-tall as it appears to be, allowing children to be 100% high
        var tbl = $(this);
        var ht = tbl.height();
        tbl.height(ht);
    });

});


