﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

// perform redirect from Default.aspx to home
function checkRedirect() {
    var match = new RegExp(/Default.aspx$/i);
    var location = window.location.href
    if (match.exec(location) != null)
        window.location = location.substring(0, location.length - 12);
}
checkRedirect();

function loadCufon() {
    Cufon.replace(".Milo", { hover: true });
}
loadCufon();

// string functions
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

// init code
var loadedImages = []; // this must be outside any function to remain in scope all the time

// preloads an image
function preloadImage(image) {
    var cacheImage = document.createElement('img');
    cacheImage.src = image;
    loadedImages.push(cacheImage);
}

// preloads images for all states
function preloadImageStates(image) {
    var normalImage = image.replace("_Hover", "_Normal");
    var hoverImage = image.replace("_Normal", "_Hover");
    if (normalImage != hoverImage) {
        preloadImage(normalImage);
        preloadImage(hoverImage);
    }
    else
        preloadImage(image);
}

/*// preloads images for all sizes
function preloadImageSizes(image) {
    // Some images may be saved in different folders. Eg the backgrounds /Shared/Backgrounds/_Narrow etc
    // Check Constants.cs for reference.
    var wideImage = image.replace("_Narrow", "_Widescreen");
    var narrowImage = image.replace("_Widescreen", "_Narrow");
    if (wideImage != narrowImage) {
        preloadImageStates(wideImage);
        preloadImageStates(narrowImage);
    }
    else
        preloadImageStates(image);
}*/

// setup resize handler
var resizeFunction = function () {
    var width = $(window).width();
    var body = $("body");
    // 'dead' region of 30 pixels prevents flickering
    var makeLarge = 1242; // if larger than this, enlarge
    var makeSmall = 1212; // if smaller than this, shrink
    if (width > makeLarge && !body.hasClass("Widescreen"))
        body.attr("class", "Widescreen");
    else if (width < makeSmall && !body.hasClass("Narrow"))
        body.attr("class", "Narrow");
    else
        return; // prevents cufon from loading when not resizing
    loadCufon();
};
resizeFunction();
$(window).resize(resizeFunction);

$(function () {
    // Setup cufon
    Cufon.now();

    // setup handlers for text fields, init fields
    $(".jToggleInput")
        .each(function () {
            if ($(this).val() == $(this).attr("title"))
                $(this).addClass("Blur");
            else if ($(this).val() == "") {
                $(this).addClass("Blur");
                $(this).val($(this).attr("title"));
            }
            else
                $(this).removeClass("Blur");
        })
        .focus(function () {
            if ($(this).val() == $(this).attr("title")) {
                $(this).val("");
                $(this).removeClass("Blur");
            }
        })
        .blur(function () {
            if ($(this).val() == "") {
                $(this).val($(this).attr("title"));
                $(this).addClass("Blur");
            }
        });

    // hack external links,
    // we cannot have target="_blank" in xhtml strict, so ensure all external links here open in a new window
    $('a[rel=external]').click(function () {
        window.open(this.href);
        return false;
    });


/*
    // preload images
    $(".jPreloadableImage, .jPreloadableImage img, .jRollover, .jRollover img").each(function () {
        // check source of image
        var imageSrc = $(this).attr("src");
        if (imageSrc != null)
            preloadImageSizes(imageSrc);

        // check background image
        var background = $(this).css("background-image");
        if (background != null && background != "none") {
            backgroundImageSrc = background.replace(/"/g, "").replace(/url\(|\)$/ig, "");
            preloadImageSizes(backgroundImageSrc);
        }
    });

    // setup rollovers
    $("input.jRollover, img.jRollover, .jRollover img").hover(function () {
        // change rollover based on current src, not src that existed at load
        var src = $(this).attr("src");
        var hoverSrc = src.replace("_Normal", "_Hover");
        $(this).attr("src", hoverSrc);
    },
    function () {
        var src = $(this).attr("src");
        var normalSrc = src.replace("_Hover", "_Normal");
        $(this).attr("src", normalSrc);
    });*/

    // Animate menu rollovers
    $("#Navigation li.TopLevel").hoverIntent({
        over: function () {
            $(".SubMenu", $(this)).show();
        },
        out: function () {
            $(".SubMenu", $(this)).hide("fast");
        },
        timeout: 400
    });

    createEmailDialog();

    // share with a friend
    $(".jShareButton").click(function (e) {

        e.preventDefault();
        openEmailDialog();
        // show the "share this" window
        //        var dlg = $(".jShareWindow").dialog({
        //            width: 450,
        //            position: ['center', 150],
        //            height: 420,
        //            modal: true,
        //            title: "Share with a friend",
        //            close: emptyShareText,
        //            buttons: { "Send": function () {

        //                var share = {};
        //                $(".jShareWindow input[type='text']").each(function () {
        //                    share[$(this).attr("id")] = $(this).val();
        //                });

        //                share["Message"] = $(".jShareWindow textarea").val();
        //                share["PageUrl"] = window.location.href;

        //                var DTO = { 'share': share };
        //                $(".jShareWindow .loader").removeClass("hide");

        //                $.ajax({
        //                    type: "POST",
        //                    contentType: "application/json; charset=utf-8",
        //                    url: "/Services/ShareService.asmx/ShareWithAFriend",
        //                    data: JSON.stringify(DTO),
        //                    dataType: "json",
        //                    success: function (msg) {
        //                        //Padding is applied at this point, if it is applied before it will make the
        //                        //loading image display too low.
        //                        $("#shareresponse").html($.trim(msg.d)).css("padding-top", "20px");
        //                        $(".jShareWindow .loader").addClass("hide");
        //                    }

        //                });
        //            }
        //            }
        //        });
        //dlg.parent().appendTo(jQuery("form:first"));

    });

    var openRegionDialog = function () {

        var dlg = $(".jChooseRegion").dialog({
            height: 565,
            width: 770,
            position: ['center', 100],
            modal: true,
            title: "Select your region"
        });
        dlg.parent().appendTo(jQuery("form:first"));
    }

    // region selector
    $(".jChangeRegion, .jChangeRegion a").click(function (e) {
        e.preventDefault();
        if ($(".jChangeRegion a").children(".Change").length > 0)
            openRegionDialog();
    });
    //determine whether region selector should have cursor
    $(function () {
        if ($(".jChangeRegion a").children(".Change").length > 0) {
            $("#Page #Navigation #RegionSelector").css("cursor", "pointer");
            $("#Page #Navigation #RegionSelector a").css("cursor", "pointer");
        }
        else {
            $("#Page #Navigation #RegionSelector").css("cursor", "default");
            $("#Page #Navigation #RegionSelector a").css("cursor", "default");
        }
    });

    // TVC video popups
    $("a[href$=.flv]").click(function (e) {
        e.preventDefault();
        var videoPath = $(this).attr("href");
        // get title
        var image = $("img", this);
        var title = image.attr("longdesc");
        if (title == null || title.length == 0)
            title = image.attr("alt");
        // show ui box
        var dlg = $(".jShowVideo").dialog({
            height: 464,
            width: 740,
            position: ['center', 100],
            modal: true,
            title: title,
            open: function () {
                $("#VideoContainer").flashembed({
                    src: "/Content/Flash/VideoPlayer.swf",
                    expressInstall: "/Content/Flash/expressinstall.swf",
                    wmode: "opaque"
                },
                {
                    flvPath: videoPath,
                    skinPath: "/Content/Flash/VideoPlayerAssets.swf"
                });
            },
            beforeclose: function () {
                $("#VideoContainer").html("");
            }
        });
    });




});

function openEmailDialog() {
    $(".jShareWindow").dialog('open');
}

function createEmailDialog() {

    var dlg = $(".jShareWindow").dialog({
        autoOpen: false,
        width: 450,
        position: ['center', 150],
        height: 420,
        modal: true,
        title: "Share with a friend",
        close: emptyShareText,
        buttons: { "Send": function () {

            var share = {};
            $(".jShareWindow input[type='text']").each(function () {
                share[$(this).attr("id")] = $(this).val();
            });

            share["Message"] = $(".jShareWindow textarea").val();
            share["PageUrl"] = window.location.href;

            var DTO = { 'share': share };
            $(".jShareWindow .loader").removeClass("hide");

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Services/ShareService.asmx/ShareWithAFriend",
                data: JSON.stringify(DTO),
                dataType: "json",
                success: function (msg) {
                    //Padding is applied at this point, if it is applied before it will make the
                    //loading image display too low.
                    $("#shareresponse").html($.trim(msg.d)).css("padding-top", "20px");
                    $(".jShareWindow .loader").addClass("hide");
                    $('#sendAnother').show();

                }

            });
        }
        }
    });


    $('#sendAnother').click(function (e) {
        e.preventDefault();
        $('#FriendName').val("");
        $('#FriendEmail').val("");
        $("#shareresponse").empty("");
        $('#sendAnother').hide();
    });

    $('#sendAnother').hide();

    //return dlg;
}

function emptyShareText() {

    //Empty textboxes and response if lightbox closes.
    $(".jShareWindow input[type='text']").val("");
    $(".jShareWindow textarea").val("");
    $("#shareresponse").empty("");
    
}

function addZieraInputKink(obj) {
    obj.wrap("<div class='zierakink'>");
}

// Requests that the user enters their password / email address and notify if signed up to the newsletter
function showUpdateLoginLightbox() {
    // wrap in document.ready block to fix IE7 crash
    $(function () {
        // show lightbox if triggered by code
        var window = $(".jReturningUsers").dialog({
            width: 500,
            position: ['center', 100],
            modal: true,
            open: function (event, ui) {
                //hide close button.
                $(this).parent().children().children('.ui-dialog-titlebar-close').hide();
            },
            title: "Welcome to Ziera, a new era of Kumfs"
        });
        window.parent().appendTo(jQuery("form:first"));
       });

 }
