﻿
// -----------------------------
// Image Title generator and technology tagger scripts
// -----------------------------
$(document).ready(function () {

    $("#tvboxes input[type=checkbox]").click(function () {
        var box = $(this).attr("id");
        var status = $("#" + box)[0].checked;
        if(status)
        $("#tvboxes").parent().parent().children("input[type=radio]")[0].checked = true;
    });
    $("#dvdboxes input[type=checkbox]").click(function () {
        var box = $(this).attr("id");
        var status = $("#" + box)[0].checked;
        if (status)
            $("#dvdboxes").parent().parent().children("input[type=radio]")[0].checked = true;
    });
    $("#recorderboxes input[type=checkbox]").click(function () {
        var box = $(this).attr("id");
        var status = $("#" + box)[0].checked;
        if (status)
            $("#recorderboxes").parent().parent().children("input[type=radio]")[0].checked = true;
    });

    // code to change titles to Image Text
    $(".title").each(function () {
        var text = $(this).html().replace(/^\s+|\s+$/g, '');
        $(this).html("<img src='DrawText.ashx?text=" + encodeURI(text) + "' alt='" + text + "'/>");
    });

    // code to change titles to Image Text
    $(".h1title").each(function () {
        var text = $(this).html().replace(/^\s+|\s+$/g, '');
        $(this).html("<img src='DrawText.ashx?text=" + escape(text) + "&fontSize=11' alt='" + text + "'/>");
    });

    // code to change titles to Image Text
    $(".h2title").each(function () {
        var text = $(this).html().replace(/^\s+|\s+$/g, '');
        $(this).html("<img src='DrawText.ashx?text=" + escape(text) + "&fontSize=7' alt='" + text + "'/>");
    });

    // register technology tag mouseout and mouseover events
    $(".TechTag").hover(
        function (e) {
            showTechnologyOverlay($(this), e.pageX, e.pageY);
        },
        function () {
            hideTechnologyOverlay();
        }
    );
});

// -----------------------------
// Technology tagger
// -----------------------------

function showTechnologyOverlay(sender, x, y) {
    // create and configure overlay
    $(".pageContainer").append("<div id=\"divTechTag\" class=\"TechTagPopUp\"></div>");
    $("#divTechTag").text("Please wait, loading...");
    var yCoord = y - $("#divTechTag").parent().offset().top;
    var xCoord = x - $("#divTechTag").parent().offset().left;
    $("#divTechTag").css({ "z-index": "10000", "left": xCoord + "px", "top": yCoord + "px" });

    // download data and add it to overlay
    var pageId = $(sender).attr("techTag");
    getTechnologyData(pageId);

    $("#divTechTag").show();
}

function getTechnologyData(pageId) {

    $.ajax({
        type: "POST",
        url: "/ToshibaServices/ToshibaClientService.asmx/GetTechnologyDescription",
        cache: true,
        data: 'id=' + pageId + '&langBranch=' + currentLanguage + '',
        dataType: "xml",
        success: function (data, status) {
            $("#divTechTag").html($(data).text());
            $("#divTechTag").show();
        },
        error: function (xmlRequest) {
            alert(xmlRequest.status + ' \n\r ' +
              xmlRequest.statusText + '\n\r' +
              xmlRequest.responseText);
        }
    });

}

function hideTechnologyOverlay() {
    $("#divTechTag").remove();
}

// -----------------------------
// Product list page scripts
// -----------------------------

// show quick view overlay lightbox
function showLightBox(productId) {
    $('#lightBox').html("Please wait, loading...");
    $.get("/Templates/Pages/LightBoxContent.aspx?lang=" + currentLanguage + "&product=" + productId, function (result) {
        $('#lightBox').html($(result).find("#lightBoxContent").html());
        //alert($('#lightBox').html());
        $('#lightBox')[0].innerHTML += '';
        $('#lightBox').lightbox_me({
            centered: true,
            onLoad: function () {

                $('#lightBox').append("");
                initOverlayImages();
            },
            closeClick: true
        });
    });
    
}

// quick view button init
function initQuickViewButtons() {
    var showInt = 0;
    var buttonHtml = "<img src=\"" + quickViewButton + "\" class=\"quickViewButton\" style=\"border: 0 solid black\"/>";
    $(".productMedia").each(function () {
        $(this).append(buttonHtml);
        $(this).css("position", "relative");
        var image = $(this).children("a:first").children("img:first");
        var prodId = $(image).attr("prodId");
        var qvImage = $(this).children(".quickViewButton:first");
        $(qvImage).css("left", 10);
        $(qvImage).css("top", 10);
        $(qvImage).attr("prodId", prodId);

        $(image).hover(function () {
            $(qvImage).fadeIn('fast');
        }, function () {
            showInt = setTimeout(function () { $(qvImage).hide(); }, 800);
        });

        $(qvImage).mouseover(function () {
            //$(this).stop().fadeIn();
            clearTimeout(showInt);
        });
        $(qvImage).click(function () {
            $(this).hide();
            showLightBox(prodId);
        });
    });
}

function previewImage(linkObj) {

    // get thumbnail url
    var src = $(linkObj).children(":first-child").attr("src");
    var indexOfUrl = src.indexOf("&image=");
    var imageUrl = "ShowImage.ashx?size=373&iswidth=True&image=" + src.substring(indexOfUrl + 7);
    // init preview image
    $("#imgPreview").attr("src", imageUrl);

}

function initOverlayImages() {
    $(document).ready(function () {
        $(".thumbnailButton").each(function () {
            $(this).click(function () {

                previewImage(this);

            });

        });

        previewImage($(".thumbnailButton:first"));
    });
}

function closeOverlay() {
    $(".lb_overlay").hide();
    $("#lightBox").hide();
}


//Product filter...
var filterControl = {
    allFilters: new Array(),
    selectedFilters: new Array(),
    products: new Array(),

    init: function () {

        // initialise variables
        this.allFilters = new Array();
        this.selectedFilters = new Array();
        this.products = new Array();
        var self = this;

        // init handlers
        $(".filter").click(function () {
            if ($(this).attr("disabled") != "disabled")
                self.selectUnselectFilter($(this));
        });

        // add product ids to the products array
        $(".productListItem").each(function () {
            var productId = $(this).attr("productId");
            self.products.push(productId);
        });

        // add all filter ids to the allFilters array
        $(".filter").each(function () {
            var filterId = $(this).attr("filterId");
            self.allFilters.push(filterId);
        });

        // init selected filters if it is stored in a cookie
        var filters = $.cookie('productSelector_' + pageID);
        if (filters != null && filters != "") {
            var selected = filters.split(',');

            for (var i in selected) {
                var filterElement = $(".filter[filterId=" + selected[i] + "]");
                this.selectUnselectFilter($(filterElement));
            }
        }
        else {
            this.enableDisableFilters();
        }
    },

    selectUnselectFilter: function (selected) {
        if ($(selected).parent().attr("class") == "selected") {
            //$(selected).parent().css("background-color", "white");
            $(selected).parent().attr("class", "");

        } else {
            //$(selected).parent().css("background-color", "green");
            $(selected).parent().addClass("selected");
        }

        this.enableDisableFilters();
    },

    enableDisableFilters: function () {

        var self = this;
        this.pushSelectedFilters();
        var selectedProducts = this.getFilteredProductIDs();
        $(".filter").each(function () {
            var filterId = $(this).attr("filterId");

            if ($.inArray(filterId, self.selectedFilters) == -1) {
                if (self.isFilterValid(filterId)) {
                    $(this).attr("disabled", "");
                    $(this).css("color", "Black");
                    $(this).parent().attr("class", "")
                } else {
                    $(this).attr("disabled", "disabled");
                    $(this).css("color", "Gray");
                    $(this).parent().addClass("disabled");
                }
            }
        });


        if (selectedProducts.length > 0) {
            $(".productListItem").hide();
            $(".productListItem").attr("filteredOut", "true");
            for (var i in selectedProducts) {
                $(".productListItem[productid=" + selectedProducts[i] + "]").show();
                $(".productListItem[productid=" + selectedProducts[i] + "]").attr("filteredOut", "false");
            }
        }
        else {
            $(".productListItem").show();
            $(".productListItem").attr("filteredOut", "false");
        }

        paginationController.init(true);
    },

    pushSelectedFilters: function () {
        var self = this;
        this.selectedFilters = new Array();
        $(".filter").each(function () {
            if ($(this).parent().attr("class") == "selected") {
                var filterId = $(this).attr("filterId");
                self.selectedFilters.push(filterId);
            }
        });

        // store the selected filters in a cookie
        $.cookie('productSelector_' + pageID, self.convertArrayToCSV(self.selectedFilters), { expires: 7, path: '/' });
    },

    isFilterValid: function (filterId) {
        var selectedProducts = this.getFilteredProductIDs();
        var newProducts = this.getProductsFromFilter(filterId);
        var intersect = this.intersection(selectedProducts, newProducts);
        //console.info("Filter Id: " + filterId + " selectedProducts: " + selectedProducts.length + " newProducts: " + newProducts.length + " intersect: " + intersect.length);

        if (selectedProducts.length > 0) {
            if (intersect.length > 0 && intersect.length < selectedProducts.length) {
                return true;
            }
            else
                return false;
        }
        else {
            if (newProducts.length > 0)
                if (intersect.length != this.products.length)
                    return true;
                else
                    return false;
            else {
                return false;
            }
        }
    },

    // returns with an array of product IDs filtered by selected filters
    getFilteredProductIDs: function () {
        var productArray = new Array();

        // get first filtered products
        for (var i in this.selectedFilters) {

            var assignedProducts = this.getProductsFromFilter(this.selectedFilters[i]);

            if (i == 0) {
                for (var j in assignedProducts) {
                    productArray.push(assignedProducts[j]);
                }
            } else {
                productArray = this.intersection(productArray, assignedProducts);
            }
        }

        return productArray;
    },

    // returns with an array of products associated with the passed filter
    getProductsFromFilter: function (filterId) {
        var filter = $("[filterId=" + filterId + "]");
        var productList = $(filter).attr("products");
        if (productList != undefined)
            return productList.split(",");
        else
            return new Array();
    },

    intersection: function (x, y) {
        x.sort(); y.sort();
        var i = j = 0; ret = [];
        while (i < x.length && j < y.length) {
            if (x[i] < y[j]) i++;
            else if (y[j] < x[i]) j++;
            else {
                ret.push(x[i]);
                i++, j++;
            }
        }
        return ret;
    },

    convertArrayToCSV: function (arrayList) {
        var convertedCSV = "";

        for (var i in arrayList) {
            convertedCSV += arrayList[i] + (i + 1 < arrayList.length ? "," : "");
        }

        return convertedCSV;
    }
}


//EOF Ptroduct filter

// pagination controller
var paginationController = {
    currentPage: 0,
    maxItemsPerPage: 20,
    pageLinkSelector: ".pageLink",
    pageLinkActiveClass: "active",
    listItemSelector: "section .productListItem",
    listItems: null,
    itemCount: 0,
    maxPages: 0,
    prevLink: null,
    nextLink: null,

    init: function (reinit) {
        // init variables
        this.currentPage = 0;
        this.listItems = $("section .productListItem[filteredOut=false]");
        this.itemCount = $(this.listItems).length;
        this.maxPages = Math.ceil(this.itemCount / this.maxItemsPerPage)

        // init buttons
        this.prevLink = $(".prevLink");
        this.nextLink = $(".nextLink");

        // update product counter
        $(".spanNumOfProds").html(this.itemCount);

        // register pager events
        if (!reinit) {
            this.prevLink.click(function () {
                self.prevPage();
            });

            this.nextLink.click(function () {
                self.nextPage();
            });
        }

        // hide items we don't need to display and show the ones on the current page
        this.changePage(0);
        var self = this;

        if (this.maxPages > 1) {

            $(".resultsIndex").show();

            // create page indexes
            var pageIndexLinkHtml = "<a href=\"javascript:void(0)\" title=\"{0}\" class=\"pageLink\">{0}</a>";

            if (reinit) {
                $(".pageLink").remove();
            }

            for (var i = 1; i <= this.maxPages; i++) {
                $(this.nextLink).before(pageIndexLinkHtml.format([i]));
            }

            // make first index active
            $(".pageLink:contains('1')").addClass("active");

            // register page index events
            $(".pageLink").click(function () {
                var pageIndex = $(this).html();
                self.changePage(pageIndex - 1);
            });
        }
        else {
            $(".resultsIndex").hide();
        }
    },

    changePage: function (pageIndex) {

        // check if pageIndex vaild, fix if not
        if (pageIndex > this.maxPages)
            pageIndex = this.maxPages;

        // set currentPage
        this.currentPage = pageIndex;

        // hide all items
        this.listItems.hide();

        // display the ones on the current page
        this.listItems.slice(this.currentPage * this.maxItemsPerPage,
                                 this.currentPage * this.maxItemsPerPage + this.maxItemsPerPage).show();

        if (this.maxPages > 1) {
            // hide/show prev and next buttons
            if (this.currentPage == 0)
                $(this.prevLink).hide();
            else
                $(this.prevLink).show();

            if (this.currentPage == this.maxPages - 1)
                $(this.nextLink).hide();
            else
                $(this.nextLink).show();

            // change page index selection
            $(".pageLink").removeClass("active");
            $(".pageLink:contains('" + (this.currentPage + 1) + "')").addClass("active");
        }
    },

    nextPage: function () {

        if (this.currentPage == this.maxPages)
            return false;

        this.currentPage += 1;
        this.changePage(this.currentPage);
    },

    prevPage: function () {

        if (this.currentPage == 0)
            return false;

        this.currentPage -= 1;
        this.changePage(this.currentPage);
    }
}

// -----------------------------
// FAQ page scripts
// -----------------------------

var faqTabControl = {
    products: new Array(),
    modelNumberText: "",
    selectedTab: null,
    selectTab: function (sender) {
        var selectedTab = $(sender).attr("tabIndex");

        // hide all tabs and show only the active one
        $(".faqTab").hide();
        $(".faqTab:eq(" + selectedTab + ")").show();

        $(".faqTab:eq(" + selectedTab + ")").children(".showHideItem").show();

        // make selected tablink active
        $(".faqTabLink").removeClass("active");
        $(sender).addClass("active");

        // change address
        $.address.value("tab-" + selectedTab);

        this.buildProductFilter($(".faqTab:eq(" + selectedTab + ")"));
        this.selectedTab = selectedTab;
    },
    init: function () {

        // init click event handlers
        var self = this;
        $(".faqTabLink").click(function () {
            self.selectTab($(this));
        });

        // get first tab
        var selectedTab = null;
        if ($.address.value() == "/")
            selectedTab = $(".faqTabLink:first");
        else {
            selectedTab = $(".faqTabLink:eq(" + $.address.value().replace("/tab-", "") + ")");

        }
        // select the first tab
        this.selectTab(selectedTab);

        // handle product filter selection
        $('#partNumbers').change(function () {
            var partNumber = $(this).val();

            if (partNumber == "-") {
                $(".faqTab:eq(" + self.selectedTab + ")").children(".showHideItem").show();
            } else {
                $(".faqTab:eq(" + self.selectedTab + ")").children(".showHideItem").hide();
                $(".faqTab:eq(" + self.selectedTab + ")").children(".showHideItem[partNumbers^=" + partNumber + "]").show();
            }
        });

        // handle show all items click
        $('#showAll').click(function () {

            $(".faqTab:eq(" + self.selectedTab + ")").children(".showHideItem").show();
        });
    },
    buildProductFilter: function (sender) {
        var self = this;
        self.products = new Array();

        $('#partNumbers').html("");
        $('#partNumbers').
                append($("<option></option>").
                attr("value", "-").
                text(self.modelNumberText));

        $(sender).find(".showHideItem").each(function () {

            var partNumbers = $(this).attr("partNumbers");
            var prods = partNumbers.split(",");
            var text = this;
            $.each(prods, function () {
                if ($.inArray(this, self.products) == -1 && this != "") {
                    self.products.push(this);
                }
            });

        });

        $.each(self.products, function () {
            var itemText = this;
            var fake = "3DGLA4PK";
            var element = $("<option></option>");
            $('#partNumbers').append($(element));
            $(element).val(itemText);
            $(element).text(itemText.replace(/^\s+|\s+$/g, ''));

        });
    }
}

// -----------------------------
// Glossary page scripts
// -----------------------------
var glossaryControl = {

    selectedLetter: "0",

    init: function () {

        var self = this;

        // init letter and number list
        $("#navLetters a").click(function () {
            self.selectLetter($(this));

            // change address parameter
            var addressParameter = "letter-" + self.selectedLetter;
            $.address.value(addressParameter);
        });
        $("#navNumbers a").click(function () {
            self.selectLetter($(this));

            // change address parameter
            var addressParameter = "number-" + self.selectedLetter;
            $.address.value(addressParameter);
        });

        // init drop down event
        $("#ddlSelector").change(function () {
            if ($(this).val() == "1") {
                $("#navLetters").show();
                $("#navNumbers").hide();
            }
            else {
                $("#navLetters").hide();
                $("#navNumbers").show();
            }
        });

        // select default letter
        if ($.address.value() == "/")
            this.selectLetter($("#navLetters a:first"));
        else {
            var requestedLetter = "";
            var requestedButton = null;
            if ($.address.value().indexOf("letter") > -1) {
                requestedLetter = $.address.value().replace("/letter-", "");
                requestedButton = $("#navLetters a:contains('" + requestedLetter + "')");
            } else {
                requestedLetter = $.address.value().replace("/number-", "");
                requestedButton = $("#navNumbers a:contains('" + requestedLetter + "')");

                // show number list
                $("#navLetters").hide();
                $("#navNumbers").show();
                $("#ddlSelector").val("1");
            }

            this.selectLetter($(requestedButton));
        }
    },

    selectLetter: function (sender) {

        // get selected letter
        this.selectedLetter = $(sender).html();

        // activate selected letter
        this.activateSelectedLetter($(sender));

        // show loading message and download technology items
        this.loadTechnologyList(this.selectedLetter);
    },

    activateSelectedLetter: function (sender) {
        var containerName = this.getLetterType() == "letter" ? "navLetters" : "navNumbers";
        $("#" + containerName + " a").removeClass("active");
        $(sender).addClass("active");
    },

    getLetterType: function () {
        if ($("#navLetters").css("display") == "none")
            return "number";
        else
            return "letter";
    },

    loadTechnologyList: function (selectedLetter) {
        var cachedLetter = $("#letter-" + selectedLetter);
//        if ($(cachedLetter).length == 0) {
            // download technology list from the server if it is not cached for the selected letter
            $(".glossarySearchResults").html("<p>Please wait, loading items...</p>");
            var self = this;
            $(".glossarySearchResults").load("/Templates/Pages/TechnologyListAjax.aspx?lang=" + currentLanguage + "&letter=" + selectedLetter + " #techList", function () {
                
                // cache letter
                //$("#cached_items").append("<div id='letter-" + selectedLetter + "'>" + $(".glossarySearchResults").html() + "</div>");

                // trick for IE
                $(".glossarySearchResults")[0].innerHTML += '';
                initBuilder();

                // update status bar
                self.updateStatusBar();
            });
//        } else {
//            // get technology list from cache
//            $(".glossarySearchResults").html($(cachedLetter).html());

//            initBuilder();

//            // update status bar
//            this.updateStatusBar();
//        }
    },

    updateStatusBar: function () {
        $("#spanSelectedLetter").html(this.selectedLetter);
        $("#spanNumOfResults").html($(".glossarySearchResults section").length);
    }
}

// -----------------------------
// show video lightbox
// -----------------------------
// load video and display popup
function LoadAndShowVideo(videoFileName) {

    InsertFlash(videoFileName);

    $('#videoLightBox').lightbox_me({
        centered: true,
        onLoad: function () {

        },
        closeClick: true
    });

}

// hide the popup and load a non existent flash movie
function HideAndUnloadVideo() {
    $(".lb_overlay").hide();
    $("#videoLightBox").hide();
    $("#videoLightBoxContent").html("");
    swfobject.removeSWF("videoObject");
}

// insert flash file using swfobject
function InsertFlash(videoFileName) {

    $("#videoLightBoxContent").html("<div id=\"videoLightBoxContentFlash\"></div>");

    var flashvars = {};
    var attributes = { id: 'videoObject', name: 'videoObject', allowscriptaccess: "always" };
    var params = { wmode: "opaque", allowscriptaccess: "always" };
    swfobject.embedSWF(videoFileName,
                           "videoLightBoxContentFlash", "640", "385", "10.0.0",
                           "/scripts/expressInstall.swf", flashvars, params, attributes);
}

// -----------------------------
// Utility scripts
// -----------------------------

// open quick clip window
function openQuickClip(page, width, height) {
    window.open(page, "quicClip", "width=" + width + ", height=" + height + ",top=0,left=0");
}

// string formatting function
String.prototype.format = function (args) {
    var str = this;
    return str.replace(String.prototype.format.regex, function (item) {
        var intVal = parseInt(item.substring(1, item.length - 1));
        var replace;
        if (intVal >= 0) {
            replace = args[intVal];
        } else if (intVal === -1) {
            replace = "{";
        } else if (intVal === -2) {
            replace = "}";
        } else {
            replace = "";
        }
        return replace;
    });
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");

function heightOfChildren(element) {
    var $heights = 0;
    $(element).children().each(function () {
        $heights = $heights + parseInt($(this).height()); // gets height of content
        $heights = $heights + parseInt($(this).css("margin-top")); // adds height of box model
        $heights = $heights + parseInt($(this).css("margin-bottom"));
        $heights = $heights + parseInt($(this).css("border-top-width"));
        $heights = $heights + parseInt($(this).css("border-bottom-width"));
        $heights = $heights + parseInt($(this).css("padding-top"));
        $heights = $heights + parseInt($(this).css("padding-bottom"));
    });
    return $heights;
}

function showHide(elementName, sender) {
    var element = $("#" + elementName);
    if ($(element).css("display") == "none")
        $(element).show();
    else
        $(element).hide();
}
