/*===========================================================================
	Behavior (Global)
	
	This JavaScript executes dynamic behaviors such as:
	* Preloading images
	* Flash Replacements (i.e. sIFR, UFO, SWFObject, etc.)
	* Decorate the DOM with presentational elements
	* Collapsing/expanding sections
	* Form validation
	* Popup windows
===========================================================================*/

/* Enable FireBug/etc. logging if logging widget is loaded
===========================================================================*/

jQuery.extend(jQuery.browser,
{ SafariMobile: navigator.userAgent.toLowerCase().match(/iP(hone|ad)/i) }
);

if (window.YAHOO && YAHOO.widget.Logger) {
	YAHOO.widget.Logger.enableBrowserConsole();
}

// IE 6 Detection
if ($.browser.msie && $.browser.versionNumber < 7) {
	DD_roundies.addRule("span.icon");
	DD_roundies.addRule("#search-form");
	DD_roundies.addRule("#change-language");
	DD_roundies.addRule("#language-box-arrow");
}

$().geekGaTrackPage("UA-9585526-1");

Modernizr._fontfaceready(function(bool){
  if (!bool) {
    Cufon.replace("h1");
    Cufon.replace("h2", {hover: true, seperate: "character"});
    Cufon.replace("h3", {hover: true});
    Cufon.replace("body.utility-section form label span.label-title");
    Cufon.replace("ul#breadcrumb li:not(.first-child)", {hover: true});
    Cufon.replace("a.gs-title", {hover: true});
  }
});

$(document).ready(function () {
    // Add rounded corners for IE.
    if (!$.support.borderRadius) {
        DD_roundies.addRule("div#logo-container", "10px");
        DD_roundies.addRule("#primary-navigation-container", "10px");
        DD_roundies.addRule("#utility-navigation-container", "10px");
        DD_roundies.addRule("div#content-header h1", "10px");
        DD_roundies.addRule("ul#secondary-content li", "10px");
        DD_roundies.addRule("#language-options", "10px");
        DD_roundies.addRule("#content-header", "10px 10px 0 0");
    }

    $("ul.product-images li:not(.video) a").live("click", function (e) {
        e.preventDefault();
        $(".product-image").show();
        $("#product-video-container").hide();
        $(this).addClass("current");
        $("ul.product-images li a.current").removeClass("current");
        $("div.product-image img").attr("src", $(this).attr("href"));
    });

    $("a[rel='external']").click(function (e) {
        // Adapted from: http://www.456bereastreet.com/archive/200610/opening_new_windows_with_javascript_version_12/
        var oWin = window.open(this.getAttribute("href"), "_blank");
        if (oWin) {
            if (oWin.focus) oWin.focus();
            return false;
        }

        oWin = null;
        return true;
    });

    $("#welcome-text").cycle();

    $("div#item-number-help").scrollFollow({ offset: 30 }).jqm({ trigger: '.item-number-help', closeClass: 'close-modal', onShow: function (hash) {
        hash.w.css('visibility', 'visible');
    }, onHide: function (hash) {
        hash.w.css('visibility', 'hidden');
        hash.o.remove();
    }
    });

    $("ul#faq a.title").toggle(function (e) {
        e.preventDefault();
        $(this).addClass("active").parents("li").children("div.body").show();
    }, function (e) {
        e.preventDefault();
        $(this).removeClass("active").parents("li").children("div.body").hide();
    });

    $("ul#faq div.body a.close").live("click", function (e) {
        e.preventDefault();
        $(this).parents("li").children("h2").children("a.title").removeClass("active");
        $(this).parents("div.body").hide();
    });

    $('input#search').each(function () {
        if ($(this).val() === '') {
            $(this).val($(this).attr('title'));
        }

        $(this).focus(function () {
            if ($(this).val() === $(this).attr('title')) {
                $(this).val('').addClass('focused');
            }
        });

        $(this).blur(function () {
            if ($(this).val() === '') {
                $(this).val($(this).attr('title')).removeClass('focused');
            }
        });
    });

    $("#change-language").toggle(function (e) {
        e.preventDefault();
        $("#language-options").show();
    }, function (e) {
        e.preventDefault();
        $("#language-options").hide();
    });

    $('#language-options').click(function (e) {
        e.stopPropagation();
    });

    $(document).click(function () {
        $('#language-options').hide();
    });

    $("#language-options-navigation :not(#switch-region) a").click(function (e) {
        var date = new Date();
        date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
        e.preventDefault();
        $.cookie("language_id", null, { path: '/', domain: '.kidkraft.com', expires: date });
        $.cookie("language_code", null, { path: '/', domain: '.kidkraft.com', expires: date });
        var language = $(this).attr("href").replace("#", "").split("-");
        var language_id = language[0];
        var language_code = language[1];
        $.cookie("language_id", language_id, { path: '/', domain: '.kidkraft.com', expires: date });
        $.cookie("language_code", language_code, { path: '/', domain: '.kidkraft.com', expires: date });
        location.reload(true);
    });

    $(".product-images .video a").click(function (e) {
        e.preventDefault();
        $(".product-image").hide();
        $("#product-video-container").show();

        $(this).addClass("current");
        $("ul.product-images li a.current").removeClass("current");

        if ($.browser.SafariMobile) {
            var mediaURL = $(this).attr("href");
            CreateVideoJSPlayer($("#product-video"), mediaURL);
        }
        else {
            var flashvars = {
                flvpWidth: 442,
                flvpHeight: 305,
                flvpVideoSource: $(this).attr("href"),
                flvpFolderLocation: "/_vendor/flvplayer"
            };

            var params = {
                menu: "true",
                allowfullscreen: "true",
                stretching: "uniform"
            };

            var so = swfobject.embedSWF("/_vendor/flvplayer/FLVplayer.swf", "product-video", "442", "305", "9.0.0", "/_vendor/swfobject/expressInstall.swf", flashvars, params);
            //so.addVariable('stretching', 'uniform');
            //so.addVariable('backcolor', 'EEEEEE');
        }
    });

});

//jQuery.fn.replace = function () {
//    return this.domManip(arguments, true, 1, function (a) {
//        this.parentNode.replaceChild(a, this);
//    });
//};


function CreateVideoJSPlayer(id, mediaURL) {
    var r, el = id;

    var width = 442;
    var height = 304;
    var posterURL = "/_media/logos/KK-STANDARD-LOGO-441x304.jpg";

    $(".video-js-box").remove();

    var videoBox = document.createElement("div");
    videoBox.setAttribute("class", "video-js-box");
    videoBox.setAttribute("style", "text-align: center;");

    var video = document.createElement("video");
    video.setAttribute("class", "video-js");
    video.setAttribute("width", width);
    video.setAttribute("height", height);
    video.setAttribute("controls", "");
    video.setAttribute("preload", "");
    video.setAttribute("autoplay", "");
    video.setAttribute("poster", posterURL);
    $(videoBox).append(video);

    var source = document.createElement("source");
    source.setAttribute("src", mediaURL);
    source.setAttribute("type", "video/mp4; codecs='avc1.42E01E, mp4a.40.2'");
    $(video).append(source);

    var flash = document.createElement("object");
    flash.setAttribute("class", "vjs-flash-fallback");
    flash.setAttribute("width", width);
    flash.setAttribute("height", height);
    flash.setAttribute("type", "application/x-shockwave-flash");
    flash.setAttribute("data", "http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf");
    $(video).append(flash);

    var param1 = document.createElement("param");
    param1.setAttribute("name", "movie");
    param1.setAttribute("value", "http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf");
    $(flash).append(param1);

    var param2 = document.createElement("param");
    param2.setAttribute("name", "allowfullscreen");
    param2.setAttribute("value", "true");
    $(flash).append(param2);

    var param3 = document.createElement("param");
    param3.setAttribute("name", "flashvars");
    param3.setAttribute("value", 'config={"playlist":["h' + posterURL + '", {"url": "' + mediaURL + '","autoPlay":false,"autoBuffering":true}]}');
    $(flash).append(param3);

    //<!-- Image Fallback. Typically the same as the poster image. -->
    var img1 = document.createElement("img");
    img1.setAttribute("src", posterURL);
    img1.setAttribute("width", width);
    img1.setAttribute("height", height);
    img1.setAttribute("alt", "Poster Image");
    img1.setAttribute("title", "No video playback capabilities.");
    $(flash).append(img1);

    var noVideo = document.createElement("p");
    noVideo.setAttribute("class", "vjs-no-video");
    noVideo.setAttribute("style", "display: none;");
    $(videoBox).append(noVideo);

    var noVideoTitle = document.createElement("strong");
    noVideoTitle.innerHTML = "Download Video:";
    $(noVideo).append(noVideoTitle);

    var noVideoLink = document.createElement("a");
    noVideoLink.setAttribute("href", mediaURL);
    noVideoLink.innerHTML = "MP4";
    $(noVideo).append(noVideoLink);

    // THIS OBJECT WAS USED TO DEBUG THE MEDIA URL
    //var test = document.createElement("p");
    //test.innerHTML = mediaURL;
    //$(videoBox).append(test);
    
    //$(el).replaceWith(videoBox);
    $(el).append(videoBox);
    
    r = video;
    return r;
}		

