﻿function registerNS(ns) {
    var nsParts = ns.split(".");
    var root = window;

    for (var i = 0; i < nsParts.length; i++) {
        if (typeof root[nsParts[i]] == "undefined")
            root[nsParts[i]] = new Object();

        root = root[nsParts[i]];
    }
}

function GetQueryString(key, defaultValue) {
    if (defaultValue == null) defaultValue = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return defaultValue;
    else
        return qs[1];
}

function FancyBoxPop(str, redirUrl) {
    // set hidden field that will tell login form where to redirect user after successful login
    if (redirUrl) {
        if (str == 'signup') {
            document.getElementById('hfRegisterReturnUrl').value = redirUrl;
        } else {
            document.getElementById('hfLoginReturnUrl').value = redirUrl;
        }
    }
    $('#' + str + '-btn').click();
}

registerNS("String");
String.Format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }

    return s;
}

// Universal AJAX settings for jQuery. Can be overridden on each individual call.
$.ajaxSetup({
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8"
});

registerNS("Meguiars");

// Used for functionality that needs the language code (mainly services)
// Default to English.
Meguiars.LanguageCode = "en";
Meguiars.SessionKey = "";

Meguiars.GetDictionaryItem = function (key) {
    if (typeof languageItems != 'undefined' && key in languageItems)
        return languageItems[key];
    return "";
}

/* Fixes link button so that it can be used as a default button.
*/
Meguiars.FixLinkButton = function (clientId) {
    var b = document.getElementById(clientId);

    if (b != null) {
        b.click = function () {
            var result = true;
            if (b.onclick) result = b.onclick();
            if (typeof (result) == 'undefined' || result) {
                eval(b.getAttribute('href'));
            }
        }
    }
}

Meguiars.AlignSite = function () {
    //design width 1260px, min window view support 1024px
    //$('.siteWrapper').css('left', Math.round(($(window).width() - 1260) / 2));
    $('.numButtonHolder').css('left', Math.round(($('.circularMenu').width() - ($('.numButtonHolder li').length * 22)) / 2));

    /* moved to initializeSite() because the menus got additional events when the window was resized - Ross Higgins 11/2/2011
    $('.menu').click(function (event) {
        event.preventDefault();
        $(this).next('.a_menu').slideToggle();
    });
    */
}

Meguiars.HandleMessage = function (message, redirectUrl, mustBeLoggedIn) {
    // If must be logged in, show login popup
    if (mustBeLoggedIn == undefined || mustBeLoggedIn == null || mustBeLoggedIn == "")
        mustBeLoggedIn = false;

    if (mustBeLoggedIn) {
        Meguiars.OpenLoginPopup(redirectUrl);
        return;
    }

    if (redirectUrl != undefined && redirectUrl != '')
        window.location = redirectUrl;
    else {
        Meguiars.ShowMessage(message);
    }
}

Meguiars.ShowDictionaryMessage = function (key) {
    Meguiars.ShowMessage(Meguiars.GetDictionaryItem(key));
}

Meguiars.ShowMessage = function (message) {
    // Using basic alert for now. Swap out for something else down the line. Boxy? jQuery UI dialog?
    //alert(message);
	$.fancybox(message, {
		'padding': 25
	});
}

Meguiars.SetSessionKey = function (sessionKey) {
    if (sessionKey != null && sessionKey != '')
        Meguiars.SessionKey = sessionKey;
}

Meguiars.SetLanguageCode = function (languageCode) {
    if (languageCode != null && languageCode != '')
        Meguiars.LanguageCode = languageCode;
}

Meguiars.InitializeSite = function ()
{

    Meguiars.AlignSite();
    //$('select').selectbox();
    $("#carousel").CloudCarousel({
        xPos: 470,
        yPos: 32,
        xRadius: 420,
        yRadius: 20,
        minScale: 0.15,
        speed: 0.1,
        buttonLeft: $("#left-but"),
        buttonRight: $("#right-but"),
        numButton: $("ul.numButton li")
    });

    $('.menu').click(function (event)
    {
        event.preventDefault();
        $(this).next('.a_menu').slideToggle();
    });

    //make default expand for all group list items, Consumer, Products, Videos
    $('.menu').click();

    Meguiars.InitializePasswordField();

    $(window).resize(function ()
    {
        Meguiars.AlignSite();
    });

    // Wire up signup, login, and forgot password modals
    $("#signup-btn").fancybox({
        'overlayColor': '#000',
        'overlayOpacity': 0.7,
        autoDimensions: true
    });

    $("#login-btn").fancybox({
        'overlayColor': '#000',
        'overlayOpacity': 0.7,
        autoDimensions: false,
        height: 230,
        onComplete: function () { $("#login1_txtUsername").focus(); }
    });

    $(".forgotpw-btn").fancybox({
        'overlayColor': '#000',
        'overlayOpacity': 0.7,
        autoDimensions: false,
        height: 190
    });

    // See if we should show popup
    var showLogin = GetQueryString("showLogin", 0);
    if (showLogin)
    {
        var redirectUrl = GetQueryString("redirectUrl", String.Format("/{0}/my-garage/", Meguiars.LanguageCode));
        Meguiars.OpenLoginPopup(redirectUrl);
    }
}

Meguiars.FinalizeSite = function () {
    // Exclude rating select box since it's using the raty control
    $("select").not("#ddlRating").selectmenu();

    // For review grand wrapup!
    var grandRating = $("#hdnGrandReviewRating");
    if (grandRating.length > 0) {
        $("#grandReviewRatingHolder").raty({
            readOnly: true,
            start: grandRating.val(),
            path: '/images/'
        });
    }

    var ddlRating = $("#ddlRating");
    if (ddlRating.length > 0) {
        $("#ratingSelector").raty({
            path: '/images/',
            start: ddlRating.val(),
            click: function (score, evt) {
                ddlRating.val(score);
            }
        });
    }

    // For review listing
    $("div.reviewHolder div.rating").each(function () {
        // Get rating
        var rating = $(this).find(".hdnRating").val();

        // Wire up stars
        $(this).find(".ratingHolder").raty({
            readOnly: true,
            start: rating,
            path: '/images/'
        });
    });
}

Meguiars.OpenLoginPopup = function (redirectUrl) {
    FancyBoxPop("login", redirectUrl);
}

Meguiars.InitializeProductListingPage = function ()
{    
    // Set hover over functionality. Grab the content from the div inside each item
    $("div.productListingItem").each(function ()
    {
        var productId = $(this).find(".productListingItem_productId").val();
        var content = $("#productHover_" + productId).html();

        $(this).qtip(
        {
            content: content,
            position: {
                corner: {
                    target: 'topMiddle',
                    tooltip: 'bottomMiddle'
                },
                adjust: {
                    screen: true
                }
            },
            style: { width: 300, padding: 20 },
            hide: { when: 'mouseout', fixed: true }
        });
    });

    if ($("body").hasClass("ff7") || $("body").hasClass("ff8"))
    {
        // firefox 7 doesnt display the qTip tooltips in the correct position when used with isotope
        $('#productListing').isotope({
            itemSelector: '.productListingItemHolder',
            transformsEnabled: false
        });
    } else
    {
        $('#productListing').isotope({
            itemSelector: '.productListingItemHolder'
        });
    }

    $('.tagGroup input[type=checkbox], .all-selector').live('click', function ()
    {
        var selectors = '';

        //always clear selected items cookies
        ClearProductsSelectedItems();

        if ($(this).hasClass('all-selector'))
        {
            selectors = '*';
            $('.tagGroup input[type=checkbox]').removeAttr('checked');
        } else
        {
            var tagGroup = $('.tagGroup');
            tagGroup.each(function ()
            {
                var checkGroup = $(this).find('input[type=checkbox]:checked');
                if (checkGroup.length != 0)
                {
                    checkGroup.each(function ()
                    {
                        selectors += $.trim($(this).siblings('label').attr('data-filter'));
                    });
                    selectors += ', ';
                }
            });

            if (selectors.length == 0) { selectors = '*' }

        }

        $('#productListing').isotope({ filter: selectors });

        var totalLeft = $(".productListingItemHolder").not(".isotope-hidden").length;
        if (totalLeft == 0)
        {
            Meguiars.ShowDictionaryMessage("No Products Left After Filtering Message");
        }

        //preserve products selected items in cookies
        SaveProductsSelectedItems();
    });

    //set selected items filter
    //note: this method only call the end
    SetProductsSelectedItemsByCookies();
}

Meguiars.InitializeDealerListingPage = function () {
    $("div.hoverInfo").each(function () {
        var content = $(this).find('.dealerHover').html();
        //var content = '<p>testing</p>';
        $(this).qtip({
            content: content,
            style: {
                width: 300,
                height: 300,
                padding: 15
            },
            position: {
                adjust: {
                    screen: true
                }
            },
            hide: {
                when: 'mouseout',
                fixed: true,
                delay: 500 
            },
            api: {
                onShow: function () {
                    fleXenv.initByClass("qtip-content");
                }
            }
        });
    });
}

Meguiars.InitializeVideoListingPage = function () {
    // Set hover over functionality. Grab the content from the div inside each item
    $("div.videoListingItemHolder").each(function () {
        var videoListingItem = $(this).find("div.videoListingItem");
        var videoId = $(this).find(".videoListingItem_videoId").val();
        var content = $("#videoHover_" + videoId).html();
        var imageAnchor = $(this).find(".image a");
        var hoverAnchor = $(this).find(".videoHover a");

        imageAnchor.click(function (event) {
            event.preventDefault();
            Meguiars.GetVideoPopup(videoId);
        });

        videoListingItem.qtip(
        {
            content: content,
            position: {
                corner: {
                    target: 'topMiddle',
                    tooltip: 'bottomMiddle'
                },
                adjust: {
                    screen: true
                }
            },
            style: { width: 300, padding: 20 },
            hide: { when: 'mouseout', fixed: true }
        });
    });


    $('#videoListing').isotope({
        itemSelector: '.videoListingItemHolder'
    });

    $('.tagGroup input[type=checkbox], .all-selector').live('click', function () {
        var selectors = '';

        if ($(this).hasClass('all-selector')) {
            selectors = '*';
            $('.tagGroup input[type=checkbox]').removeAttr('checked');
        } else {
            var checkGroup = $('.tagGroup input[type=checkbox]:checked');
            if (checkGroup.length == 0) {
                selectors = '*';
            } else {
                checkGroup.each(function () {
                    selectors += '.' + $.trim($(this).siblings('label').attr('data-filter'));
                });
            }
        }

        $('#videoListing').isotope({ filter: selectors });

        var totalLeft = $(".videoListingItemHolder").not(".isotope-hidden").length;
        if (totalLeft == 0) {
            Meguiars.ShowDictionaryMessage("No Videos Left After Filtering Message");
        }
    });
}

Meguiars.ClearIsotopeCheckboxes = function () {
    $('.tagGroup input[type=checkbox]').removeAttr('checked');
}

Meguiars.GetVideoPopup = function (videoId) {
    $.ajax({
        type: "GET",
        url: "/services/video.svc/GetVideoPopup",
        data: { videoId: videoId },
        dataType: "json",
        success: function (result) {
            var resp = result.d;
            $.fancybox(result.d, {
                'autoDimensions': true,
                onComplete: function () {
                    fleXenv.fleXcrollMain("ctl01_productsInVideo");
                }  
            });
        }
    });
}

Meguiars.InitializeProductPage = function () {
    Meguiars.WireUpCommunityVehiclesForProduct();

    $("div.videoHolder").each(function () {
        var videoId = $(this).find(".videoHolder_videoId").val();
        var anchor = $(this).find("a");

        anchor.click(function (event) {
            event.preventDefault();
            Meguiars.GetVideoPopup(videoId);
        });
    });
    
    $(document).ready(function () {
        $('.tabs ul li a').live('click', function () {
            var tabPage = $(this).attr('rel');
            $('.tabs ul li').removeClass('current');
            $(this).parent().addClass('current');
            $('.tabs .tab-wrapper div.tab-body').removeClass('current');
            $('.tabs .tab-wrapper .tab-' + tabPage).addClass('current');
        });
    })
}

Meguiars.WireUpCommunityVehiclesForProduct = function () {
    var productId = $("#hdnProductId").val();

    // Wire up next/previous clicks
    $("#aPrevious").click(function (event) {
        event.preventDefault();
        var sequenceId = $("#hdnPreviousSequenceId").val();
        var imageId = $("#hdnPreviousImageId").val();
        Meguiars.GetCommunityVehiclesForProduct(productId, sequenceId, imageId);
    });

    $("#aNext").click(function (event) {
        event.preventDefault();
        var sequenceId = $("#hdnNextSequenceId").val();
        var imageId = $("#hdnNextImageId").val();
        Meguiars.GetCommunityVehiclesForProduct(productId, sequenceId, imageId);
    });

    var currentShowcaseImageId = $("#hdnCurrentImageId");
    if (currentShowcaseImageId.length > 0) {
        Meguiars.WireUpReportImageForProductPage(currentShowcaseImageId.val());
    }
}

// Loads the community vehicle block and replaces the existing community vehicle block with the response
Meguiars.GetCommunityVehiclesForProduct = function (productId, sequenceId, showcaseImageId) {
    $.ajax({
        type: "GET",
        url: "/services/showcase.svc/GetCommunityVehicles",
        data: { showcaseImageId: showcaseImageId, sequenceId: sequenceId, productId: productId },
        dataType: "json",
        success: function (result) {
            var resp = result.d;
            $("#communityVehiclesHolder").html(resp);
            Meguiars.WireUpCommunityVehiclesForProduct();

            // Okay, setup report functionality
            Meguiars.WireUpReportImageForProductPage(showcaseImageId);
        }
    });
}

Meguiars.WireUpReportImageForProductPage = function (showcaseImageId) {
    $("#reportImage").click(function (event) {
        event.preventDefault();
        $(this).hide();
        $("#reportImageOptionsHolder").show();
        $("#reportImageOptions").selectmenu();
    });

    $("#reportImageOptions").change(function () {
        $("#reportImageOptionsHolder").hide();

        var reportTypeId = $(this).val();
        
        var data = { showcaseImageId: showcaseImageId, reportTypeId: reportTypeId, languageCode: Meguiars.LanguageCode };
        $.ajax({
            url: "/services/showcase.svc/ReportShowcaseImage",
            data: JSON.stringify(data),
            success: function (result) {
                var resp = result.d;
                if (resp.Success) {
                    Meguiars.ShowMessage(resp.Message);
                    $("#reportImage").show();
                    $("#reportImageOptions").val("");
                }
                else {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                }
            }
        });
    });
}

Meguiars.InitializeMyGaragePage = function () {
    $("a.deleteShowcase").click(function (event) {
        event.preventDefault();

        var answer = confirm(Meguiars.GetDictionaryItem("Are You Sure You Want To Delete Vehicle Message"));

        if (answer) {
            var showcaseId = $(this).parents(".deleteBtn").find(":input").val();
            var containerBlock = $(this).parents(".block");

            var data = { showcaseId: showcaseId, languageCode: Meguiars.LanguageCode };

            $.ajax({
                url: "/services/showcase.svc/DeleteShowcase",
                data: JSON.stringify(data),
                success: function (result) {
                    var resp = result.d;
                    if (resp.Success) {
                        containerBlock.fadeOut();

                        var message = JSON.parse(resp.Message);

                        $("#totalImages").html(message.TotalImages);
                        $("#totalComments").html(message.TotalReviews);
                        $("#totalVotes").html(message.TotalVotes);
                    }
                    else {
                        Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                    }
                }
            });
        }
    });
}

Meguiars.InitializeShowcasePage = function () {
    Meguiars.WireUpVoteForShowcase();

    $("#reportImage").click(function (event) {
        event.preventDefault();
        $(this).hide();
        $("#reportImageOptionsHolder").show();
        $("#reportImageOptions").selectmenu();
    });

    $("#reportImageOptions").change(function () {
        $("#reportImageOptionsHolder").hide();

        var reportTypeId = $(this).val();
        var showcaseImageId = Meguiars.GetCurrentShowcaseImageIdFromSlider();

        var data = { showcaseImageId: showcaseImageId, reportTypeId: reportTypeId, languageCode: Meguiars.LanguageCode };
        $.ajax({
            url: "/services/showcase.svc/ReportShowcaseImage",
            data: JSON.stringify(data),
            success: function (result) {
                var resp = result.d;
                if (resp.Success) {
                    Meguiars.ShowMessage(resp.Message);
                    $("#reportImage").show();
                    $("#reportImageOptions").val("");
                }
                else {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                }
            }
        });
    });

    Meguiars.InitializeReviewBlock();
}

Meguiars.GetCurrentShowcaseImageIdFromSlider = function () {
    var currentImage = jQuery('#slider').data('nivo:vars').currentImage[0];
    var currentImageId = currentImage.id.replace("reportImage", "");
    return currentImageId;
}

Meguiars.InitializePasswordField = function () {
    // show fake password field & hide the real one
    $('.fakepw').show();
    $('.realpw').hide();
    // show real password field
    $('.fakepw').live('click', function () {
        $(this).hide();
        $('.realpw').show().focus();
    })
}

// TODO: Should move this in its own container class with private variables for ddls
Meguiars.InitializeShowcaseAddEditPage = function () {
    Meguiars.WireUpVehicleYear("ddlVehicleYears", "ddlVehicleMakes", "ddlVehicleModels", "ddlVehicleTrims");
    Meguiars.WireUpVehicleMake("ddlVehicleMakes", "ddlVehicleModels", "ddlVehicleTrims");
    Meguiars.WireUpVehicleModel("ddlVehicleModels", "ddlVehicleTrims");
    Meguiars.WireUpVehicleTrim("ddlVehicleTrims");
    Meguiars.WireUpUploader("ddlVehicleYears", "ddlVehicleMakes", "ddlVehicleModels", "ddlVehicleTrims", "tbDescription");
    Meguiars.ToggleShowcaseUploader();

    $("#tbDescription").keyup(function () {
        Meguiars.ToggleShowcaseUploader();
    });

    // Assumes the products variable has been populated
    if (typeof products != 'undefined') {
        $("#tbProductName").autocomplete(products, {
            matchContains: true,
            formatItem: function (data, i, total) {
                return data.Value;
            }
        });
    }

    $("#tbProductName").result(findValueCallback).next().click(function () {
        // find the last selected item and return that item for consumption by our
        // findValueCallback
        $(this).prev().search();
    });

    function findValueCallback(event, data, formatted) {
        // Set the hidden field to the selected product id
        $("#hdnSelectedProductId").val(data.Key);
    }

    $("#addProduct").click(function (event) {
        event.preventDefault();

        var ddlStoreChains = $("#ddlStoreChains");
        var selectedProductId = $("#hdnSelectedProductId").val();
        var selectedProductName = $("#tbProductName").val();
        var selectedDealerChainId = ddlStoreChains.val();

        if (Meguiars.AddProductToList(selectedDealerChainId, selectedProductId, selectedProductName, 0)) {
            $("#hdnSelectedProductId").val("");
            $("#tbProductName").val("");
            ddlStoreChains.val("");
            ddlStoreChains.selectmenu();
        }
    });

    $("#deleteImage").click(function (event) {
        event.preventDefault();
        var showcaseId = $("#showcaseId").val();
        var currentShowcaseImageId = $("#currentShowcaseImageId").val();

        var data = { showcaseId: showcaseId, showcaseImageId: currentShowcaseImageId, languageCode: Meguiars.LanguageCode };

        $.ajax({
            type: "POST",
            url: "/services/showcase.svc/DeleteShowcaseImage",
            data: JSON.stringify(data),
            success: function (result) {
                var resp = result.d;
                if (resp.Success) {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl);
                }
                else {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                }
            }
        });
    });

    $("#save").click(function (event) {
        event.preventDefault();
        Meguiars.SaveCurrentShowcaseImage(true);
    });

    $("#previouslyAddedProducts a.add").click(function (event) {
        event.preventDefault();

        var dealerChainId = $(this).parents(".previouslyAddedProduct").find(".hdnDealerChainId").val();
        var productId = $(this).parents(".previouslyAddedProduct").find(".hdnProductId").val();
        var productName = $(this).parents(".previouslyAddedProduct").find(".name").text();

        Meguiars.AddProductToList(dealerChainId, productId, productName, 0);
    });

    $("#productsAdded a.remove").click(function () {
        // Get container and kill it!
        $(this).parents(".addedProduct").fadeOut("normal", function () { $(this).remove(); });
    });
    // TODO: Cleanup above methods
}

/* redirectAfterSuccess: if true, will redirect after success. If afterSuccessMethod wired up and not redirecting after success, it will fire.
 * 
 */
Meguiars.SaveCurrentShowcaseImage = function (redirectAfterSuccess, afterSuccessMethod) {
    var showcaseId = $("#showcaseId").val();
    var currentShowcaseImageId = $("#currentShowcaseImageId").val();
    var showcaseImageCategoryId = $("#ddlShowcaseImageCategories").val();
    var makeDefault = $("#cbMakeDefault").is(":checked");
    var description = $("#tbDescription").val();
    var returnVal;

    if (showcaseImageCategoryId == "") {
        Meguiars.ShowDictionaryMessage("Must Select Category Message Single");
        return false;
    }

    // 1. Iterate through products
    // 2. Get category
    // 3. Save
    var showcaseImageProducts = new Array();
    $("#productsAdded .addedProduct").each(function () {
        var dealerChainId = $(this).find(".hdnDealerChainId").val();
        var productId = $(this).find(".hdnProductId").val();
        var showcaseImageProductId = $(this).find(".hdnShowcaseImageProductId").val();

        var showcaseImageProduct = {
            ShowcaseImageProductId: showcaseImageProductId,
            ProductId: productId,
            DealerChainId: dealerChainId,
            ShowcaseImageId: currentShowcaseImageId
        };

        showcaseImageProducts.push(showcaseImageProduct);
    });

    var saveShowcaseImageRequest = {
        ShowcaseId: showcaseId,
        Description: description,
        ShowcaseImageId: currentShowcaseImageId,
        ShowcaseImageCategoryId: showcaseImageCategoryId,
        MakeDefault: makeDefault,
        ShowcaseImageProducts: showcaseImageProducts,
        LanguageCode: Meguiars.LanguageCode
    };

    var data = { saveShowcaseImageRequest: saveShowcaseImageRequest };
    $.ajax({
        type: "POST",
        url: "/services/showcase.svc/SaveShowcaseImage",
        data: JSON.stringify(data),
        success: function (result) {
            var resp = result.d;

            if (redirectAfterSuccess === true) {
                if (resp.Success) {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl);
                }
                else {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                }
            }
            else {
                if (resp.Success) {
                    afterSuccessMethod(true);
                }
                else {
                    afterSuccessMethod(false);
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                }
            }
        }
    });
}

Meguiars.AddProductToList = function (dealerChainId, productId, productName, showcaseImageProductId) {
    if (productId === "") {
        // Make sure that product exists in our autocompleter, otherwise NO GO!
        Meguiars.ShowDictionaryMessage("Must Select Available Product Message");
        return false;
    }

    if (dealerChainId == "") {
        Meguiars.ShowDictionaryMessage("Must Select Dealer Message");
        return false;
    }

    // Make sure it isn't already in the list of added products. We're not going to do this server side to speed things up. The server side will
    // make sure to validate, but for now let's not do it.
    var alreadyExists = false;
    $("#productsAdded .hdnProductId").each(function () {
        var thisProductId = $(this).val();
        if (thisProductId == productId)
            alreadyExists = true;
    });

    if (alreadyExists) {
        Meguiars.ShowDictionaryMessage("Product Already Added Message");
        return false;
    }


    var addedProductHtml = $("<div></div>")
                                .addClass("addedProduct")
                                .append(String.Format("<input type='hidden' class='hdnDealerChainId' value='{0}'/>", dealerChainId))
                                .append(String.Format("<input type='hidden' class='hdnProductId' value='{0}'/>", productId))
                                .append(String.Format("<input type='hidden' class='hdnShowcaseImageProductId' value='{0}'/>", showcaseImageProductId))
                                .append(String.Format("<span class='name left'>{0}</span>", productName))
                                .append("<span class='action right plus'><a href='#' class='remove'>x</a></span>");

    $("#productsAdded").append(addedProductHtml);

    $("#productsAdded a.remove").click(function () {
        // Get container and kill it!
        $(this).parents(".addedProduct").fadeOut("normal", function () { $(this).remove(); });
    });

    return true;
}

Meguiars.ToggleShowcaseUploader = function () {
    // Only show uploader if description, year, make, model, and trim were selected
    var year = $("#ddlVehicleYears").val();
    var make = $("#ddlVehicleMakes").val();
    var model = $("#ddlVehicleModels").val();
    var trim = $("#ddlVehicleTrims").val();
    var uploader = $("#fileUploadContainer");

    //if (year == "" || make == "" || model == "" || trim == "")
    //remove trim 
    if (year == "" || make == "" || model == "")
        uploader.hide();
    else
        uploader.show();
}

/* everythingOk - if true, will start upload process. otherwise will clear upload queue
 * 
 */
Meguiars.ShowcaseStartUpload = function (everythingOk) {
    if (everythingOk === true)
        $("#fileUpload").uploadifyUpload();
    else
        $("#fileUpload").uploadifyClearQueue();
}

Meguiars.WireUpUploader = function (yearControlId, makeControlId, modelControlId, trimControlId, descriptionControlId) {
    // Get showcase identifier
    var showcaseId = $("#showcaseId").val();
    var data = { showcaseId: showcaseId, languageCode: Meguiars.LanguageCode, sessionKey: Meguiars.SessionKey };
    var tempImages = new Array();
    var errorFound = false;

    // Set upload control
    $("#fileUpload").uploadify({
        'uploader': '/flash/uploadify.swf',
        'wmode': 'transparent',
        'script': '/services/showcaseimageupload.ashx',
        'scriptData': data,
        'cancelImg': '/images/cancel.png',
        'buttonImg': '/images/btnUpload.png',
        'auto': false,
        'multi': true,
        'fileExt': '*.jpg;*.jpeg',
        'fileDesc': 'Images',
        'onSelectOnce': function (event, data) {
            if (showcaseId > 0) {
                Meguiars.SaveCurrentShowcaseImage(false, Meguiars.ShowcaseStartUpload);
            }
            else {
                // Go ahead so we can create it
                Meguiars.ShowcaseStartUpload(true);
            }
        },
        'onComplete': function (event, id, file, response, data) {
            var result = JSON.parse(response);
            if (!result.Success) {
                Meguiars.HandleMessage(result.Message, result.RedirectUrl);
                errorFound = true;
            }
            else {
                // Add item to queue which we will then open when all processing is down
                tempImages.push(result.TempImage);
            }
        },
        'onAllComplete': function (filesUploaded, errors, allBytesLoaded, speed) {
            if (!errorFound) {
                $.ajax({
                    type: "GET",
                    url: "/services/showcase.svc/GetShowcaseImagePopupInfo",
                    data: { languageCode: Meguiars.LanguageCode },
                    dataType: "json",
                    success: function (result) {
                        var resp = result.d;

                        var html = $("<div></div>").addClass("showcaseImagesPopup");
                        $.each(tempImages, function () {
                            var categories = $("<select class='showcaseImageCategory'></select>");

                            // Add default text and default value
                            categories.append($("<option/>").val(resp.ShowcaseImageCategoryDefaultValue).text(resp.ShowcaseImageCategoryDefaultText));

                            $.each(resp.ShowcaseImageCategories, function () {
                                categories.append($("<option/>").val(this.ShowcaseImageCategoryId).text(this.DisplayName));
                            });

                            var tempImageHtml = $("<div></div>")
                                                    .addClass("showcaseImage")
                                                    .append(String.Format("<input type='hidden' class='imageId' value='{0}'/>", this.Id))
                                                    .append(String.Format("<p><img src='{0}'/></p>", this.LargeWebPath))
                                                    .append(categories)
                                                    .append(String.Format("<p><input type='checkbox' value='0' class='makeDefault' name='defaultShowcaseImage'/> {0}</p>", resp.MakeDefaultText));
                            html.append(tempImageHtml);
                        });

                        html.append($("<div class='clear'></div>"));
                        html.append($(String.Format("<a href='#' id='finishUploadingImages'>{0}</a>", resp.FinishButtonText)));

                        // Wire up onclick
                        html.find("#finishUploadingImages").click(function (event) {
                            event.preventDefault();

                            var notAllCategoriesSet = false;

                            // Make sure categories are all set
                            html.find("select.showcaseImageCategory").each(function () {
                                var selectedValue = $(this).val();
                                if (selectedValue == null || selectedValue == "") {
                                    notAllCategoriesSet = true;
                                }
                            });

                            if (notAllCategoriesSet) {
                                Meguiars.ShowMessage(resp.MustSelectCategoryText);
                            }
                            else {
                                // Okay, let's get the images and save 'em up!
                                var tempImages = new Array();
                                html.find("div.showcaseImage").each(function () {
                                    // Get image id
                                    // Get showcase image category id
                                    // Get if it's going to be the default image
                                    var id = $(this).find(".imageId").val();
                                    var showcaseImageCategoryId = $(this).find(".showcaseImageCategory").val();
                                    var makeDefault = $(this).find(".makeDefault").is(":checked");

                                    var tempImage = { ShowcaseImageId: 0, Id: id, ShowcaseImageCategoryId: showcaseImageCategoryId, MakeDefault: makeDefault };
                                    tempImages.push(tempImage);
                                });

                                // Try saving these images
                                var saveShowcaseImagesRequest = {
                                    ShowcaseId: showcaseId,
                                    LanguageCode: Meguiars.LanguageCode,
                                    Description: $("#" + descriptionControlId).val(),
                                    VehicleYear: $("#" + yearControlId).val(),
                                    VehicleMakeId: $("#" + makeControlId).val(),
                                    VehicleModelId: $("#" + modelControlId).val(),
                                    VehicleTrimId: $("#" + trimControlId).val(),
                                    TempImages: tempImages
                                };

                                var data = { saveShowcaseImagesRequest: saveShowcaseImagesRequest };

                                $.ajax({
                                    type: "POST",
                                    url: "/services/showcase.svc/SaveShowcaseImages",
                                    data: JSON.stringify(data),
                                    success: function (result) {
                                        var imageResp = result.d;
                                        Meguiars.HandleMessage(imageResp.Message, imageResp.RedirectUrl);
                                    }
                                });
                            }
                        });

                        $(html).dialog({ modal: true, minWidth: 662, minHeight: 600, open: function (event, ui) { $(".showcaseImagesPopup select").selectmenu(); $('.styled > input').addClass('styled'); } });
                        tempImages = new Array();
                    }
                });
            }
        }
    });
}
Meguiars.WireUpVehicleYear = function (yearControlId, makeControlId, modelControlId, trimControlId) {
    // Year selected
    $("#" + yearControlId).change(function () {
        var year = $(this).val();
        var makes = $("#" + makeControlId);
        var models = $("#" + modelControlId);
        var trims = $("#" + trimControlId);

        if (year != "") {
            $.ajax({
                type: "GET",
                url: "/services/showcase.svc/GetVehicleMakes",
                data: { year: year, languageCode: Meguiars.LanguageCode },
                dataType: "json",
                success: function (result) {
                    makes.empty();
                    models.empty();
                    trims.empty();

                    var resp = result.d;

                    // Add default text and default value
                    makes.append($("<option/>").val(resp.DefaultValue).text(resp.DefaultText));

                    $.each(resp.VehicleMakes, function () {
                        makes.append($("<option/>").val(this.VehicleMakeId).text(this.Name));
                    });

                    // Refresh select menu
                    makes.selectmenu();
                    models.selectmenu();
                    trims.selectmenu();

                    Meguiars.SetSelectedVehicleName();
                    Meguiars.ToggleShowcaseUploader();
                }
            });
        }
        else {
            makes.empty();
            makes.selectmenu();
            models.empty();
            models.selectmenu();
            trims.empty();
            trims.selectmenu();

            Meguiars.SetSelectedVehicleName();
            Meguiars.ToggleShowcaseUploader();
        }
    });
}

Meguiars.WireUpVehicleMake = function (makeControlId, modelControlId, trimControlId) {
    // Make selected
    $("#" + makeControlId).change(function () {
        var makeId = $(this).val();
        var makeName = $(this).find("option:selected").text();
        var models = $("#" + modelControlId);
        var trims = $("#" + trimControlId);

        if (makeId != "") {
            $.ajax({
                type: "GET",
                url: "/services/showcase.svc/GetVehicleModels",
                data: { vehicleMakeId: makeId, languageCode: Meguiars.LanguageCode },
                dataType: "json",
                success: function (result) {
                    models.empty();
                    trims.empty();

                    var resp = result.d;

                    // Add default text and default value
                    models.append($("<option/>").val(resp.DefaultValue).text(resp.DefaultText));

                    $.each(resp.VehicleModels, function () {
                        models.append($("<option/>").val(this.VehicleModelId).text(this.Name));
                    });

                    // Refresh select menu
                    models.selectmenu();
                    trims.selectmenu();

                    Meguiars.SetSelectedVehicleName();
                    Meguiars.ToggleShowcaseUploader();
                }
            });
        }
        else {
            models.empty();
            models.selectmenu();
            trims.empty();
            trims.selectmenu();

            Meguiars.SetSelectedVehicleName();
            Meguiars.ToggleShowcaseUploader();
        }
    });
}

Meguiars.WireUpVehicleModel = function (modelControlId, trimControlId)
{
    // Model selected
    $("#" + modelControlId).change(function ()
    {
        var modelId = $(this).val();
        var modelName = $(this).find("option:selected").text();
        var trims = $("#" + trimControlId);

        if (modelId != "")
        {
            $.ajax({
                type: "GET",
                url: "/services/showcase.svc/GetVehicleTrims",
                data: { vehicleModelId: modelId, languageCode: Meguiars.LanguageCode },
                dataType: "json",
                success: function (result)
                {
                    trims.empty();

                    var index = 1;
                    var resp = result.d;

                    // Add default text and default value
                    trims.append($("<option/>").val(resp.DefaultValue).text(resp.DefaultText));

                    $.each(resp.VehicleTrims, function ()
                    {
                        var text;

                        if (this.Trim != null && this.Trim != '')
                            text = this.Trim;
                        else if (this.BodyType != null && this.BodyType != '')
                            text = this.BodyType;
                        else if (this.BodyType2 != null && this.BodyType2 != '')
                            text = this.BodyType2;
                        else
                            text = "---";

                        //set first trim item as default selected item, not the --select-- item                        
                        if (index == 1)
                        {
                            trims.append($("<option selected='selected'/>").val(this.VehicleTrimId).text(text));
                        }
                        else
                        {
                            trims.append($("<option/>").val(this.VehicleTrimId).text(text));
                        }

                        index++;
                    });

                    // Refresh select menu
                    trims.selectmenu();

                    Meguiars.SetSelectedVehicleName();
                    Meguiars.ToggleShowcaseUploader();
                }
            });
        }
        else
        {
            trims.empty();
            trims.selectmenu();

            Meguiars.SetSelectedVehicleName();
            Meguiars.ToggleShowcaseUploader();
        }
    });
}

Meguiars.WireUpVehicleTrim = function ( trimControlId) {
    // Model selected
    $("#" + trimControlId).change(function () {
        Meguiars.ToggleShowcaseUploader();
    });
}

Meguiars.SetSelectedVehicleName = function () {
    var name = "";
    var yearControl = $("#ddlVehicleYears");
    var makeControl = $("#ddlVehicleMakes");
    var modelControl = $("#ddlVehicleModels");

    if (yearControl != null && yearControl.val() != "") {
        name += yearControl.find("option:selected").text() + " ";

        if (makeControl != null && makeControl.val() != "") {
            name += makeControl.find("option:selected").text() + " ";

            if (modelControl != null && modelControl.val() != "") {
                name += modelControl.find("option:selected").text() + " ";
            }
        }
    }

    $("#spnTitle").html(name);
}

Meguiars.InitializeReviewBlock = function () {
    $(".reviewHolder a.reportContent").click(function (event) {
        event.preventDefault();

        // Get review and content type id
        var reviewId = $(this).parents(".report").find(".hdnReviewId").val();
        var contentTypeId = $(this).parents(".report").find(".hdnReviewContentTypeId").val();
        var reportContent = $(this);

        var data = { reviewId: reviewId, contentTypeId: contentTypeId, languageCode: Meguiars.LanguageCode };
        $.ajax({
            url: "/services/review.svc/ReportInappropriateContent",
            data: JSON.stringify(data),
            success: function (result) {
                var resp = result.d;
                if (resp.Success) {
                    reportContent.hide();
                    Meguiars.ShowMessage(resp.Message);
                }
                else {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                }
            }
        });
    });
}

Meguiars.WireUpVoteForShowcase = function () {
    var totalVotes = $("#aTotalVotes");
    if (totalVotes.length > 0) {
        totalVotes.click(function (event) {
            event.preventDefault();
        });
    }

    // Wire up click for vote functionality
    $("#aVote").click(function (event) {
        event.preventDefault();
        var showcaseId = $("#showcaseId").val();
        var aVote = $("#aVote");

        var data = { showcaseId: showcaseId, languageCode: Meguiars.LanguageCode };
        $.ajax({
            type: "POST",
            url: "/services/showcase.svc/Vote",
            data: JSON.stringify(data),
            success: function (result) {
                var resp = result.d;
                if (resp.Success) {
                    aVote.hide();
                    totalVotes.html(String.Format("{0} {1}", resp.Message, Meguiars.GetDictionaryItem("Thumbs Up")));
                    totalVotes.fadeIn();
                }
                else {
                    Meguiars.HandleMessage(resp.Message, resp.RedirectUrl, resp.MustBeLoggedIn);
                }
            }
        });
    });
}

/****************************/
//Sponsorship Upload Image
/****************************/
Meguiars.WireUpSponsorshipUploader = function ()
{
    // Get showcase identifier
    var showcaseId = $("#showcaseId").val();
    var data = { showcaseId: showcaseId, languageCode: Meguiars.LanguageCode, sessionKey: Meguiars.SessionKey };
    var tempImages = new Array();
    var errorFound = false;

    // Set upload control
    $("#fileUpload").uploadify(
    {
        'uploader': '/flash/uploadify.swf',
		'wmode'       : 'transparent',
        'script': '/services/SponsorshipImageUpload.ashx',
        'scriptData': data,
        'cancelImg': '/images/cancel.png',        
		'buttonImg': '/images/btnUpload.png',
        'auto': true,
        'multi': true,
        'fileExt': '*.jpg;*.jpeg',
        'fileDesc': 'Images',
        'sizeLimit': 4024000,
        'onComplete': function (event, id, file, response, data)
        {
            var result = JSON.parse(response);
            if (!result.Success)
            {
                Meguiars.HandleMessage(result.Message, result.RedirectUrl);
                errorFound = true;
            }
            else
            {
                // Add item to queue which we will then open when all processing is down
                tempImages.push(result.TempImage);
            }
        },
        'onAllComplete': function (filesUploaded, errors, allBytesLoaded, speed)
        {
            if (!errorFound)
            {
                var html = $("<div></div>").addClass("showcaseImagesPopup");
                $.each(tempImages, function ()
                {
                    var tempImageHtml = $("<div></div>")
                                                    .addClass("showcaseImage")
                                                    .append(String.Format("<input type='hidden' class='imageId' value='{0}'/>", this.Id))
                                                    //.append(String.Format("<p><img class='imageSource' src='{0}' /></p>", this.LargeWebPath))
                                                    .append(String.Format("<p><img class='imageSource' src='{0}' /><input type='checkbox' checked='checked' onclick='ImageChecked(this)' class='imageCheck' value='{1}'/></p>", this.LargeWebPath, this.LargeWebPath))                                                    
                                                    //.append(String.Format("<input type='checkbox' class='imageCheck'/>"))
                    html.append(tempImageHtml);

                    //save image file name
                    var tempText = $("#txtImageFileName").val();
                    tempText = tempText + "%%" + this.LargeWebPath;
                    $("#txtImageFileName").val(tempText);
                });

                html.append($("<div class='clear'></div>"));
                $(html).dialog({ modal: true, minWidth: 800, minHeight: 600 });
                tempImages = new Array();
            }
        }
    });
}



/***********************************/
//save recaptcha data to text box
/***********************************/
Meguiars.WireUpRecaptchaSubmit = function ()
{
    $("#btnSubmit").click(function (event)
    {        
        var challenge = $("#recaptcha_challenge_field").val();
        var response = $("#recaptcha_response_field").val();

        $("#txtRecaptchaChallenge").val(challenge);
        $("#txtRecaptchaResponse").val(response);

        return true;
    });
}


/*************************************/
//Contact Us Upload Image 
//1. only accept single image file
//2. max file size 1MB - 1,024,000
/*************************************/
Meguiars.WireUpContactUsUploader = function ()
{
    // Get showcase identifier    
    var data = { languageCode: Meguiars.LanguageCode, sessionKey: Meguiars.SessionKey };
    var tempImages = new Array();
    var errorFound = false;

    // Set upload control
    $("#fileUpload").uploadify(
    {
        'uploader': '/flash/uploadify.swf',
        'wmode': 'transparent',
        'script': '/services/ContactUsImageUpload.ashx',
        'scriptData': data,
        'cancelImg': '/images/cancel.png',
        'buttonImg': '/images/btnUpload.png',
        'auto': true,
        'multi': false,
        'fileExt': '*.jpg;*.jpeg;*.gif;',
        'fileDesc': 'Images',
        'sizeLimit': 1024000,        
        'onComplete': function (event, id, file, response, data)
        {
            var result = JSON.parse(response);
            if (!result.Success)
            {
                Meguiars.HandleMessage(result.Message, result.RedirectUrl);
                errorFound = true;
            }
            else
            {
                // Add item to queue which we will then open when all processing is down
                tempImages.push(result.TempImage);
            }
        },
        'onAllComplete': function (filesUploaded, errors, allBytesLoaded, speed)
        {
            if (!errorFound)
            {
                var html = $("<div></div>").addClass("contactUsImagesPopup");
                $.each(tempImages, function ()
                {
                    var tempImageHtml = $("<div></div>")
                                                    .addClass("showcaseImage")
                                                    .append(String.Format("<input type='hidden' class='imageId' value='{0}'/>", this.Id))
                                                    //.append(String.Format("<p><img class='imageSource' src='{0}' /></p>", this.LargeWebPath))
                                                    .append(String.Format("<p><img class='imageSource' src='{0}' /><input type='checkbox' checked='checked' onclick='ImageChecked(this)' class='imageCheck' value='{1}'/></p>", this.LargeWebPath, this.LargeWebPath))
                                                    //.append(String.Format("<input type='checkbox' class='imageCheck'/>"))
                    html.append(tempImageHtml);

                    //save image file name
                    var tempText = $("#txtImageFileName").val();
                    tempText = tempText + "%%" + this.LargeWebPath;
                    $("#txtImageFileName").val(tempText);
                });

                html.append($("<div class='clear'></div>"));
                $(html).dialog({ modal: true, minWidth: 800, minHeight: 600 });
                tempImages = new Array();
            }
        }
    });
}

/***********************************/
//select images
/***********************************/
function ImageChecked(chkbox)
{   
    if (chkbox.checked)
    {
        var addImage = $(chkbox).val();
        var orgImage = $("#txtImageFileName").val();
        var newImage = orgImage + "%%" + addImage;

        $("#txtImageFileName").val(newImage);        
    }
    else
    {
        var delImage = $(chkbox).val();
        var orgImage = $("#txtImageFileName").val();
        var remImage = orgImage.replace(delImage, "");

        $("#txtImageFileName").val(remImage);        
    }
}

/***********************************/
//show calendar control
/***********************************/
function ShowCalendar()
{    
    $("#cldEventDate").show();
    return true;
}



/***********************************************/
//Cookie Settings
//setCookie, getCookie, checkCookie
//copied from W3C
//http://www.w3schools.com/js/js_cookies.asp
/***********************************************/

/***********************************/
//setCookie
/***********************************/
function setCookie(c_name, value, exdays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

/***********************************/
//getCookie
/***********************************/
function getCookie(c_name)
{
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++)
    {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name)
        {
            return unescape(y);
        }
    }
}


//cookie name
var ProductsSelectedFilters = "ProductsSelectedFilters";

/****************************************/
//Set Products Selected Items By Cookies
/****************************************/
function SetProductsSelectedItemsByCookies()
{    
    var checkedArray;
    var checkedList = getCookie(ProductsSelectedFilters);    
    var checkBoxList = $('.tagGroup input[type=checkbox]');    

    //make sure selected items in cookies
    if (typeof checkedList == "undefined" || checkedList == '')
        return;

    //if checkbox are dynamic generate by ProductSection.master.cs 
    //which get from database and it may change, therefore when
    //both length not match then don't do anything
    //--------------------------------------
    //checkedArray.length have to minus one because it contain last ','
    //which don't have any value
    checkedArray = checkedList.split(',');
    if ((checkedArray.length - 1) != checkBoxList.length)
        return;

    for (var n = 0; n < checkBoxList.length; n++)
    {
        if (checkedArray[n] == "1")
        {
            $(checkBoxList[n]).attr('checked', true);
            FilterProductsSelection($(checkBoxList[n]));
        }
        else
        {
            $(checkBoxList[n]).attr('checked', false);
        }
    }
}

/***********************************/
//Save Products Selected tems
/***********************************/
function SaveProductsSelectedItems()
{
    var checkedList = '';
    var checkBoxList = $('.tagGroup input[type=checkbox]');

    for (var n = 0; n < checkBoxList.length; n++)
    {
        if ($(checkBoxList[n]).is(':checked') == true)
        {            
            checkedList = checkedList + "1,";
        }
        else
        {            
            checkedList = checkedList + "0,";
        }
    }
    
    setCookie(ProductsSelectedFilters, checkedList);
}

/***********************************/
//Clear Products Selected Items
/***********************************/
function ClearProductsSelectedItems()
{    
    setCookie(ProductsSelectedFilters, '');
}


/***********************************/
//Filter Products Selection
/***********************************/
function FilterProductsSelection(me)
{    
    var selectors = '';
    var tagGroup = $('.tagGroup');

    tagGroup.each(function ()
    {        
        var checkGroup = $(this).find('input[type=checkbox]:checked');
        if (checkGroup.length != 0)
        {            
            checkGroup.each(function ()
            {                
                selectors += $.trim($(this).siblings('label').attr('data-filter'));                
            });
            selectors += ', ';
        }
    });

    if (selectors.length == 0) { selectors = '*' }

    $('#productListing').isotope({ filter: selectors });

    var totalLeft = $(".productListingItemHolder").not(".isotope-hidden").length;
    if (totalLeft == 0)
    {
        Meguiars.ShowDictionaryMessage("No Products Left After Filtering Message");
    }
}
