window.P1to2 = {};
window.Loader = {};

var QueryStringParser = (function(name, path) {
    return {
        get: function(name, path) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = ["[\\?&]", name, "=([^&#]*)"].join(''),
                regex = new RegExp(regexS),
                results = regex.exec(path || window.location.href);

            if (results == null) {
                return "";
            } else {
                return results[1];
            }
        }
    };
}());

(function($) {
    window.Loader.hasStylesheet = function(name) {
        var sheets = document.styleSheets;
        for (var i = 0, j = sheets.length; i < j; i++) {
            if (sheets[i].href.indexOf(name) !== -1) {
                return true;
            }
        }
        return false;
    };

    var Shortcuts = {
        overlayHTML: ""
    };

    var Constants = {
        addthis_pub: "SMGWeb",
        addthis_url: "http://s7.addthis.com/js/widget.php?v=10"
    };

    var settings = {
        overlay: {
            fancy: false
        }
    };

    // Shortcut for (function() { return false; });
    function False() {
        return false;
    }

    // Shortcut for (function() { return true; });
    function True() {
        return true;
    }

    // Pull a value out of window.location.search
    var getURLParameter = function(key) {
        return unescape((RegExp(key + '=' + '(.*?)(&|$)').exec(window.location.search) || [,null])[1]);
    };

    // Add a simple tabbing plugin
    $.fn.extend({
       overlayTabs: function(options) {
           var defaults = {},
               options = $.extend(defaults, options);

           return this.each(function() {
               var container = $(this),
                   tabs = container.children('.tabs:first'),
                   pagecontent = container.closest('div.pagecontent'),
                   tabbedItems = container.children('div.tabbed-item');

               // Hide all tabbed content items; the right one will be shown again momentarily.
               tabbedItems.hide();

               // Highlight the tab specified by tabs param (or general) and show 
               // its corresponding tab content body.
			   var show1st = '';
			   var tabsVal = getURLParameter("tabs");
			   if (tabsVal != 'null' && tabsVal.length > 0) show1st = "#tab-" + tabsVal;

               tabs.children('li').each(function(i) {
                    var li = $(this);
                    var tabdivname = li.children('a').first().attr('href');
					if ((show1st === tabdivname) || (show1st === '' && i == 0)) {
                        li.addClass('selected').children('a:first').each(function() {
                            var firstItem = $(this).attr('href').split('#')[1];
                            tabbedItems.filter(['#', firstItem].join('')).show();
                        });
                    }

                    // Listen for clicks on the tabs to show other tabbed content bodies.
                    li.children('a').unbind().click(function(e) {
                        e.preventDefault();
                        var a = $(this),
                            itemToShow = $(this).attr('href').split('#')[1];

                        a.parent('li').addClass('selected').siblings('li').removeClass('selected');
                        tabbedItems.hide().filter(function() {
                            if ($(this).attr('id') === itemToShow) {
                                $(this).show();
                            }
                        });

                        return false;
                    });
                });

                if (options.compactHeaders) {
                    // See if the y-coordinate of the first item and the last item are the same.
                    // If the last item is greater, then compacting these headers might help line up on one line.
                    try {
                        var pool = tabs.children('li'),
                                firstY = pool.first().offset().top,
                                lastY = pool.eq(pool.length - 1).offset().top;

                        if (firstY < lastY) {
                            pool.each(function() {
                                var a = $(this).children('a'),
                                        chunks = $.trim(a.text()).split(/\s/);

                                if (chunks.length % 2) {
                                    chunks.splice(chunks.length / 2, 0, "<br>");
                                } else if (chunks.length % 3) {
                                    chunks.splice(chunks.length - 2, 0, "<br>");
                                }
                                a.html(chunks.join(' ')).addClass('compacted');

                            });
                        }
                    } catch(ex) {
                        //window.console && console.warn(ex)
                    }
                }

               // Show div.pagecontent if it's available. It should be.
               if (pagecontent.length > 0) {
                   pagecontent.show();
               }

           });
       }
    });

    function Phase1to2() {
        var body = $('body'),
            head = $('head'),
            self = this;

        // Override the default fancy overlay settings if ?fancy=true in the address bar
        var fancy = getURLParameter("fancy");
        if (fancy != null && fancy == "true") {
            settings.overlay.fancy = true;
        }

        return {
            buildFromTemplates: function() {
                body.find('textarea.phase1to2stylesheet, textarea.phase1to2script').each(function() {
                    var textarea = $(this),
                        uri = $(this).val(),
                        className = textarea.attr('class'),
                        isStylesheet = (className.indexOf('stylesheet') !== -1),
                        node;
                    if (isStylesheet) {
                        var link = document.createElement("link");
                        link.rel = "stylesheet";
                        link.type = "text/css";
                        link.href = uri;
                        document.getElementsByTagName("head")[0].appendChild(link);
                    } else {
                        //alert("getting script : " + uri);
                        if ($.browser.msie) {
                            var head = document.getElementsByTagName("head")[0],
                                script = document.createElement("script");
                            script.type = "text/javascript";
                            script.src = uri;
                            head.appendChild(script);
                        } else {
                            $.getScript(uri, function() {
                                // nothing really necessary to do here
                                // window.console && console.info("Loaded script: " + uri);

                            });
                        }
                    }
                    textarea.remove();
                });
            },

            // Turn off links that shouldn't be followed.
            disableNofollowLinks: function() {
                //window.console && console.log("Disabling unclickable links");
                body.find('a.no-follow').click(False);
            },
            normalizeRelatedAssetHeights: function() {
                body.find('div.related-assets').each(function() {
                    var maxHeight = 0;
                    $(this).find('ul:first > li > div').each(function() {
                        var height = $(this).height();
                        maxHeight = (height > maxHeight) ? height : maxHeight;
                    }).map(function() {
                        $(this).height(maxHeight);
                    });
                });
            },

            // Show a lightbox or a popup window.
            testLightbox: function() {

                var getProductCatalogLink = function(productId) {
                    var a = document.createElement("a");
                    a.href = ["/smg/catalog/productTemplate.jsp?proId=", productId].join('');
                    return a.href;
                };

                var showOverlay = {

                    // Show the overlay in a fancy javascript lightbox.
                    fancy: function(e) {
                        e.preventDefault();

                        var productId = QueryStringParser.get("proId", $(this).attr("href")),
                            linkToShare = window.location.href; // This will be overwritten momentarily with a proper product template url

                        linkToShare = getProductCatalogLink(productId);

                        var showDialog = function(node) {
                            node.dialog({
                                modal: true,
                                dialogClass: 'product-detail-overlay',
                                width: 700,
                                open: function(event, ui) {
                                    var count = 0;

                                    node.find('div.tabbed-interface').overlayTabs().end();

/*                                  // Get ratings for the general and ratings tabs.
									node.find('.get-rating').each(function() {
                                        $(this).removeClass('get-rating');
                                        var attachTo = $(this),
                                            id = attachTo.attr('id').split(':')[1];
                                        gSiteLife.DynamicRating(id, attachTo);
                                    }).end();
*/
                                    node.find('a.addthis_button').each(function() {
                                        var link = $(this),
                                            someId = ["addthis", Math.floor(100000 * Math.random(new Date().getTime()))].join(''),
                                            someIdSelector = ['#', someId].join('');
                                        // Add the random element id and the addthis:url sharing override;
                                        link.attr({
                                            id: someId,
                                            'addthis:url': linkToShare
                                        });
                                        if (typeof addthis === "object") {
                                            addthis.button(someIdSelector);
                                        } else {
                                            //console && console.warn("addthis is not an object");
                                        }
                                    }).end();

                                    node.find('.add-addthis-button').each(function() {
                                        var addthis_pub = Constants.addthis_pub,
                                            node = $(this),
                                            script = $('<script>').attr({
                                                type: 'text/javascript'
                                            });
                                        node.append(script);
                                    }).end();

                                    node.find('p.close-dialog button').click(function() {
                                        node.dialog('close');
                                    });
                                }
                            })
                        };

                        $.get($(this).attr('href'), {}, function(response) {
                            var longcut = $(response);
                            showDialog(longcut);
                        });
                        return false;
                    },

                    // Show the product details in a popup window.
                    plain: function(e) {
                        e.preventDefault();
                        var href = $(this).attr('href'),
                            width = 710,
                            height = 710,
                            left = (screen.width / 2) - (width / 2),
                            top = (screen.top / 2) - (height / 2),
                            args = "toolbar=no,location=no,directories=no,status=yes,menubar=no," + 
                            	"scrollbars=yes,resizable=yes,copyhistory=no,width=" + width + 
                            	",height=" + height +",top=" + top + ",left=" + left,
                            popup = window.open(href, "popup", args);

                        return false;
                    }
                };

                var selectors = [
                        '#featured-products table.element-display tbody td a',
                        '#popup-test a, ul.product-grid-list a',
                        '#product-category-tabs table.product-grid-list tbody a'
                ];

                $(selectors.join(',')).unbind().each(function() {
                    var a = $(this),
                        toReplace = /productTemplate\.jsp/;

                    // Depending on whether or not the overlay is "fancy", change the urls to the product details accordingly.
                    if (!settings.overlay.fancy) {
                        a.attr('href', a.attr('href').replace(toReplace, "productTemplatePopup.jsp"));
                    } else {
                        a.attr('href', a.attr('href').replace(toReplace, "phase1to2/overlays/product/template.jsp"));
                    }
                }).click(((settings.overlay.fancy) ? showOverlay.fancy : showOverlay.plain));

            },

            // Add simple tabbing behavior to the popup window.
            popupTabs: function() {
                $('body.productDetailPopup').each(function() {
                    $(this).find('div.tabbed-interface').overlayTabs();
                })
            },

            // Change the custom "addthis:url" attribute to point to a url that does not contain the "Popup" string.
            // Thus when the link on the popup is shared via addthis, only the original product detail page will
            // be shared, and not the popup.
            tweakAddThis: function() {
                $('body.productDetailPopup').each(function() {
                    $(this).find('a.addthis_button').each(function() {
                        var link = $(this),
                            attrName = "addthis:url",
                            attrVal = link.attr(attrName);

                        attrVal = attrVal.replace(/productTemplatePopup\.jsp/, "productTemplate.jsp");
                        link.attr(attrName, attrVal);

                    });
                });
            },

            categoryTabs: function(after) {
                $('#product-category-tabs').overlayTabs({
                    compactHeaders: true,
                    after: [
                        after
                    ]
                });
            }
        };
    }

    $(document).ready(function() {
        // Make sure that addthis.com functionality is present
        if (typeof addthis !== "object") {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "http://s7.addthis.com/js/250/addthis_widget.js";
            document.getElementsByTagName("head")[0].appendChild(script);
        }
        var phaseChanger = new Phase1to2();
        try {
            phaseChanger.buildFromTemplates();
        } catch(e) {
            var a = [];
            for (var i in e) {
                a.push([i, e[i]].join(': '));
            }
            //alert(a.join('\n'));
        }
        phaseChanger.disableNofollowLinks();
        phaseChanger.testLightbox();
        phaseChanger.popupTabs();
        phaseChanger.tweakAddThis();
        phaseChanger.categoryTabs(phaseChanger.testLightbox);
        window.P1to2 = phaseChanger;
    });
}(jQuery));

