(function ($) {
    //VALIDATION - GG
    //FORM, DATA, SHOW ERROR LIST
    var validateForm = function ($form, data, showerror) {
        var $err = $('.error-report');
        var $errlist = $err.find('#error-list');
        $errlist.empty();
        var valid = true;
        //alert(data);
        $('.required').each(function () {
            callback = function () { }
            // FOR INPUT
            var $input = $(this).find('input:first');
            var label = $(this).find('label').html();
            if ($input) {
                var value = $input.val();
                if (value === '') {
                    $(this).addClass('error');
                    $(this).keyup(function () {
                        $(this).removeClass('error');
                    });
                    $errlist.append('<li>' + label + '</li>');
                    valid = false;
                }
            }
            // FOR TEXTAREA
            var $textarea = $(this).find('textarea:first');
            var label = $(this).find('label').html();
            if ($textarea) {
                var value = $textarea.val();
                if (value === '') {
                    $(this).addClass('error');
                    $(this).keyup(function () {
                        $(this).removeClass('error');
                    });
                    $errlist.append('<li>' + label + '</li>');
                    valid = false;
                }
            }

        });
        if (valid != true) {
            /**
            if (showerror === 1) {
            setTimeout(function(){$err.slideDown({
            duration: 1200, 
            easing: 'easeOutElastic', 
            complete: callback});},280);
            }
            **/
            return false;
        }
        else {
            return;
        }
    };



    $(document).ready(function () {

        //HERO INIT

        // Count the number of tabs
        var countTabs = $('.random-tab').children().size();
        // Find a random number between 0 and the number of tabs (countTabs)
        var randomizeIt = Math.floor(Math.random() * (countTabs));

        //$("#tabs-vertical").tabs({ fx: { opacity: 'toggle', duration: '2000'} }).tabs("rotate", 0, true).show();
        $("#tabs-vertical").tabs({ fx: { opacity: 'toggle', duration: '2000'} }).tabs("rotate", 5000, true).show();
        $(".feature-container").hover(
			function () {
			    $("#tabs-vertical").tabs("rotate", 0, true);
			},
			function () {
			    //$("#tabs-vertical").tabs("rotate", 0, true);
			    $("#tabs-vertical").tabs("rotate", 5000, true);
			}
		);

        $('#tabs-vertical').tabs({
            selected: 0
        });

        $("#tabs-vertical li").click(function () {
            return $(this).find('a').click();
        });

        //TABS INIT

        $('.explore-tabs').tabs({
            event: 'click'
        }).show();

        $('#product-action').tabs({
            selected: randomizeIt
        });

        $("#tabs").tabs({
            event: 'click'
        }).show();

        $("#account-tabs").tabs({
            event: 'click'
        }).show();
        $('#profile-edit').click(function () {
            $('#account-tabs').tabs({
                selected: 1
            });
            $.scrollTo(0);
            return false;
        });

        var host = loadHost();
        var thisUrl = document.location.protocol + "//" + host;
        $('form.jqtransform').jqTransform({
            imgPath: thisUrl + '/assets/img/_forms/'
        }).show();

        //MORE INIT

        $('.datepicker').datepicker();

        $('#breadcrumbs').xBreadcrumbs({
            collapsible: true
        });

        //ACTIONS AND BUTTONS
        //RETAILES ON PRODUCT DETAILS PAGE - GG

        $('#findit-retailers-online li,#findit-retailers-store li').live('mouseover', function () {
            if ($(this).hasClass('available')) {
                $(this).css('background', '#ffe');
                $('#findit-retailers-header').css('background', '#fff');
                $('#findit-retailers-header > .retailer-logo').addClass($(this).attr('class'));
            }
        }).live('mouseout', function () {
            if ($(this).hasClass('available')) {
                $(this).css('background', '#fff');
                $('#findit-retailers-header').css('background', 'transparent');
                $('#findit-retailers-header > .retailer-logo').removeClass($(this).attr('class'));
            }
        });
        $('#findit-retailers-online li,#findit-retailers-store li').live('click', (function () {
            if ($(this).hasClass('available')) {
                $(this).find('a').trigger('click');
            }
        }));
        $('#findit-retailers a').each(function () {
            $(this).click(function () {
                if ($(this).parents('li').hasClass('available')) {
                    return;
                }
                else {
                    return false;
                }
            });
        });

        // /products/index.aspx
        $('#buy-button').click(function () {

            var host = loadHost();

            var thisUrl = document.location.protocol + "//" + host;
            // hidden field.  if 0 then redirect to an out of stock page
            var instock = $('#instock').val();
            var item_id = $('form#product-color-form option:selected').attr('id');
            var instock_variance = $('form#product-color-form option:selected').attr('instock');

            if (instock_variance == 'false') {
                alert('The item is out of stock');
                return false;
            }

            var item_id = item_id.replace('option', '');
            var item_qty = $('#product-quantity').val();
            //			if (instock == '0') {
            //				window.location.href = thisUrl + '/products/outofstock/' + item_id;
            //                return false; 
            //            }
            var newcount;
            $.ajax({
                url: thisUrl + "/shoppingcart/add",
                data: { id: item_id, qty: item_qty },
                dataType: "json",
                success: function (itemcount) {   // or some alternate callback            
                    newcount = $('.my-items').val(itemcount + (itemcount == '1' ? ' item' : ' items')).val();
                    $('.my-items').find('span').html(newcount);
                },
                type: "POST"
            });
            //  alert(newcount);
            $('.my-items').find('span');
            $.scrollTo(0);
            setTimeout(function () {
                $(".my-items").addClass('highlighted');
                setTimeout(function () {
                    $(".my-items").removeClass('highlighted').show();
                }, 6000);
            }, 800);
            return false;
        });

        // /shoppingcart/index.aspx
        // the final checkout button.  we just redirect to the shoppingcart controller's
        // save method which has an [authorize] attribute.  once the user's identity is 
        // established, save() redirects to checkout().  (same controller)
        $('.checkout-checkout').click(function () {
            var host = loadHost();
            if (host.match("/powera")) {
                var thisUrl = document.location.protocol + "//" + host;
                window.location.href = thisUrl + '/shoppingcart/save';
            }
            else {
                var thisUrl = document.location.protocol + "//" + host;
                window.location.href = thisUrl + '/shoppingcart/save';
            }
            return false;
        });

        // The "update" button (shoppingcart) 
        $('.toggle-update').click(function () {
            var host = loadHost();
            instock = $('#product-color option:selected').attr('instock');
            if (instock == 'false') {
                alert('The item is out of stock');
                return false;
            }
            id = $('input', this).val();
            var thisUrl = document.location.protocol + "//" + host;
            var base = thisUrl + '/shoppingcart/change/' + id;
            var qty = $(this).parents('.cart-item').find('input#product-quantity').val();

            if (qty < 0 || qty == '')
                window.location.href = thisUrl + '/shoppingcart';
            else {
                var color = $(this).parent().find('select[name="product-color"] option:selected').attr('id').replace('option', '');
                var url = base + '/?qty=' + qty + '&newid=' + color;
                window.location.href = url;
            }
        });

        //  shoppingcart remove button.  the product id is stored in a hidden field 
        $(".cart-option-remove").click(function () {
            var id = $(this).find('input:first').val();
            var $cartitem = $(this).parents('.cart-item');
            var host = loadHost();
            if (host.match("/powera")) {
                var thisUrl = document.location.protocol + "//" + host;
                callback = function () {
                    window.location.href = (thisUrl + '/shoppingcart/delete/' + id);
                }
                setTimeout(function () {
                    $cartitem.slideUp({
                        duration: 1200,
                        easing: 'easeOutBounce',
                        complete: callback
                    });
                }, 300);
            }
            else {
                var thisUrl = document.location.protocol + "//" + host;
                callback = function () {
                    window.location.href = (thisUrl + '/shoppingcart/delete/' + id);
                }
                setTimeout(function () {
                    $cartitem.slideUp({
                        duration: 1200,
                        easing: 'easeOutBounce',
                        complete: callback
                    });
                }, 300);
            }
            return false;
        });

        // /home/index.aspx - newsletter signup 
        $('#signupform').submit(function (e) {
            e.preventDefault();
            var host = loadHost();
            var thisUrl = document.location.protocol + "//" + host;
            var frm = $('#signupform');
            var frmData = frm.serialize();
            var emailAddress;
            var emailFld;

            if ($("#email").length > 0) {
                emailFld = $("#email");
            }
            else {
                emailFld = $("#email-signup");
            }
            emailAddress = $(emailFld).val();
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

            if (emailAddress = '' || !emailAddress.match(re)) {
                $('#signup-response').text('Please enter a valid email address.').css({ "color": "red", "display": "block", "font-size": "12px" });
                return false;
            }

            $.ajax({
                url: this.action + "?" + frmData,
                type: this.method,
                data: frmData,
                success: function (result) {
                    frm[0].reset();
                    $(emailFld).hide();
                    $('#signup-button').hide();
                    if (result == 1) {
                        $('#signup-response').show().css({ "font-size": "100%", "color": "#656565" }).html('Thank you! Please check your email.');
                    } else if (result == 0) {
                        $('#signup-response').show().css({ "font-size": "100%", "color": "#656565" }).html('You are already registered to receive updates from POWER A.<br/> Thank you for your interest!');
                        $('#signup-response-wrapper-news').css({ "width": "100%", "margin-right": "0px", "margin-top": "10px" });
                    } else if (result == -1) {
                        $('#signup-response').show().css({ "font-size": "100%", "color": "Red" }).html('Error');
                    }

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $(emailFld).hide();
                    $('#signup-button').hide();
                    $('#signup-response').show().css({ "color": "red", "display": "block", "font-size": "12px" }).html("Error sending form. Refresh your browser and try again.");
                },
                complete: function () {
                    //alert('done!');
                }

            });
        });













        // /account/forgotpassword.aspx
        $('#passwordresetbutton').click(function () {
            var host = loadHost();
            var thisUrl = document.location.protocol + "//" + host;
            if ($('#emailaddress').val() == '') return false;

            $.ajax({
                url: thisUrl + "/account/resetpasswordrequest",
                data: { emailaddress: $('#emailaddress').val() },
                success: function () {
                    $('#passwordresetform').fadeOut('slow');
                    $('#passwordreset-response').text('Please check your email. It may take a few minutes...');
                },
                type: "POST"
            });

            return false;
        })

        // FORMS - GARRETT GUYNN
        $('form#login-form,form#signup-form,form#profile-form,form#registration-form').submit(function () {
            //VALIDATION LAYER - GG
            //PREPATE STRING
            var $form = $(this);
            var data = $(this).serialize();
            $.scrollTo('.page-contents');
            return validateForm($form, data, 1);
        });

        // /home/community.aspx - feedback form
        $('form#community-form').submit(function (e) {
            e.preventDefault();
            var $form = $(this);
            var data = $(this).serialize();
            $.scrollTo('.community-form');
            var ret = validateForm($form, data, 0);

            if (typeof ret != 'undefined') return; //not sure where this undef is coming from. should be true or false.

            $.ajax({
                url: this.action,
                type: this.method,
                data: data,
                success: function () {
                    $form[0].reset();
                    $('#feedback-response').text('Thank you for your feedback.');
                }
            });
        });

        $('#search form').submit(function (e) {
            e.preventDefault();
            var value = $(this).find('#query-input').val();
            if (value === 'SEARCH' || value === '') {
                return false;
            }
            else {
                return submitQuery();
            }
        });

        $('a.ajaxsubmit').each(function () {
            $(this).click(function () {
                var $form = $(this).parents('form');
                $form.submit();

                //RETURN
                return;

            });
        });

        $('a#back-to-products-a').click(function () {
            if (document.referrer.indexOf("Browser.swf") > 0) {
                history.go(-1);
                return false;
            }
        });

        //AJAX FEEDS - GARRETT GUYNN
        var wordpressurl = 'http://50.18.47.94/html/wordpress/';
        var $feed = $('div.rssGET');
        $feed.livequery(function () {
            var $data = $(this).find('div.rssDATA');
            var string = $data.html();
            string = string.split('|');
            var url = string[0];
            var count = parseInt(string[1]);
            var blocktype = string[2];
            var $ajax = $(this).find('div.rssAJAX');
            $.jGFeed(url,
			function (feeds) {
			    // Check for errors
			    if (!feeds) {
			        // there was an error
			        return false;
			    }
			    // do whatever you want with feeds here
			    for (var i = 0; i < feeds.entries.length; i++) {
			        var entry = feeds.entries[i];
			        var link = entry.link;
			        var author = entry.author;
			        var string = entry.title;
			        string = string.split("|");
			        var title = string[0];
			        var postid = string[1];
			        var pdflink = (wordpressurl + 'wp-content/plugins/as-pdf/generate.php?post=' + postid);
			        var description = entry.content;
			        var date = entry.publishedDate;
			        var content = '';
			        if (blocktype == 'news') {
			            content = content + ("<div class='news-block'>");
			            content = content + ("<h4><a href='" + link + "' class='wordpress'>" + title + "</a></h4>");
			            content = content + ("<p class='posted'>" + date + "</p>")
			            content = content + ("<p>" + description + "&#8230</p>");
			            content = content + ("<p>&nbsp;<a href='" + link + "' class='wordpress'>Read Full Release &rsaquo;</a></p>");
			            content = content + ("</div>");
			        } else if (blocktype == 'aside-news') {
			            content = content + ("<li><p><a href='" + link + "' class='wordpress'>" + title + "</a>");
			            content = content + ("<br/>");
			            content = content + ("<em><span style='display:none'>" + author);
			            content = content + (" - " + date);
			            content = content + ("</span></em></p></li>");
			        } else if (blocktype == 'explore-news') {
			            date = date.split(" ");
			            content = content + ("<li>");
			            content = content + ('<div><span class="month">' + date[2] + '</span> <span class="day">' + date[1] + '</span></div>');
			            content = content + ("<a href='" + link + "' class='wordpress'>" + title + "</a>");
			            //content = content + (" <em>" + author + "</em>");
			            content = content + ("</li>");
			        } else if (blocktype == 'press') {
			            content = content + ("<div class='news-block'>");
			            content = content + ("<h4><a href='" + link + "' class='wordpress'>" + title + "</a></h4>");
			            content = content + ("<p class='posted'>" + date + "</p>")
			            content = content + ("<p>" + description + "</p>");
			            content = content + ("<p><a href='" + pdflink + "' class='pdflink'><em><img src='/assets/img/explore-pdf-sm.gif' class='va'/> Download</em></a></p>");
			            content = content + ("</div>");
			        } else if (blocktype == 'aside-press') {
			            content = content + ("<li><p><a href='" + link + "' class='wordpress'>" + title + "</a>");
			            content = content + ("<br/>");
			            content = content + ("<a href='" + pdflink + "' class='pdflink'><img src='/assets/img/explore-pdf-sm.gif' class='va'/> <em>Download</em></a>");
			            content = content + ("<em> | " + date + "</em>");
			            content = content + ("</p></li>");
			        } else if (blocktype == 'explore-press') {
			            content = content + ("<li>");
			            content = content + ("<a href='" + link + "' class='wordpress'>" + title + "</a><em>");
			            content = content + ("<a href='" + pdflink + "' class='pdflink'>Download</a> ");
			            content = content + (" | " + date);
			            content = content + ("</em></li>");
			        } else if (blocktype == 'topic') {
			            content = content + ("<li><a href='" + link + "' class='wordpress'>" + title + "</a></li>");
			        } else if (blocktype == 'support') {
			            content = content + ("<li><a href='" + link + "' class='wordpress'>" + title + "</a></li>");
			        }
			        $ajax.append(content);
			    }
			}, count);
        });

        //MORE ACTIONS AND BUTTONS

        var $items = $('#vtab>ul>li');
        $items.mouseover(function () {
            $items.removeClass('selected');
            $(this).addClass('selected');
            var index = $items.index($(this));
            $('#vtab>div').hide().eq(index).show();
        }).eq(1).mouseover();

        $("div.cart-holder .cart-option-edit").each(function () {
            var $row = $(this).parents(".cart-item");
            var $checkout = $row.find(".cart-pre-checkout");
            $checkout.css('visibility', 'hidden');
            $checkout.show();
            $checkout.find('.product-color-form').jqTransform();
            $checkout.hide();
            $checkout.css('visibility', 'visible');
            $(this).click(function () {
                var callback = function () {
                    $row.find('.product-color-form').show();
                }
                setTimeout(function () {
                    $checkout.slideToggle('200');
                }, 100);

            });
        });
        $('.cart-print a').click(function () {
            window.print();
            return false;
        });
        // Inner - Close Panel
        $("#close-panel").click(function () {
            $("div#panel").slideUp("slow");
        });

        $('img').each(function () {
            var $a = $(this).parents('a');
            $a.css('text-decoration', 'none!important');
        });

        try {

            $('.buy-button,.help-button,.cart-help-button,.checkout-checkout,.small-button a, #signupform #signup-button').append('<span class="hover"></span>').each(function () {
                if ($.browser.msie && ($.browser.version != "8.0" && $.browser.version != "7.0") || !$.browser.msie) {
                    var $span = $('> span.hover', this).css('opacity', 0);
                    $(this).hover(function () {
                        $span.stop().fadeTo(500, 1);
                    }, function () {
                        $span.stop().fadeTo(500, 0);
                    });
                }
                else {
                    var $span = $('> span.hover', this).hide();
                    $(this).hover(function() {
                        $span.show();
                    }, function() {
                        $span.hide();
                    });
                }
            });
        }
        catch (e) {
            // alert("error." + e.description.toString()); 
        }

        //CHECKOUT SHIPPING PULLDOWN -GG
        $('.checkout-quantity-holder li a').click(function () {
            $(this).parents('.checkout-quantity-holder').find('li a.selected').each(function () {
                var string = $(this).html();
                string = string.split('$');
                var cost = ('$' + string[1]);
                $('.checkout-shipping-price p').html(cost);
                var total = (parseFloat($('.checkout-shipping-price p').text().replace(/\$/, '').replace(/\,/, ''))
                    + parseFloat($('.checkout-subtotal p').text().replace(/\$/, '').replace(/\,/, ''))).toFixed(2);
                $('.checkout-price').text('$' + total);
            });
        });

        var $color_wrapper = $('div.checkout-quantity-holder"');

        $('#birthday').datepicker();
        //COUNT CHARS IN TEXTAREA
        $('textarea.maxfield').keyup(function () {
            var $maxspan = $('span#maxchar');
            if ($(this).val() === '') {
                $maxspan.html('Max 255 characters');
            }
            else {
                var count = parseInt('255') - parseInt(this.value.replace(/{[^}]*}/, '').length);
                if (count <= '-1') {
                    $maxspan.text('Max characters exceeded!');
                }
                else {
                    $maxspan.text(count + ' characters left');
                }
            }
        });

        $("a.fancybox, a.inline-fancybox").fancybox({
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'centerOnScroll': true
        });

        $("a.wordpress").livequery(function () {
            $(this).fancybox({
                'width': 625,
                'autoDimensions': true,
                'autoScale': true,
                'transitionIn': 'elastic',
                'titleShow': false,
                'transitionOut': 'elastic',
                'centerOnScroll': true,
                'type': 'iframe'
            });
        });

    });
    //END DOCUMENT READY



































    //ACTIVE RETAILERS ON PRODUCT DETAILS PATE
    initActiveRetailers = function (url, sku) {
        $.ajax({
            type: "GET",
            url: url,
            dataType: "xml",
            success: function (xml) {
                $(xml).find('Product > SKU').each(function () {
                    if ($(this).text() === sku) {
                        $(this).parents('Product').find('Retailer > Name').each(function () {
                            var retailer = $(this).text();
                            if (retailer === 'Tru') {
                                $('li.retailer-toys-r-us').addClass('available');
                            }
                            if (retailer === 'amazon.com') {
                                $('li.retailer-amazon').addClass('available');
                            }
                            if (retailer === 'tru.com') {
                                $('li.retailer-toys-r-us').addClass('available');
                            }
                            if (retailer === 'Best Buy') {
                                $('li.retailer-best-buy').addClass('available');
                            }
                            if (retailer === 'bestbuy.com') {
                                $('li.retailer-best-buy').addClass('available');
                            }
                            if (retailer === 'target.com') {
                                $('li.retailer-target').addClass('available');
                            }
                            if (retailer === 'Gamestop') {
                                $('li.retailer-gamestop').addClass('available');
                            }
                            if (retailer === 'gamestop.com') {
                                $('li.retailer-gamestop').addClass('available');
                            }
                            if (retailer === 'Fred Meyer') {
                                $('li.retailer-fred-meyer').addClass('available');
                            }
                            if (retailer === 'Target') {
                                $('li.retailer-target').addClass('available');
                            }
                            if (retailer === 'Kmart') {
                                $('li.retailer-kmart').addClass('available');
                            }
                            if (retailer === 'Meijer') {
                                $('li.retailer-meijer').addClass('available');
                            }
                            if (retailer === 'Sams Club') {
                                $('li.retailer-sams-club').addClass('available');
                            }
                            if (retailer === 'samsclub.com') {
                                $('li.retailer-sams-club').addClass('available');
                            }
                            if (retailer === 'Walmart') {
                                $('li.retailer-walmart').addClass('available');
                            }
                            if (retailer === 'walmart.com') {
                                $('li.retailer-walmart').addClass('available');
                            }
                            if (retailer === 'Frys') {
                                $('li.retailer-frys').addClass('available');
                            }
                        });
                    }
                });
            }
        });
    }
    //PRODUCT REGISTRATION SCRIPT
    //PARSES XML AND PROVIDES INTERATION SELECTING PRODUCT
    //~GARRETT GUYNN
    initSupport = function (url) {
        $.ajax({
            type: "GET",
            url: url,
            dataType: "xml",
            success: function (xml) {
                // checks the page to see if the warranty filter is required.
                var warranty = $("#warrantyfilter").val();
                function trim(str) {
                    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
                }
                function removeDuplicates(inputArray) {
                    var i;
                    var len = inputArray.length;
                    var outputArray = [];
                    var temp = {};
                    for (i = 0; i < len; i++) {
                        temp[inputArray[i]] = 0;
                    }
                    for (i in temp) {
                        i = trim(i);
                        outputArray.push(i);
                    }
                    return outputArray;
                }
                function showProductsSelect() {
                    var $select_sku = $('#select-sku');
                    var product_name = '';
                    var product_sku = '';
                    $(xml).find('Product > Name').each(function () {
                        var sku = $(this).parents('Product').find('SKU').text();
                        var color = $(this).parents('Product').find('Color > Name').text();
                        if (color === 'ONE COLOR') {
                            color = '';
                        }
                        else {
                            color = (' (' + color + ')');
                        }
                        if (warranty == null || $(this).parents('Product').find('Warranty').text() == 'true') {
                            product_name = (product_name + sku + '-' + $(this).text() + color + '#!');
                            product_sku = (product_sku + sku + '#!');
                        }
                    });
                    var array = product_name.split('#!');
                    var product_name = removeDuplicates(array);
                    var product_sku = product_sku.split('#!');
                    $(product_name).each(function (key, value) {
                        if ((value !== '') && (product_sku[key] != '')) {
                            $select_sku.append('<option value="' + product_sku[key] + '">' + value + '<' + '/' + 'option>');
                        }
                    });

                    // set a default sku
                    var defaultSKU = $('#select-sku').val();
                    $('#skuno').val(defaultSKU);


                    return;
                }
                function showRetailersSelect() {
                    var $retailer = $('select#Location');
                    $retailer.append('<option value="amazon">Amazon</option><option value="apple">Apple Store</option><option value="bestbuy">Best Buy</option><option value="gamestop">GameStop</option><option value="kmart">Kmart</option><option value="samsclub">Sam\'s Club</option><option value="sears">Sears</option><option value="target">Target</option><option value="toysrus">Toys \'R\' Us</option><option value="walmart">Walmart</option>');
                    return;
                }
                function createOptions($select) {
                    var system_name = '';
                    $(xml).find('System > Name').each(function () {
                        if (warranty == null || $(this).parents('Product').find('Warranty').text() == 'true') {
                            system_name = (system_name + $(this).text() + '#!');
                        }
                    });
                    var array = system_name.split('#!');
                    var system_name = removeDuplicates(array);
                    $select.append('<select id="select-system" size="' + (system_name.length) + '"><option selected value="">--select--</option></select>');
                    var $select_system = $('#select-system');
                    $(system_name).each(function (key, value) {
                        if (value !== '') {
                            $select_system.append('<option value="' + value + '">' + value + '<' + '/' + 'option>');
                        }
                    });
                    return $select.append('<select id="select-product-type" size="' + (system_name.length) + '"><option selected value="">--select--</option></select><select id="select-theme" size="' + (system_name.length) + '"><option selected value="">--select--</option></select>');
                }
                function createTypes(system) {
                    var $select_product_type = $('#select-product-type');
                    var product_type = '';
                    $(xml).find('System > Name').each(function () {
                        if ((warranty == null || $(this).parents('Product').find('Warranty').text() == 'true') &&
						    $(this).text() === system) {
                            product_type = (product_type + $(this).parents('Product').find('ProductType > Name:first').text() + '#!');
                        }
                    });
                    var array = product_type.split('#!');
                    var product_type = removeDuplicates(array);
                    $(product_type).each(function (key, value) {
                        if ((value !== '') && (value !== 'Basic Essentials')) {
                            $select_product_type.append('<option value="' + value + '">' + value + '<' + '/' + 'option>');
                        }
                    });
                    return;
                }
                function createThemes(system, type) {
                    var $select_product_type = $('#select-product-type');
                    var $select_theme = $('#select-theme');
                    var product_theme = '';
                    $(xml).find('System > Name').each(function () {
                        if ((warranty == null || $(this).parents('Product').find('Warranty').text() == 'true') &&
							($(this).text() === system) &&
							($(this).parents('Product').find('ProductType > Name').text() === type)) {
                            product_theme = (product_theme + $(this).parents('Product').find('Theme > Name:first').text() + '#!');
                        }
                    });
                    var array = product_theme.split('#!');
                    var product_theme = removeDuplicates(array);
                    $(product_theme).each(function (key, value) {
                        if (value !== '') {
                            $select_theme.append('<option value="' + value + '">' + value + '<' + '/' + 'option>');
                        }
                    });
                    return;
                }
                function filterProducts(system, type, theme) {
                    var $select_sku = $('#select-sku');
                    $select_sku.empty();
                    var product_name = '';
                    var product_sku = '';
                    $(xml).find('Product > Name').each(function () {
                        var sku = $(this).parents('Product').find('SKU').text();
                        var color = $(this).parents('Product').find('Color > Name').text();
                        var warr = $(this).parents('Product').find('Warranty').text();
                        if ((type === '') && (theme === '') && (warranty == null || warranty == warr)) {
                            if ($(this).parents('Product').find('System > Name:first').text() === system) {
                                product_name = (product_name + sku + '-' + $(this).text() + ' (' + color + ')' + '#!');
                                product_sku = (product_sku + sku + '#!');
                            }
                        }
                        else if (theme === '') {
                            if (($(this).parents('Product').find('System > Name:first').text() === system) &&
							    ($(this).parents('Product').find('ProductType > Name:first').text() === type) &&
								(warranty == null || warranty == warr)) {
                                product_name = (product_name + sku + '-' + $(this).text() + ' (' + color + ')' + '#!');
                                product_sku = (product_sku + sku + '#!');
                            }
                        }
                        else {
                            if (($(this).parents('Product').find('System > Name:first').text() === system) &&
							    ($(this).parents('Product').find('ProductType > Name:first').text() === type) &&
								($(this).parents('Product').find('Theme > Name:first').text() === theme) &&
								(warranty == null || warranty == warr)) {
                                product_name = (product_name + sku + '-' + $(this).text() + ' (' + color + ')' + '#!');
                                product_sku = (product_sku + sku + '#!');
                            }
                        }
                    });

                    var array = product_name.split('#!');
                    var product_name = removeDuplicates(array);
                    var product_sku = product_sku.split('#!');
                    $(product_name).each(function (key, value) {
                        if ((value !== '') && (product_sku[key] != '')) {
                            $select_sku.append('<option value="' + product_sku[key] + '">' + value + '<' + '/' + 'option>');
                        }
                    });

                    // set a default sku
                    var defaultSKU = $('#select-sku').val();
                    $('#skuno').val(defaultSKU);

                    return;
                }
                //INIT
                showProductsSelect();
                showRetailersSelect();
                var $select = $('#select-module');
                createOptions($select);
                //INTERACTION
                var $select_system = $('#select-system');
                var $select_product_type = $('#select-product-type');
                var $select_theme = $('#select-theme');
                $select_system.livequery(function () {
                    $(this).change(function () {
                        $select_product_type.html('<option selected value="">--select--</option>');
                        $select_theme.html('<option selected value="">--select--</option>');
                        var system = $(this).val();
                        if (system === '') {
                            showProductsSelect();
                        }
                        else {
                            filterProducts(system, '', '');
                            createTypes(system);
                        }
                        return;
                    });
                });
                $select_product_type.livequery(function () {
                    $(this).change(function () {
                        $select_theme.html('<option selected value="">--select--</option>');
                        var system = $select_system.val();
                        var type = $(this).val();
                        if (type === '') {
                            return false;
                        }
                        else {
                            filterProducts(system, type, '');
                            createThemes(system, type);
                        }
                        return;
                    });
                });
                $select_theme.livequery(function () {
                    $(this).change(function () {
                        var system = $select_system.val();
                        var type = $select_product_type.val();
                        var theme = $(this).val();
                        if (type === '') {
                            return false;
                        }
                        else {
                            filterProducts(system, type, theme);
                        }
                        return;
                    });
                });

                $('#select-sku').change(function () {
                    var selectedSKU = $(this).val();
                    $('#skuno').val(selectedSKU);
                });

            }
        });

    };



})(jQuery);

// Activates form placeholders for FF and IE
function activatePlaceholders() {
    var detect = navigator.userAgent.toLowerCase();
    if (detect.indexOf("safari") > 0) return false;
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].getAttribute("type") == "text") {
            if (inputs[i].getAttribute("placeholder") && inputs[i].getAttribute("placeholder").length > 0) {
                inputs[i].value = inputs[i].getAttribute("placeholder");
                inputs[i].onclick = function(){
                    if (this.value == this.getAttribute("placeholder")) {
                        this.value = "";
                    }
                    return false;
                }
                inputs[i].onblur = function(){
                    if (this.value != null && this.value != "nAn" && this.value.length < 1) {
                        this.value = this.getAttribute("placeholder");
                    }
                }
            }
        }
    }
}

function loadHost()
{
	var host = document.location.host;
	if (host != 'www.powera.com' && host != 'powera.com') {
		host = host + '/powera';
	}
	return host;
}

window.onload = function() {
    activatePlaceholders();
};


jkmegamenu.definemenu("megaanchor1", "megamenu1", "mouseover");
jkmegamenu.definemenu("megaanchor2", "megamenu2", "mouseover");
jkmegamenu.definemenu("megaanchor3", "megamenu3", "mouseover");

// Detect enter keydown and submit form if exists on page.
$().ready(function() {
   	$(document).bind('keydown', function (evt) {
   		if ($('form') != null &&
			evt.keyCode == 13) {
   			$('form').submit();
   		}
   	});
});

