// Closure to run on the specs and docs page. It handles changes to the product line dropdown, clicks to the "show downloads" links,
// and colors the page.
(function($) {
    $(document).ready(function() {
        var select = $('#documentation-switcher');
        select.attr('selectedIndex', '0');
        var div = $('#specifications-and-documentation');
        var bundleClass = "documentation-bundle";
        var downloadClass = "download-info";

        // This will color every other visible <li> element on the page.
        var stripe = function() {
            div.find('.documentation-bundle > ul > li').removeClass('odd-row');
            div.find('.documentation-bundle > ul > li:visible').each(function(i) {
                if (i % 2 == 0) {
                    $(this).addClass("odd-row");
                }
            });
        };
        stripe(); // Go ahead and run it.

        // Runs each time the dropdown is changed.
        select.change(function() {
            var klass = $(this).val().replace(/\s/, '_');
            $('body').focus();
            if (klass.match(/ALL/)) {
               div.find(['.', bundleClass].pack()).show();
            } else {
                div.find(['.', bundleClass].pack()).hide().filter(['.', klass].pack()).show();
            }
            stripe(); // Re-stripe the page
        });

        // If an item has a property, then this function will add the item to a list.
        var busy = false;
        var add_item = function(list, json, description) {
			var li = $('<li>');
			var a = $(['<a target=\"_blank\" href="', json.url, '">', json.english, '</a>'].pack());
			li.append(a);
			var span = $('<span>');
			if (json.filesize && json.lastModified) {
				span = $(['<span>&nbsp;(', json.filesize, ' - ', json.lastModified, ')</span>'].pack());
			} else {
				span = $(['<span>&nbsp;(', json.filesize, ')</span>'].pack());
			}
			li.append(span);
			list.append(li);
		};

        // Functions for the various download links.
        $('.download-link').each(function() {
            // Give each link a false clicked expando attribute, because when the page loads obviously nothing has been clicked yet.
            $(this)[0].clicked = false;
            this.busy = false; // property to flip while the dom is being built. This keeps folks from clicking as fast as they possibly can.
        }).click(function() {
            var link = $(this);
            if (link[0].busy) {
                // Don't do anything if the already running click function is working.
                return false;
            }
            link[0].busy = true;
            // Flip the clicked expando property. This will show or hide certain elements later.
            $(this)[0].clicked = !$(this)[0].clicked;

            var parent = $(this).parents('li:first');
            // Is there already a download link?
            var downloadInfo = parent.find('.download-info');
            if (downloadInfo.length > 0) {
                // The specs and downloads links have already been retreived, so there's no need to do it again.
                // Just show/hide the info back and forth as many times as necessary.
                downloadInfo.slideToggle(500, function() {
                    link[0].busy = !link[0].busy
                });
                if (link[0].clicked) {
                    link.find('span').text('- Hide');
                } else {
                    link.find('span').text('+ Show');
                }
            } else {
                // Get it

                if (link.parents('li:first').hasClass('odd-row')) {
                    // Add a spinner with the gray background
                    link.addClass('documentation-loading-gray');
                } else {
                    // Add a spinner with the white background
                    link.addClass('documentation-loading-white');
                }
                var id = parent.ident();

                // Send the request
                $.get('/consumer/util/ajax/documentation.jsp', {productId: id}, function(data) {
                    parent.find('.download-info:gt(0)').remove();
                    // Make a box that holds the specs on the left, downloads on the right.
                    var info = $('<div class="download-info">');
                    var specs = $('<div class="specs">');
                    var brochures = $('<div class="brochures">');
                    var symbols = $('<div class="symbols">');
                    info.append(specs);
                    info.append(brochures);
                    info.append(symbols);

                    var json = data.parseJSON();

                    if (json.specifications) {
                        // Everything seems to have at least one Spec, so go ahead and add the header here.
                        var ul = $('<ul><li><p><strong>Specifications and Documentation</strong></p></li></ul>');
                        // These are the properties that we want to show in the "top" list.
                        var properties = ['specs', 'expandedSpec', 'pdgCustomPanels'];
                        $.each(properties, function(i) {
                            if (json.specifications[properties[i]]) {
                                add_item(ul, json.specifications[properties[i]]);
                            }
                        });
                        specs.append(ul); // End of first list

                        ul = $('<ul>');
                        // Properties for the "bottom" list.
                        properties = ['useAndCare', 'installation', 'tips', 'referenceGuide', 'doorPanelInstallation', 'energyGuide', 'sidePanelKitInstructions', 'addInstallInstructions', 'cabinetryGuide', 'undercounterSpecs', 'freestandingSpecs', 'freestandingInstructions', 'grilleKitInstructions', 'nonStickUseAndCare', 'knifeCareSharpeningTips', 'c4_cookbook', 'ventilationGuide', 'flushMountKit'];
                        $.each(properties, function(i) {
                           if (json.specifications[properties[i]]) {
                                add_item(ul, json.specifications[properties[i]]);
                           }
                        });
                        specs.append(ul); // End of second list
                        
                        info.append(specs);
                    }
                    
                    if (json.productBrochures) {
                    	var ul = $('<ul><li><p><strong>Brochures</strong></p></li></ul>');
                    	
                    	var prodBrochures = json.productBrochures;
                    	$.each(prodBrochures, function(i) {
                    		add_item(ul, prodBrochures[i]);                    		
                    	});
                    	brochures.append(ul); // End of third list
                    	//info.append(brochures);
                    	specs.append(brochures);
                    }

                    if (json.diagrams) {
                        var diagrams = $('<ul>');
                        var addHeader = false; // Not all products have these files, so don't show the CAD header if there's nothing there.
                        // Properties for top list
                        var properties = ['cad2dDxf', 'cad2dDwg'];
                        $.each(properties, function(i) {
                           if (json.diagrams[properties[i]]) {
                               addHeader = true;
                               add_item(diagrams, json.diagrams[properties[i]]);
                           }
                        });
                        symbols.append(diagrams);
                        var ul = $('<ul>');
                        // Properties for bottom list
                        properties = ['cad3dDxf', 'cad3dDwg'];
                        $.each(properties, function(i) {
                            if (json.diagrams[properties[i]]) {
                                addHeader = true;
                                add_item(ul, json.diagrams[properties[i]]);
                            }
                        });
                        symbols.append(ul);
                        // If any of the properties in this block existed, then we should show a header.
                        if (addHeader) {
                            diagrams.prepend('<li><p><strong>CAD Downloads</strong></p></li>');
                        }
                        info.append(symbols);
                    }
                    info.append("<div class='clear'></div>"); // Clean up
                    info.hide();
                    parent.append(info);
                    info.slideDown(500);

                    // Change the words based on the click state.
                    if (link[0].clicked) {
                        link.find('span').text('- Hide');
                    } else {
                        link.find('span').text('+ Show');
                    }
                    // Get rid of any spinners.
                    link.removeClass('documentation-loading-white documentation-loading-gray');
                    link[0].busy = false;
                });
            }
            return false;
        });
    });
})(jQuery);

/*
(function($) {
	$(document).ready(function() {
		$.addStylesheet('specs');
		var spinner = $('<img src="/consumer/images/decorations/loading.gif" />');
		var url = '/consumer/util/ajax/documentation.jsp';
		var params = {};

		var add_item = function(list, json, description) {
			var li = $('<li>');
			var a = $(['<a href="', json.url, '">', json.english, '</a>'].pack());
			li.append(a);
			var span = $('<span>');
			if (json.filesize && json.lastModified) {
				span = $(['<span>&nbsp;(', json.filesize, ' - ', json.lastModified, ')</span>'].pack());
			} else {
				span = $(['<span>&nbsp;(', json.filesize, ')</span>'].pack());
			}
			li.append(span);
			list.append(li);
		}

		var get = function(node) {
			var productId = node.ident().split(':')[1];
			var row = node.find('tr:first');
			params = { productId: productId }
			$.get(url, params, function(data) {
				$('.documentation-loading-white').removeClass('documentation-loading-white');
				$('.documentation-loading-gray').removeClass('documentation-loading-gray');
				var json = data.parseJSON();
				var specifications = json.specifications;
				var has = false;
				for (var i in specifications) {
					has = true;
					break;
				}
				if (has) {

					var div = $(['<div id="leftExpanded:', productId, '"></div>'].pack()).addClass('expanded-documentation-box');
					div.append('<p><strong>Specifications and Documentation</strong></p>');
					var ul = $('<ul></ul>');
					var properties = ['specs', 'expandedSpec', 'pdgCustomPanels'];
					$.each(properties, function(i) {
						if (specifications[properties[i]]) {
							add_item(ul, specifications[properties[i]]);
						}
					})
					div.append(ul);
					ul = $('<ul>');
					properties = ['useAndCare', 'installation', 'tips', 'referenceGuide', 'doorPanelInstallation', 'energyGuide', 'sidePanelKitInstructions', 'addInstallInstructions', 'cabinetryGuide', 'undercounterSpecs', 'freestandingSpecs', 'freestandingInstructions', 'grilleKitInstructions', 'nonStickUseAndCare', 'knifeCareSharpeningTips'];
					$.each(properties, function(i) {
					   if (specifications[properties[i]]) {
					        add_item(ul, specifications[properties[i]]);
					   }
					});
					div.append(ul);
					node.parents('td:first').prev().append(div);
				}
				if (json.diagrams) {
					var diagrams = json.diagrams;
					var has = false;
					for (var i in diagrams) {
						has = true;
						break;
					}
					if (has) {
						var div = $(['<div id="rightExpanded:', productId, '"></div>'].pack()).addClass('expanded-documentation-box');
						div.append('<p><strong>CAD Downloads</strong></p>');
						var ul = $('<ul>');
						var properties = ['cad2dDxf', 'cad2dDwg'];
						for (var i in properties) {
							if (diagrams[properties[i]]) {
								add_item(ul, diagrams[properties[i]]);
							}
						}
						div.append(ul);
						ul = $('<ul>');
						properties = ['cad3dDxf', 'cad3dDwg'];
						for (var i in properties) {
							if (diagrams[properties[i]]) {
								add_item(ul, diagrams[properties[i]]);
							}
						}
						div.append(ul);
						node.parents('td:first').append(div);
					}
				}
			});

		};

		var remove = function(node) {
			node.parents('td:first').find('div:last').remove()
			node.parents('td:first').prev().find('div:last').remove();
		};

        var loadingImage;
        // Preload the white loading image
        var img = new Image();
        img.src = '/consumer/images/decorations/loader-white.gif';
        loadingImage = $(img);

		var init = function(catalogName) {
			$('span.documentationDownload').click(function() {
				var span = $(this);
				//if (span[0].clicked || typeof span[0].clicked == "undefined") {
				var hasDocumentation = span.parents('td:first').find('.expanded-documentation-box').length > 0;
				if (!hasDocumentation) {
					span.text('- Hide Downloads');
					// find out if it's a white or gray row
					var white = true;
					if (!span.parents('tr:first').attr('class').match(/even/)) {
						white = false;
					}
					if (white) {
						span.parents('td:first').addClass('documentation-loading-white');
					} else {
						span.parents('td:first').addClass('documentation-loading-gray');
					}
					get(span);
				} else {
					span.text('+ Show Downloads');
					remove(span);
				}
				span[0].clicked = !span[0].clicked;
                if ($.browser.msie) {
                    // Prevent memory leaks
                    $(this)[0].onclick = null;
                }
			});

		    // make the "View All" selection selected on page load. this is used when the user
			// clicks the back button and all products are displayed
            // LOKVIK-1514 Actually don't reset to View All.
            if (!catalogName) {
			    $('#documentation-switcher').attr('selectedIndex', 0);
            } else {
                // Leave it alone
            }

            var parent = $('#specifications-and-documentation').parents(":first");

			$('#documentation-switcher').change(function() {
                var dropdown = $(this);
				var catalogName = dropdown.val();
                $('body').focus(); // Prevent accidental mouse-scrolling that changes the catalog name in the dropdown.
                if ($.browser.msie) {
                    $('.documentationDownload').each(function() {
                        $(this).unbind();
                    });
                    $('#specifications-and-documentation td, #specifications-and-documentation tr, #specifications-and-documentation tbody').each(function() {
                        $(this)[0] = null;
                    });
                }
                $('#specifications-and-documentation').html('<tr><td></td></tr>');
                $('#specifications-and-documentation').find('td').append(loadingImage);

				$.get("/consumer/util/ajax/documentation.jsp", { catalogName: catalogName }, function(data) {
					var payload = data.parseJSON();
					var table = $('<table id="specifications-and-documentation">');
					$.each(payload, function(i) {
						var json = payload[i];
						var category = json.category;
						var products = json.products;
						table.append(['<tr class="odd-row"><td colspan="2"><strong>', category, '</strong></td></tr>'].pack());
						var row_classes = ['even-row', 'odd-row'];
						$.each(products, function(j) {
							var name = products[j].name;
							var id = products[j].id;
							var productId = ['product', id].join(':');
							var left = ['left', id].join(':');
							var right = ['right', id].join(':');
							var klass = row_classes[j % 2];
							var tr = $(['<tr class="', klass, '"><td id="', left, '"></td><td id="', right, '"></td></tr>'].pack());
							table.append(tr);
							var a = $(['<a href="/consumer/products/product.jsp?id=', id, '">', name, '</a>'].pack());
							var span = $(['<span class="documentationDownload" id="', productId, '" clicked="false">+Show Downloads</span>'].pack());
							table.find('tr:last td:first').append(a);
							table.find('tr:last td:last').append(span);
						});
                        delete json;
					});
                    delete payload;
					$('#specifications-and-documentation').remove();
                    parent.append(table);
					init(catalogName);
				});
                if ($.browser.msie) {
                    $(this)[0].onchange = null;
                }
			});
		};

		if ($('#specifications-and-documentation').length > 0) {
			init();
		}
	});
})(jQuery);
*/        