Math.mid = function(a, b, c) { return Math.max(a, Math.min(b, c)); };


// After fade in effect, IE disables anti-aliasing on text, so fix this.
$.fn.fixIEFade = function() {
    if ($.browser.msie && $.browser.version <= 8)
        return this.each(function() {
            this.style.removeAttribute('filter');
        });
    return this;
};
function fixIEFade() { $(this).fixIEFade(); }

/* registering default button for link buttons */
function regDefBtn(_container_id, _link_id) {
    $('#' + _container_id).keydown(function(event) {
        if (event.keyCode == '13') {
            var _link = $('#' + _link_id + ':visible');
            if (_link.length > 0) {
                _link.trigger('click');
                eval(_link.attr('href'));
            }
            event.preventDefault();
        }
    });
}

(function($) {
    var cache = [];
    var methods = {
        cssExists: function(_fname) {
            return $('head link[rel=stylesheet][href*="' + _fname + '"]').length > 0;
        },
        addCss: function(_url) {
            $('head').append('<link href="' + _url + '" media="screen" rel="stylesheet" type="text/css" />');
            return this;
        },
        addJs: function(_url) {
            $('head').append('<script type="text/javascript" language="javascript" src="' + _url + '" />');
            return this;
        },
        validateEmpty: function() {
            var _valid = true;
            this.each(function() {
                if ($.trim($(this).val()) == '') {
                    _valid = false;
                    $(this).next('p').show();
                }
                else {
                    $(this).next('p').hide();
                }
            });
            return _valid;
        },
        clearForm: function() {
            return this.each(function() {
                var type = this.type, tag = this.tagName.toLowerCase();
                if (tag == 'form' || tag == 'div' || tag == 'table')
                    return $(':input', this).dc_utils('clearForm');
                if (type == 'text' || type == 'password' || tag == 'textarea')
                    this.value = '';
                else if (type == 'checkbox' || type == 'radio')
                    this.checked = false;
                else if (tag == 'select')
                    this.selectedIndex = 0;
            });
        },
        tcb: function() {
            var _ie = $.browser.msie && $.browser.version <= 7;
            this.each(function() {
                var _a = $(this).parent('a');
                _a.addClass('tcb');
                $(this).replaceWith(function() {
                    return "<div class='main_tcb' style='clear:both;'><div class='tcb_l'>&nbsp;</div><div class='tcb_s'>" + $(this).html() + "</div><div class='tcb_r'>&nbsp;</div></div>";
                });
                if (_ie) {
                    var _l = _a.text().length;
                    var _w = _l * 9.17;
                    _w = _w < 45 ? 45 : _w;
                    _a.css('width', _w);
                }
            });
        },
        fix_radio: function() {
            this.each(function() {
                $(this).find(':radio[name*="$"]').each(function() {
                    var _name = $(this).attr('name');
                    $(this).attr('name', _name.substring(_name.lastIndexOf('$') + 1));
                });
            });
        },
        get_current_page: function() {
            var _split = $(location).attr('href').split('/');
            if (_split.length > 0) {
                var _page = _split[_split.length - 1];
                var _split2 = _page.split('?');
                if (_split2.length > 0) {
                    return _split2[0];
                }
            }
            return '';
        }
    };

    $.fn.dc_utils = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method == 'object' || !method) {
            return this;
        }
        else {
            $.error('Method ' + method + ' does not exists on jQuery.dc_utils');
        }
    };
})(jQuery);

$.extend({ URLEncode: function(c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        } 
    } return o;
},
    URLDecode: function(s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});


/* sc utils */
var sc_utils = {
    replace: function(_string, _old, _new) {
        return (_string.split(_old)).join(_new);
    },
    get_value: function(_data, _key) {
        var _value = eval("_data." + _key);
        if (typeof _value == 'undefined') return null;
        return _value;
    },
    assign_props: function(_prefix, _args) {
        for (var _key in _args) {
            var _exp1 = _prefix + _key;
            if (typeof eval(_exp1) != 'undefined') {
                eval(_exp1 + " = _args." + _key);
            }
        }
    },
    set_alt_row: function(_table, _css, _ignore) {
        _table.find('tr').not(_ignore.length > 0 && _ignore[0] != '.' ? ('.' + _ignore) : _ignore).filter(':odd').addClass(_css);
    },
    get_options: function(_data, _text_key, _value_key) {
        var _options = [];
        for (var i = 0; i < _data.length; i++) {
            _options.push('<option value="' + _data[i][_value_key] + '">' + _data[i][_text_key] + '</option>');
        }
        if (arguments.length == 4) _options.push('<option value="-1">' + arguments[3] + '</option>');
        return _options.join();
    },
    disable_fields: function(_target) {
        _target.find('input[key],select[key]').removeAttr('readonly').attr('disabled', 'true');
    },
    enable_fields: function(_target, _readonly) {
        _target.find('input[key],select[key]').removeAttr('disabled');
        if (_readonly) this.make_readonly(_target);
    },
    make_readonly: function(_target) {
        _target.find('input[key],select[key]').attr('readonly', 'true');
    },
    remove_readonly: function(_target) {
        _target.find('input[key],select[key]').removeAttr('readonly');
    },
    clear_fields: function(_target) {
        _target.find('input[type="text"]').val('');
        _target.find('select[key!="add_list"]').each(function() {
            $(this).val($(this).children('option:eq(0)').attr('value'));
        });
    },
    outer_html: function(_ctrl) {
        return $('<div />').append(_ctrl.clone()).html();
    },
    position_fixed_supported: function() {
        var container = document.body;
        if (document.createElement && container && container.appendChild && container.removeChild) {
            var el = document.createElement("div");
            if (!el.getBoundingClientRect) {
                return false;
            }
            el.innerHTML = "x";
            el.style.cssText = "position:fixed;top:100px;";
            container.appendChild(el);
            var originalHeight = container.style.height, originalScrollTop = container.scrollTop;
            container.style.height = "3000px";
            container.scrollTop = 500;
            var elementTop = el.getBoundingClientRect().top;
            container.style.height = originalHeight;
            var isSupported = elementTop === 100;
            container.removeChild(el);
            container.scrollTop = originalScrollTop;
            return isSupported;
        }
        return false;
    }
};

/* printer */

var printer = {
    title: 'DC Print Preview',
    preview_template: '<HTML><HEAD><title>{title}</title>{css}{jquery}<base target="_self"></HEAD><body MS_POSITIONING="GridLayout" bottomMargin="0" leftMargin="0" topMargin="0" rightMargin="0"><TABLE width="750"><TR><TD></TD></TR><TR><TD align="right" class="content"><p class="buttons" style="border-top:0;border-bottom:1px solid #D9D9D9;padding-bottom:20px;"><a onclick="javascript:window.print();" class="button print" style="cursor:pointer;width:100px;"><span>Print</span></a></p></TD></TR><TR><TD>&nbsp;</TD></TR><tr><td style="padding-left:20px;">{controls}</td></tr></TABLE>{script}</body></HTML>',
    use_page_css: false,
    css: [],
    control_ids: [],
    _window_options: 'toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,width=800,height=600,left=100,top=25',
    _preview_window: null,
    on_complete_script: '',
    init: function(_args) {
        sc_utils.assign_props('printer.', _args);
    },
    preview: function() {
        this._preview_window = $(window.open("", "", this._window_options));
        this._preview_window[0].document.writeln(this._build_template());
        this._preview_window[0].document.close();
    },
    print: function() {
        window.print();
    },
    _build_template: function() {
        var _html = this.preview_template;
        _html = sc_utils.replace(_html, '{title}', this.title);
        _html = sc_utils.replace(_html, '{css}', this._get_css());
        _html = sc_utils.replace(_html, '{controls}', this._get_controls());
        _html = sc_utils.replace(_html, '{script}', this._get_complete_script());
        _html = sc_utils.replace(_html, '{jquery}', this._get_jquery_script());
        return _html;
    },
    _get_controls: function() {
        var _controls = [];
        if (this.control_ids.length == 0) {
            var _body = $('body').clone();
            _body.find('script').remove();
            return _body.html();
        }
        else {
            for (var i = 0; i < this.control_ids.length; i++) {
                var _ctrl = $('#' + this.control_ids[i]);
                if (_ctrl) _controls.push(sc_utils.outer_html(_ctrl));
            }
        }
        return _controls.join("<br />");
    },
    _get_css: function() {
        if (this.use_page_css) {
            return sc_utils.outer_html($('link[type="text/css"],style'));
        }
        else {
            var _css = [];
            for (var i = 0; i < this.css.length; i++) {
                _css.push('<link rel="stylesheet" type="text/css" href="' + this.css[i] + '" />');
            }
            return _css.join();
        }
    },
    _get_complete_script: function() {
        return this.on_complete_script != '' ? '<script type="text/javascript" language="javascript">' + this.on_complete_script + '</script>' : '';
    },
    _get_jquery_script: function() {
        return this.on_complete_script != '' ? '<script type="text/javascript" language="javascript" src="' + $('script[src$="jquery.js"]').attr('src') + '"></script>' : '';
    }
};

var main = {
    resizeResource: function() {
        var windowResizedHeight = 0;
        var imgHeight = 0;
        var $this = "";
        $("a.close").unbind('click').click(function() {
            windowResizedHeight = 0;
            imgHeight = 0;
            $(this).parent().children().each(function() {
                if ($(this).attr("class") != "img")
                    windowResizedHeight += $(this).height();
                else {
                    imgHeight = parseInt($(this).css("paddingTop").slice(0, -2)) + $(this).height();
                }
                windowResizedHeight += parseInt($(this).css("marginTop").slice(0, -2));
                windowResizedHeight += parseInt($(this).css("paddingBottom").slice(0, -2));
            })

            if (imgHeight > windowResizedHeight) {
                windowResizedHeight = imgHeight;
            }
            $this = $(this).parent().parent();
            if ($this.filter(".active").length) {
                $this.removeClass("active");
                $this.children(".resource").stop().animate({ height: '135px' }, 500, function() {
                    $(this).children("p.intro").show().children("p.description").hide();
                    $(this).children("p.intro").show();
                    $(this).children("p.description").hide();
                    $(this).children("div.related").each(function() {
                        $(this).hide();
                    });
                });
            }
            else {
                $thisChildren = $this.children(".resource");
                $thisChildren.children("p.description").show();
                $thisChildren.children("p.intro").hide();
                $thisChildren.children("div.related").each(function() {
                    $(this).show();
                });

                $(".resource-wrapper").filter(".active").removeClass("active").children("div").animate({ height: '135px' }, 500, function() {
                    $(this).children("p.intro").show();
                    $(this).children("p.description").hide();
                    $(this).children("div.related").each(function() {
                        $(this).hide();
                    });
                });
                $this.addClass("active");
                $thisChildren.stop().animate({ height: windowResizedHeight + 'px' }, 500);
            }

        });
    },

    returnIntroText: function(description, limit) {
        var desc = new Array;
        desc = description.split("");

        var intro = "";
        for (var i = 0; i < desc.length; i++) {
            if (i >= limit)
                if (desc[i] == " ")
                break;
            intro += desc[i];
        }
        intro += "...";
        return intro;
    },

    showIntroText: function(limit) {
        var description = "";
        $(".resource").each(function() {
            description = $(this).children("p.description").hide().html();
            $(this).children("p.intro").html(main.returnIntroText(description, limit));
        })
    },

    pagination: function() {
        var counter = 1;
        var list = "";
        $(".resources").each(function() {
            if (counter == 1)
                list += '<li><a class="active" title="#resources-' + counter + '">' + counter + '</a></li>';
            else
                list += '<li><a title="#resources-' + counter + '">' + counter + '</a></li>';
            counter++;
        })
        $(".pagination ul").html(list);
    },

    changePage: function() {
        var $element = $(".pagination ul li a");
        var tabId = "";
        $element.hover(function() {
            tabId = $(this).attr("title");
            $(this).attr({ title: "" });
        },
		    function() {
		        $(this).attr({ title: tabId });
		    })

        $element.click(function() {
            $(".resources").each(function() {
                if ($(this).attr("id") != tabId)
                    $(this).hide();
            });

            $element.not(this).filter(".active").removeClass("active");
            $(this).addClass("active");
            $(tabId).show();
        })
    },

    tooltip: function() {
        //showing tooltip
        $("p.column a").click(function() {
            $("span.tooltip").filter(".active").stop().fadeOut().removeClass("active");
            $(this).parent().children("span.tooltip").stop().fadeIn().addClass("active");
        })
        //closing tooltip
        $("a.close-cross").click(function() {
            $("span.tooltip").filter(".active").fadeOut().removeClass("active");
        })

    },

    checkboxSelection: function() {
        $(".multiple-choice ul li input").click(function() {
            //if we check first checkbox we clear all other checkboxes
            if ($(this).parent().index() == 0) {
                if ($(this).attr("checked"))
                    $(this).parent().parent().children("li").not(":first").children("input").attr("checked", false);
            }
            //if we check other element than first we clear first element
            else {
                if ($(this).attr("checked"))
                    $(this).parent().parent().children("li").filter(":first").children("input").attr("checked", false);
            }
        })
    }    
}


function afterResize() {
    if ($(".people-1c").length)
        main.showIntroText('70');
    else if ($(".people-2c").length)
        main.showIntroText('130');
    else if ($(".three-cols").length)
        main.showIntroText('200');
    else
        main.showIntroText('120');
}

var m_quantity_increment = 1;

function reinitCart() {
    $(".more").click(function() { changeQuantity($(this), true); });
    $(".less").click(function() { changeQuantity($(this), false); });
}

function changeQuantity(_ctrl, _dir) {
    try {
        var _input = $(_ctrl).parent().parent().children("input");
        var _quantity = parseInt(_input.val());
        _quantity = isNaN(_quantity) ? 1 : _quantity;
        var _val = _dir ? (_quantity < 1 ? 1 : _quantity + m_quantity_increment) : (_quantity <= 1 ? 1 : _quantity - m_quantity_increment);
        _input.val(_val);
    }
    catch (e) { }
}

var m_home_banner_rotate = true;
var m_home_banner_timer = 5000;

$(window).load(function() {
    // Clear default values in text fields.
    $('.search>p>input:text,.EditingFormControlNestedControl>textarea').each(function() {
        this.defaultText = this.value;
        $(this)
		    .focusin(function() { if (this.value == this.defaultText) this.value = ''; })
		    .focusout(function() { if (this.value == '' && this.defaultText) this.value = this.defaultText; });
    });

    // Stylized radio buttons in header's search form.
    $('.header div.search input:radio').each(function() {
        var $radio = $(this);
        var $fake = $('<span class="radio"></span>').insertAfter($radio);

        $fake.toggleClass('checked', $radio.is(':checked'));

        $fake.click(function() {
            $radio.click();
        });

        $radio.click(function() {
            $fake.addClass('checked');
            $fake.closest('div').find('span.radio').not($fake).removeClass('checked');
        });
    });


    $('.banner').each(function() {
        var $banner = $(this);
        var $content = $banner.children('.content');
        var $images = $banner.find('>ul.images>li');
        var $thumbs = $banner.children('.thumbs');
        var itemsCount = $images.length, currentItem = 0;
        var navItemW = 45, thumbItemH = 81, contentItemW = 312;
        var time = 333;
        var startitem = Math.floor(Math.random() * itemsCount);

        $images.filter('li:gt(0)').css({ zIndex: 1 });
        $images.css({ visibility: 'visible' }).eq(0).css({ zIndex: 2 }).addClass('active');
        //$images.css({ visibility: 'visible' }).eq(startitem).css({ zIndex: 2 }).addClass('active');

        var navItems = '';
        for (var i = 0; i < itemsCount; i++)
            navItems += '<li><a href="#">' + (i + 1) + '</a></li>';

        var $nav = $('<div class="navigation"><p class="previous"><a href="#">&lt;</a></p><div class="clip"><ul>' + navItems + '</ul></div><p class="next"><a href="#">&gt;</a></p></div>').appendTo($content);
        $nav.find('ul>li:first-child>a').addClass('active');
        //$nav.find('ul>li:eq(' + startitem + ')>a').addClass('active');

        $thumbs.find('ul').wrap('<div class="clip"></div>');
        $thumbs.append('<p class="previous"><a href="#">Previous</a></p><p class="next"><a href="#">Next</a></p><p class="toggle"><a href="#">Toggle</a></p>');
        $thumbs.find('ul>li:first-child>a').addClass('active');
        //$thumbs.find('ul>li:eq(' + startitem + ')>a').addClass('active');

        $thumbsList = $thumbs.find('>.clip>ul');
        $content.find('>div').not('.navigation').wrapAll('<div class="clip"><div class="list"></div></div>');
        $contentList = $content.find('.list:first');
        //$contentList.css({ left: (-startitem * contentItemW) + 'px' });

        $navList = $content.find('>.navigation>.clip>ul');
        //$navList.find('li:eq(' + startitem + ')>a').addClass('active');

        /*
        * Displays specific item - it's image, thumbnail and text description.
        */
        var animateTo = function(index) {
            index = Math.mid(0, index, itemsCount - 1);
            if (index == currentItem) {
                return;
            }
            var oldItem = currentItem;
            currentItem = index;

            var thumbsPos = Math.max((itemsCount - 4) * -thumbItemH, -currentItem * thumbItemH);
            $thumbsList.stop(true).animate({ top: thumbsPos + 'px' }, time);
            $thumbsList.find('a.active').removeClass('active');
            $thumbsList.find('li:eq(' + currentItem + ')>a').addClass('active');

            var navPos = Math.mid((itemsCount - 5) * -navItemW, (-currentItem + 2) * navItemW, 0);
            $navList.stop(true).animate({ left: navPos + 'px' }, time);
            $navList.find('a.active').removeClass('active');
            $navList.find('li:eq(' + currentItem + ')>a').addClass('active');

            $contentList.stop(true).animate({ left: (-currentItem * contentItemW) + 'px' }, time);

            $images.not('.active').css({ opacity: 0 });
            var $activeImage = $images.filter('.active').removeClass('active');
            var z = parseInt($activeImage.css('z-index'), 10);
            $content.css({ zIndex: z + 2 });
            $thumbs.css({ zIndex: z + 2 });
            $images.eq(currentItem).css({ zIndex: z + 1 }).addClass('active').animate({ opacity: 1 }, time, function() {
                $images.eq(oldItem).css({ opacity: 0 });
            });
        };

        // Show previous item.
        var previousHandler = function(e) {
            e.preventDefault();
            animateTo(currentItem - 1);
        };

        // Show next item.
        var nextHandler = function(e) {
            e.preventDefault();
            animateTo(currentItem + 1);
        };

        // Show item with index of the parent element.
        var indexHandler = function(e) {
            e.preventDefault();
            if (e.originalEvent) {
                // user clicked, stop rotation
                m_home_banner_rotate = false;
            }
            animateTo($(this).parent().index());
        };


        $nav.find('.previous a').click(previousHandler);
        $nav.find('.next a').click(nextHandler);
        $thumbs.find('.previous a').click(previousHandler);
        $thumbs.find('.next a').click(nextHandler);
        $navList.find('a').click(indexHandler);

        $thumbsList.find('a').click(indexHandler);

        // Expand and collapse thumbnails list.
        $thumbs.find('.toggle a').click(function(e) {
            e.preventDefault();
            $(this).toggleClass('active');
            var w = $(this).hasClass('active') ? 141 : 0;
            $thumbs.stop(true).animate({ width: w + 'px' }, time);
        });



    });



    function clip_show() {
        if (m_home_banner_rotate) {
            if ($('div.navigation div.clip a:last').is('.active')) {
                $('div.navigation div.clip a:first').click();
            }
            else {

                $('div.navigation div.clip a.active').parent('li').next('li').children('a').click();
            }

            setTimeout(clip_show, m_home_banner_timer);
        }

    }


    $('.boxes-b>div,.boxes-c>div:last').each(function() {
        var $this = $(this);
        var $first = $(this).children('div:first');
        var $second = $first.next().animate({ opacity: 0 }, 0);
        var $heading = $this.children('h2:first');
        var borderColor = $heading.css('border-top-color');
        var time = 333;
        $heading.css({ borderTopColor: borderColor });

        $this.hover(function() {
            $second.stop(true).animate({ opacity: 1 }, time, fixIEFade);
            $heading.stop(true).animate({ borderTopColor: '#fff' }, time);
        }, function() {
            $second.stop(true).animate({ opacity: 0 }, time);
            $heading.stop(true).animate({ borderTopColor: borderColor }, time);
        });
    });

    setTimeout(clip_show, m_home_banner_timer);

    main.resizeResource();
    //main.pagination();
    //main.changePage();
    main.tooltip();
    if ($(".people-1c").length)
        main.showIntroText('70');
    else if ($(".people-2c").length)
        main.showIntroText('130');
    else if ($(".three-cols").length)
        main.showIntroText('200');
    else
        main.showIntroText('120');

    if (typeof Sys != 'undefined') {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
		    function(sender, e) {
		        if (typeof main != "undefined") {
		            main.resizeResource();
		        }
		        if (typeof sc != "undefined") {
		            sc.products.render();
		        }
		        reinitCart();
		        afterResize();
		    }
	    );
    }


    $("#menuElem a[href^='http://']").attr("target", "_blank");

    $(".text_fx_heading").toggle(function() { $(this).next(".text_fx_desc").slideDown("medium"); }, function() { $(this).next(".text_fx_desc").slideUp("medium"); });
    $(".text_fx_expand").toggle(function() { $(".text_fx_expand_target").show(); }, function() { $(".text_fx_expand_target").hide(); });

    $(".text_fx_toggle").toggle(function() { $(".text_fx_section").slideDown("medium"); }, function() {
        $(".text_fx_section").slideUp("medium");
    });

    /*
    if (typeof m_hide_marea != "undefined" && m_hide_marea) $(".member-resources-wrapper").hide();
    */

    /*
    * Shopping Cart More/Less 
    */
    reinitCart();

    /*
    * Start Left Nav Code - Wilson
    */
    $(".subpage-menu ul.CMSListMenuUL:not('#menuElem')").each(function() {
        if ($(this).find('li.CMSListMenuHighlightedLI').length == 0) {
            $(this).wrap('<div class="flyout"></div>');
            $(this).wrap('<div></div>');
        }
    });

    $('.subpage-menu ul.CMSListMenuUL').not('#menuElem').parents('li').children('a').each(function() {
        if ($(this).find('li.CMSListMenuHighlightedLI').length == 0) {
            $(this).addClass('show-sm')
        }
    });

    $('.subpage-menu li.CMSListMenuHighlightedLI').parents('ul.CMSListMenuUL').not('#menuElem').addClass('submenu');
    $('.subpage-menu li.CMSListMenuHighlightedLI').parents('li').addClass('with-submenu');
    $('.subpage-menu li.with-submenu').children('a').removeClass('show-sm');
    $("div.hide").removeClass('hide');
    /*
    * End Left Nav Code - Wilson
    */


    /*
    * Header Menu Admin Items
    */
    $("ul.subnav").parent().append("<span class='indicator'></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

    $("ul.links li .indicator").click(function() { //When trigger is clicked...  

        //Following events are applied to the subnav itself (moving subnav up and down)  
        $(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  

        $(this).parent().hover(function() {
        }, function() {
            $(this).parent().find("ul.subnav").slideUp('fast'); //When the mouse hovers out of the subnav, move it back up  
        });

        //Following events are applied to the trigger (Hover events for the trigger)  
    }).hover(function() {
        $(this).addClass("subhover"); //On hover over, add class "subhover"  
    }, function() {  //On Hover Out  
        $(this).removeClass("subhover"); //On hover out, remove class "subhover"
    });

    /* three col button */
    $('span.tcb').dc_utils('tcb');
});



