// JQuery Unserialize v1.0 by James Campbell
(function($) {
    $.unserialize = function(Data) {
        var Data = Data.split("&");
        var Serialised = new Array();
        $.each(Data, function() {
            var Properties = this.split("=");
            Serialised[Properties[0]] = Properties[1];
        });
        return Serialised;
    };
})(jQuery);

function str_replace(search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}

//------------------------------------------------------------------------------------------------------- 
// ClearTypeFadeTo / ClearTypeFadeIn / ClearTypeFadeOut 
// 
// Custom fade in and fade out functions for jQuery that will work around 
// IE's bug with bold text in elements that have opacity filters set when 
// also using Window's ClearType text rendering. 
// 
// New Parameter: 
// bgColor    The color to set the background if none specified in the CSS (default is '#fff') 
// 
// Examples: 
// $('div').ClearTypeFadeIn({ speed: 1500 }); 
// $('div').ClearTypeFadeIn({ speed: 1500, bgColor: '#ff6666', callback: myCallback }); 
// $('div').ClearTypeFadeOut({ speed: 1500, callback: function() { alert('Fade Out complete') } }); 
// 
// Notes on the interaction of ClearType with DXTransforms in IE7 
// http://blogs.msdn.com/ie/archive/2006/08/31/730887.aspx 
(function($) {
    $.fn.ClearTypeFadeTo = function(options) {
        if (options)
            $(this)
                        .show()
                        .each(function() {
                            if (!$.support.opacity) {
                                // Save the original background color 
                                $(this).attr('oBgColor', $(this).css('background-color'));
                                // Set the bgColor so that bold text renders correctly (bug with IE/ClearType/bold text) 
                                $(this).css({ 'background-color': (options.bgColor ? options.bgColor : '#fff') })
                            }
                        })
                        .fadeTo(options.speed, options.opacity, function() {
                            if (!$.support.opacity) {
                                // ClearType can only be turned back on if this is a full fade in or 
                                // fade out. Partial opacity will still have the problem because the 
                                // filter style must remain. So, in the latter case, we will leave the 
                                // background color and 'filter' style in place. 
                                if (options.opacity == 0 || options.opacity == 1) {
                                    // Reset the background color if we saved it previously 
                                    $(this).css({ 'background-color': $(this).attr('oBgColor') }).removeAttr('oBgColor');
                                    // Remove the 'filter' style to restore ClearType functionality. 
                                    $(this).get(0).style.removeAttribute('filter');
                                }
                            }
                            if (options.callback != undefined) options.callback();
                        });
    };

    $.fn.ClearTypeFadeIn = function(options) {
        if (options)
            $(this)
                        .css({ opacity: 0 })
                        .ClearTypeFadeTo({ speed: options.speed, opacity: 1, callback: options.callback });
    };

    $.fn.ClearTypeFadeOut = function(options) {
        if (options)
            $(this)
                        .css({ opacity: 1 })
                        .ClearTypeFadeTo({ speed: options.speed, opacity: 0, callback: options.callback });
    };
})(jQuery)

function dpOnSelect(dateText, inst) {
    var $this = $(this);
    var idx = $this.parents('table').find('th').index($this.parents('th'));
    $this.parents('table').find('tr').each(function(i, v) {
        $(this).find('td:eq(' + idx + ') input').val(dateText);
    });
}

$(document).ready(function() {

    $('a.node-toggle').live('click', function(e) {
        e.preventDefault();
        var $par = $(this).parent();
        var qs = $(this).attr('href').split('?')[1];
        var uqs = $.unserialize(qs);

        if ($par.hasClass('node-close')) {
            $par.removeClass('node-close').addClass('node-open');
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetNodeData",
                data: "{'NodeID': '" + uqs['NodeID'] + "', 'NodeDepth': '" + uqs['NodeDepth'] + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    var nodedepth = $par.parents('li').length;
                    if (nodedepth == 0) {
                        $('li.node-open').not($par).removeClass('node-open').addClass('node-close').find('ul').slideUp(300, function() {
                            $(this).remove();
                        });
                    }
                    $par.append(msg.d);
                }
            });
        }
        else {
            $par.removeClass('node-open').addClass('node-close');
            $par.find('ul').remove()
        }
    });

    // treeview stuff
    var $anode = $('.active-group');
    if ($anode.length) {
        var p = $anode.position();
        $('div.treeview-wrapper').scrollTop(p.top - 190).scrollLeft(0);
    }

    // Product image swap.
    $('#product-thumbs a').live('click', function(e) {
        var $this = $(this);
        var imgsrc = $this.children('img').attr('src');
        var imgext = imgsrc.split('.')[2];
        if (($('select.product-assoc-select').val() == 1 || $('#kit-product-info').length) && imgext == 'jpg') {
            if (!$this.parent().hasClass('active-thumb')) {
                $('.product-main-image').fadeOut(100, function() {
                    $this.parents('tr').children('td').addClass('active-thumb').end().siblings().children('td').removeClass('active-thumb');
                    $(this).attr('src', imgsrc).fadeIn(300);
                    $('.thickbox').attr('href', imgsrc);
                });
            }
            return false;
        }
        return;
    });
    $('#product-thumbs td:first').addClass('active-thumb');

    // Full-size.
    $('#product-image').hover(function() {
        $('#product-full').fadeTo(200, 1);
    }, function() {
        $('#product-full').fadeTo(500, .3);
    });

    // Quantity validate.
    $('input.ProductDetailsQuantity').unbind('change, keypress');
    $('a.product-submit').parents('form').submit(function(e) {
        var msg;
        var val = $('.ProductDetailsQuantity').val();
        var qmin = $('input[name$="ProductQuantityMin"]').val();
        var qinc = $('input[name$="ProductQuantityIncrement"]').val();

        // Make sure it doesn't go below min.
        if (val < qmin) {
            msg = 'You must order at least ' + qmin + '.';
            e.preventDefault();
        }
        else if (val % qinc !== 0) {
            msg = 'You must order in increments of ' + qinc + '.';
            e.preventDefault();
        }
        else {
            msg = '';
        }
        $('#productMsg').text(msg);
    });

    // PO Number update.
    $('input.po-update').keyup(function() {
        var $this = $(this);
        var idx = $this.parents('table').find('th').index($this.parents('th'));
        $this.parents('table').find('tr').each(function(i, v) {
            $(this).find('td:eq(' + idx + ') input').val($this.val());
        });
    });

    // Shipping date.
    $('input.ship-datepick').datepicker({
        beforeShow: function(input) {
            var maxDate = $(input).datepicker('option', 'maxDate', $(this).parents('th').next().find('input.cancel-datepick').datepicker('getDate'));
        },
        onSelect: dpOnSelect,
        numberOfMonths: 3,
        minDate: new Date()
    });

    // Cancel date.
    var mindate;
    $('input.cancel-datepick').datepicker({
        beforeShow: function(input) {
            var minDate = $(input).datepicker('option', 'minDate', $(this).parents('th').prev().find('input.ship-datepick').datepicker('getDate'));
        },
        onSelect: dpOnSelect,
        numberOfMonths: 3
    }).blur(function() {
        var $this = $(this);
        var idx = $this.parents('table').find('th').index($this.parents('th'));
        $this.parents('table').find('tr').each(function(i, v) {
            $(this).find('td:eq(' + idx + ') input').val($this.val());
        });
    });

    // Cart item delete.
    $('a.item-delete').click(function() {
        if (!confirm("Are you sure you want to remove this item from your cart?")) {
            return false;
        }
        return;
    });

    $('a.popup-prepack').popupWindow({
        centerBrowser: 1,
        height: 600,
        width: 920,
        status: 0,
        toolbar: 0
    });

    $('.close-popup').click(function() {
        document.cookie = "yPos=!~0~!";
        window.close();
    });

    $('#kit-components tr').hover(function() {
        $(this).addClass('kit-row-hover');
    }, function() {
        $(this).removeClass('kit-row-hover');
    });

    $('#kit-components td').click(function(event) {
        if ($(event.target).is('td')) {
            location.href = $(this).parents("tr").find('a').attr('href');
        }
    });

    $('#complete-order input').click(function() {
    //$(this).attr('disabled', 'disabled').css({ opacity: 0.5 });
    //$.blockUI({ message: 'Processing Order...' });
    $.blockUI({
        css: {
            border: '0',
            color: '#222',
            padding: '10px',
            background: '#fff',
            '-webkit-border-radius': '7px',
            '-moz-border-radius': '7px',
            opacity: 1,
            width: '400px',
            top: '30%',
            left: '50%',
            textAlign: 'center',
            marginLeft: '-150px',
            zIndex: 1000
        },
        message: '<h3>Processing Order...</h3>'
    });
    $(this).attr.css({ opacity: 0.5 });
    });

});
