﻿function flashLoaded(e) {
    // e.ref is a reference to the Flash object. We'll pass it to jwplayer() so the API knows where the player is.

    //After player is clicked display fancybox popup
    jwplayer(e.ref).onIdle(function () { $("#popupPlayer").click(); });

    // Add event listeners - stop player from playing when clicked
    jwplayer(e.ref).onPlay( function (e) { jwplayer(e.ref).stop(); } );

}

function doSearch() {
    var searchTerms = $("#searchterms").val();
    var url = "http://" + window.location.host + "/general/searchresults?searchterms=" + searchTerms + "&page=1";
    window.location.href = url;
}

$(document).ready(function () {


    if ($("#popupLink").length > 0) {

        var formTitle = $("#popupLink").attr("formtitle");
        if (formTitle != "undefined") {
            $("#popUpTitle").html(formTitle)
        }
    }        
    
    // remove bottom dotted line style
    if ($(".productNavContainer").length) {
        var num = $(".productNavContainer").children().size();

        if (num % 2 == 0) {
            var obj1 = $(".productNavContainer").children().eq(num - 1);
            var obj2 = $(".productNavContainer").children().eq(num - 2);
            obj1.find(".lrnMore").removeClass("dottedbottom");
            obj2.find(".lrnMore").removeClass("dottedbottom");
        }
        else {
            var obj = $(".productNavContainer").children().eq(num - 1);
            var tr = obj.find(".lrnMore").removeClass("dottedbottom");
        }
    }

    if ($("input[name='campaigntoken']").length) {
        var url = window.location.href
        var index = url.lastIndexOf("/")
        var tkn = url.substr(index + 1)
        $("input[name='campaigntoken']").val(tkn);
    }

    $("a#popupPlayer").fancybox({
        'hideOnContentClick': true
    });

    $("#searchbtn").click(function (e) {
        e.preventDefault();
        doSearch();
    });

    $("#search").submit(function (e) {
        e.preventDefault();
        doSearch();
    });

    $("#searchbtn").mouseover(function () {
        $(this).css("cursor", "pointer");
    });

    $("#popupPlayer").click(function () {

        $.fancybox(
        {
            'padding': 0,
            'showCloseButton': true,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': this.title,
            'width': 360,
            'height': 280,
            'href': this.href,
            'type': 'swf',
            'overlayColor': '#000',
            'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
        });

        return false;

    });


    $("div.dropdown").hide();


    //*********************************************************
    // ******** Begin PopUp Form Handler ***************************

    $("#popUp .close").live("click", function () {
        HidePopUp();
    });

    $("#popupLink").live("click", function () {

        //get current product name from hidden field
        //var currProd = $("#currentProduct").val();
        var pageTitle = $("#pagetitle").text();
        var d = new Date()

        $.ajax({
            type: "GET",
            url: 'PopUpFormHandler.ajax?t=' + d.getTime(),
            data: {
                template: $(this).attr("formtemplate")
            },
            success: function (data) {
                var ra = data.split("||");
                var formTitle;
                if (ra[0] == "OK") {
                    if (ra.length == 2) {
                        var formTitle = $("#popupLink").attr("formtitle");
                        $("#popUp").html(ra[1]);
                        ShowPopUp();
                        // set product in hidden form field
                        $("input[name='product']").val(pageTitle);
                        $("input[name='shorttitle']").val(formTitle);
                        $("#popUpTitle").html(formTitle)
                    }
                    else
                        $("#popUp").html('');
                }
            }
        });
    });


    $("#videoWidget").live("click", function () {

        var d = new Date()

        $.ajax({
            type: "GET",
            url: 'PopUpVideoHandler.ajax?t=' + d.getTime(),
            data: {
                template: $(this).attr("formtemplate")
            },
            success: function (data) {
                var ra = data.split("||");
                if (ra[0] == "OK") {
                    if (ra.length == 2) {
                        $("#popUp").html(ra[1]);

                        ShowPopUp();

                        flowplayer("player", "/flash/player/flowplayer-3.2.0.swf", {

                            plugins: {
                                controls: {
                                    url: '/flash/player/flowplayer.controls-3.2.0.swf'
                                }
                            },
                            playlist: [
                             {},
                              {
                                  url: '/assets/videos/test.flv',
                                  autoPlay: true,
                                  autoBuffering: true
                              }
                                ]
                        });

                    }
                    else
                        $("#popUp").html('');
                }
            }
        });
    });


    function ShowPopUp() {

        //get content width        
        var w = parseInt($("#popUp").width(), 10) + parseInt($("#popUp").css("padding-left"), 10) + parseInt($("#popUp").css("padding-right"), 10);
        //alert(w / 2 + "px");

        var h = parseInt($("#popUp").height(), 10) + parseInt($("#popUp").css("padding-top"), 10) + parseInt($("#popUp").css("padding-bottom"), 10);
        //alert(h / 2 + "px");

        $("#popUp").css("margin-top", (0 - (h / 2)) + "px");
        $("#popUp").css("margin-left", (0 - (w / 2)) + "px");
        $("#popUpMask").show();
        $("#popUp").show();
    }

    function HidePopUp() {
        $("#popUp").hide();
        $("#popUpMask").hide();
        $("#popUp .content").html("");
    }

    // ******** End PopUp Form Handler ***************************

    $("#topNavigation li a").live("click", function () {
        $(this).parents("li").addClass("selected");
    });

    // select top level item for side nav menu
    $(".menuwrapper li a.selected").closest(".tl").addClass("selected");


    var dropIt;
    var closeIt;
    $("#navigation li").hover(function () {
        clearTimeout(closeIt);
        var thisThing = $(this);
        var showDropdown = function () { thisThing.children("div.dropdown").slideDown(200); };
        dropIt = setTimeout(showDropdown, 80);
        $(this).siblings("li").children("div.dropdown").slideUp();
    }, function () {
        clearTimeout(dropIt);
        var thisThing = $(this);
        var hideDropdown = function () { thisThing.children("div.dropdown").slideUp(); };
        closeIt = setTimeout(hideDropdown, 500);
    });

    //AJAX Forms
    $("form.formwrapper").live("submit", function (e) {

        e.preventDefault();

        var f = $(this);
        var serializedForm = $(f).serialize();
        var action = $(f).attr("action");
        if (serializedForm.length > 0 && action.length > 0) { serializedForm += "&sendto=" + action; }
        $.post("formsprocessor.aspx", serializedForm, function (data) {
            var ra = data.split("||");
            if (ra[0] == "OK") {
                switch (ra[2].toUpperCase()) {
                    case "SUCCESSREDIRECT":
                        if (ra[1].toLowerCase() == "refresh") {
                            window.location.href = window.location.href;
                        } else {
                            window.location.href = ra[1];
                        }
                        break;

                    case "SUCCESSFORM":
                        //set $(f).id to the new forms entity                        
                        $(f).html(ra[1]);
                        break;

                    default:
                        if (ra.length = 5) {
                            if (ra[5] = "ContactUsFrm") {

                                if ($("#contactusFrm").length > 0)
                                    $("#mainContent p").hide();
                            }
                            if (ra[5] = "campaignForm") {
                                $("#campaignContent p, #campaignContent img").hide();
                            }

                        }

                        $(f).html(ra[1]);
                        break;
                }
            } else if (ra[0] == "HASERRORS") {
                $(f).html(ra[1]);
                if ($("input[name='formentity']").val() == 'ProductContactForm') {
                    var formTitle = $("#popupLink").attr("formtitle");
                    $("#popUpTitle").html(formTitle)
                }

            } else {
                //uhoh :( internal errors or something??
            }
        });
    });


    //BUGTracker
    $("#reportBug").live("click", function () {
        serializedForm = "location=" + urlencode(window.location.href);
        var action = "BugReporter.aspx?action=show";
        $.post(action, serializedForm, showBugForm);
    });

    $("form#bugReporter .submit").live("click", function () {
        var serializedForm = $("#bugReporter").serialize();
        var action = "BugReporter.aspx?action=submit";
        $.post(action, serializedForm, showBugForm);
        $("form#bugReporter, #bugMask").remove();
    });

    $("form#bugReporter #levelID option").live("click", function () {
        $("form#bugReporter #levelID").attr("style", $(this).attr("style"));
    });

    $("form#bugReporter .bugClose").live("click", function () {
        $("form#bugReporter, #bugMask").remove();
    });

    // hide header row if not needed
    if ($("#resourcesTable thead a").eq(0).text().length == 0) {
        $(".listHeader").css("display", "none")
    }

    // redisplays resource listing filtered by industry
    $("#resourcesTable thead ax").live("click", function (e) {

        var selectedIndustry = $(this).attr("currIndustry")

        $("#filterContainer a").removeClass("selected");

        var className = $(this).attr("class");

        switch (className) {
            case "page":
            case "next":
            case "prev":
                pg = true;
                break;
            default:
                $(this).addClass('selected');
        }

        var d = new Date()
        $.ajax({
            type: "GET",
            url: 'GetResourceListRows.ajax?t=' + d.getTime(),
            cache: false,
            data: {
                resourceType: $(this).attr("resourceType"),
                contentType: $(this).attr("ContentType"),
                industryPage: $(this).attr("industryPage"),
                currIndustry: $(this).attr("currIndustry"),
                page: $(this).attr("page"),
                lang: $(this).attr("lang")
            },
            success: function (data) {
                var ra = data.split("||");
                if (ra[0] == "OK") {

                    $(".pagination").html("");

                    if (ra.length == 3) {
                        $("#resourcesTable tbody").html(ra[1]);
                        $(".pagination").html(ra[2]);
                    }
                    else if (ra.length == 2) {
                        $("#resourcesTable tbody").html(ra[1]);
                    }
                    else
                        $("#resourcesTable tbody").html('');

                    $("tr:odd").addClass("trAlternate");


                    if (pg) {
                        var s = parseInt(selectedIndustry, 10);
                        switch (s) {

                            case 4:
                                $("#filterContainer a").eq(2).addClass("selected");
                                break;
                            case 8:
                                $("#filterContainer a").eq(4).addClass("selected");
                                break;
                            case 0:
                            case 1:
                                $("#filterContainer a").eq(s).addClass("selected");
                                break;
                            case 2:
                                $("#filterContainer a").eq(3).addClass("selected");
                                break;
                        }
                    }

                }
            }
        });
    });


    // Navigate to selected product
    $("#productList").change(function () {
        // get selected item        
        var path = $(this).val();
        window.location = path.toLowerCase();
    })


    $("#productSupportList").live("change keyup", function () {

        var d = new Date()
        $.ajax({
            type: "GET",
            url: 'GetProductSupportMaterials.ajax?t=' + d.getTime(),
            cache: false,
            data: {
                productId: $(this).val()
            },
            success: function (data) {
                var ra = data.split("||");
                if (ra[0] == "OK") {
                    if (ra.length == 2)
                        $("#supportInfo").html(ra[1]);
                    else
                        $("#supportInfo").html('');
                }
            }
        });
    });


    $("#productTypeList").live("change keyup", function () {

        var d = new Date()
        $.ajax({
            type: "GET",
            url: 'GetFAQs.ajax?t=' + d.getTime(),
            cache: false,
            data: {
                productType: $(this).val(),
                lang: $("#countryCodes").val()
            },
            success: function (data) {
                var ra = data.split("||");
                if (ra[0] == "OK") {
                    if (ra.length == 2)
                        $("#faqs").html(ra[1]);
                }
            }
        });
    });


    $("#locationsList").live("change keyup", function () {

        var d = new Date()
        $.ajax({
            type: "GET",
            url: 'GetOfficeRecord.ajax?t=' + d.getTime(),
            cache: false,
            data: {
                officeId: $(this).val()
            },
            success: function (data) {
                var ra = data.split("||");
                if (ra[0] == "OK") {
                    if (ra.length == 2)
                        $("#OfficeInfo").html(ra[1]);
                    else
                        $("#OfficeInfo").html('');
                }
            }
        });
    });

    if ($("#languageadmin").length > 0) {
        $("#countryCodes").change(function () {
            //submit form and process language selection
            $('#languageadmin').submit();
        })
    }
    else {

        $("#countryCodes").change(function () {
            //submit form and process language selection
            $('#language').submit();
        })
    }

    /* Focus and Exit Form Fields  */
    $("input").focus(function () {
        var ex = $(this).attr("example");
        if (ex == $(this).val()) {
            $(this).val("");
        }
    });
    $("input").blur(function () {
        if ($(this).val() == "") {
            $(this).val($(this).attr("example"));
        }
    });

});


//Bug Reporting
function showBugForm(r) {
    $("form#bugReporter, #bugMask").remove();
    $("body").append(r);

    $("form#bugReporter #levelID option").css({ "color": "white","width":"100%"});
    $("form#bugReporter #levelID option:eq(0)").css({"color": "black", "background-color": "white"});
    $("form#bugReporter #levelID option:eq(1)").css("background-color", "red");
    $("form#bugReporter #levelID option:eq(2)").css("background-color", "orange");
    $("form#bugReporter #levelID option:eq(3)").css("background-color", "gold");
    $("form#bugReporter #levelID option:eq(4)").css("background-color", "blue");
    $("form#bugReporter #levelID option:eq(5)").css("background-color", "green");
    $("form#bugReporter #levelID").attr("style", $("form#bugReporter #levelID option:selected").attr("style"));
}


function init() {
    //see if we have and option boxes to restyle
    try {
        oHandler = $(".searchselect").msDropDown().data("dd");
        oHandler.visible(true);
        $("#ver").html($.msDropDown.version);
    } catch (err) { };

}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
