/* Local Helper Functions
 *
 * Requires jQuery javascript library
 * http://jquery.com/
 */


/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);


/* Create enclosing namespace */
var BM = new Object;

/*
 * Form Extensions
 */

/* Clear form fields */
BM.clearForm = function() {
    $(":text, :password, textarea", this.form).val("");
    $(":radio, :checkbox, select", this.form).val("");
    $(":file", this.form).val("");
    return false;
};

/* Make enter key behave like a tab in form */
jQuery.fn.fixForm = function() {
    var flds = ":text:enabled, :password:enabled";
    this.delegate(":text", "keypress", function(evt) {
        if (evt.keyCode === 13) {
            var f = $(this).closest("form").find(flds);
            f.slice($.inArray(this, f) + 1).first().focus();
            return false;
        }
    });
    return this;
};

/* Go to first form field */
jQuery.fn.goToFirst = function(pattern) {
    var fields = this.find(":input").not(":hidden, :disabled");
    if (pattern) fields = fields.filter(pattern);
    fields.filter(":first").focus();
    return this;
};

/* Toggle checkboxes
 *      button -> Control that will check/uncheck
 *      pattern -> Checkboxes that will be toggled
 */
BM.FormCheckAll = function(button, pattern) {
    $(button).toggle(
        function() {
            $(pattern, this.form).attr("checked", true);
            this.value = "Uncheck All";
        },
        function() {
            $(pattern, this.form).attr("checked", false);
            this.value = "Check All";
        }
    );
};

/* Toggle select list
 *      button -> Control that will select/unselect
 *      pattern -> Selection lists that will be toggled
 */
BM.FormSelectAll = function(button, pattern) {
    var fields = $(pattern);
    $(button).toggle(
        function() {
            $("option", fields).attr("selected", true);
            this.value = "Unselect All";
        },
        function() {
            $("option", fields).attr("selected", false);
            this.value = "Select All";
        }
    );
};

/*
 * Section Navigation Extensions
 */

/* Load page section when its link is clicked */
jQuery.fn.loadBlock = function(path, target, callback) {
    var block = jQuery(target);
    var def = this.filter(".default").attr("href");
    if (!def) def = this.first().attr("href");

    $(window).hashchange(function() {
        var url = location.hash || def;
        url = path + "/" + url.slice(1);
        block.load(url, callback);
    });
    $(window).hashchange();
    return this;
};

/* Show page section only when its link is clicked */
jQuery.fn.showBlock = function(sections) {
    var blocks = jQuery(sections).hide();
    var def = this.filter(".default").attr("href");
    if (!def) def = this.first().attr("href");

    $(window).hashchange(function() {
        var id = location.hash || def;
        blocks.hide().filter(id).show();
    });
    $(window).hashchange();
    return this;
};

/*
 * Utility Extensions
 */

/* Return maximum value of attribute */
jQuery.fn.max = function(attrib) {
    var maxVal = this.get(0)[attrib];
    this.slice(1).each(function() {
        if (maxVal < this[attrib]) maxVal = this[attrib];
    });
    return maxVal;
};

/* Set link and form targets to new window */
jQuery.fn.setTarget = function(name, opts) {
    var redirect = function() {
        var newWin = BM.openWindow("", name, opts);
        if (newWin) this.target = newWin.name;
    };

    this.filter("a").click(redirect);
    this.filter("form").submit(redirect);
    return this;
};

/* Add zebra striping to table rows */
jQuery.fn.zebra = function(pattern) {
    if (!pattern) pattern = "even";
    this.filter(":nth-child(" + pattern + ")").addClass("high1");
    return this;
};

/*
 * Display Fixes
 */

/* Hide missing product images */
BM.prdImgFix = function() {
    $(this).parents("p").eq(0).hide();
};

/* Replace missing thumbnail images */
BM.thumbImgFix = function() {
    //$(this).unbind("error");
    //this.src = "/prd_images/no_image.gif";
};

/*
 * Content Area Manipulation
 */

/* Resize iframe based on its content */
BM.adjFrame = function(name) {
    var newH = frames[name].document.body.offsetHeight + 30;
    $("iframe[@name=" + name + "]").height(newH);
};

/* Trigger page load from iframe to content div */
BM.triggerLoad = function() {
    if (window != top && top.updateDiv) {
        $(document).ready(top.updateDiv);
    }
};

/*
 *  Window functions
 */

/* Close pop-up window */
BM.closeWindow = function() {
    window.close();
};

/* Open and focus a pop-up window */
BM.openWindow = function(url, name, opts) {
    var newWin = window.open(url, name, opts);
    if (newWin) newWin.focus();
    return newWin;
};

/* Print window */
BM.printWindow = function() {
    window.print();
};

/* Preset window types */
BM.windowType = {
    cart: "width=700,height=450,resizable=1,scrollbars=1",
    img: "width=480,height=480",
    rms: "width=480,height=480,scrollbars=1",
    std: "width=640,height=480,resizable=1,scrollbars=1"
};

/*
 *  Table Sorting
 */

// Initialize sortable table
$.fn.BMmakeSortable = function() {
    this.each(function() {
        var body = $(this).find('tbody.data');
        var last = -1;

        $(this).find('tr.head').click(function(evt) {
            var col = $('th', this).index(evt.target);
            body.BMsortRows(col, col === last);
            last = col === last ? -1 : col;
        });
    });
    return this;
}

// Sort table rows
$.fn.BMsortRows = function(col, desc) {
    var sf = function(a, b) {
        var x = $(a).find('td').eq(col).text();
        if (x.charAt(0) === '$') x = x.slice(1);
        if (!isNaN(x)) x = parseFloat(x);
        var y = $(b).find('td').eq(col).text();
        if (y.charAt(0) === '$') y = y.slice(1);
        if (!isNaN(y)) y = parseFloat(y);

        if (x < y) return desc ? 1 : -1;
        if (x > y) return desc ? -1 : 1;
        return 0;
    };

    this.each(function() {
        var rows = $(this).find('tr');
        rows.detach().removeClass('high1');
        rows.sort(sf).appendTo(this).zebra('odd');
    });
    return this;
};

