﻿/* --- LOGGING ---------------------------------------------------------------- */

window.log = function () {
    log.history = log.history || [];
    log.history.push(arguments);
    window.console && console.log[console.firebug ? 'apply' : 'call'](console, Array.prototype.slice.call(arguments));
};

window.logargs = function (context) {
    log(context, arguments.callee.caller.arguments);
};

jQuery.fn.doOnce = function (func) {
    this.length && func.apply(this);
    return this;
}


/* --- BASE ---------------------------------------------------------------- */

var Radiometer = {
    Context: {},

    init: function () {
        Radiometer.navigation();
        Radiometer.pageHeight();
        Radiometer.initTabsWidth();
//        Radiometer.rmGallery.init();
        Radiometer.cufonInit();
        Radiometer.tabs();
        Radiometer.siteSelector();
        Radiometer.inputDefaultText();
        Radiometer.quickpoll();

        if ($('body').hasClass('frontpage')) {
            var docWidth = $(document).width();
            var pageWidth = $('.frontpage #content > .row').width();
            var pagePadding = Math.floor((docWidth - pageWidth) / 2) - 15;
            if (pagePadding < 0) pagePadding = 0;
            if (pagePadding > 300) pagePadding = 300;
            //alert('pagePadding ' + pagePadding);
            $('.frontpage #content > .row').css('padding', '0px ' + pagePadding + 'px');
            
//            $('#btn-vertic-portals').click(function() {
//              var d = new Date();
//              document.cookie = "Radiometer=false;expires=" + d.toGMTString() + ";" + ";";
//            });
        }

        //$('select').selectbox();

        if ($.tablesorter) {
            // add new sorting for "bytes"
            $.tablesorter.addParser({
                id: 'filesize',
                is: function (s) {
                    return s.match(new RegExp(/[0-9]+(\.[0-9]+)?\ (KB|B|GB|MB|TB)/));
                },
                format: function (s) {
                    var suf = s.match(new RegExp(/(KB|B|GB|MB|TB)$/))[1];
                    var num = parseFloat(s.match(new RegExp(/^[0-9]+(\.[0-9]+)?/))[0]);

                    switch (suf) {
                        case 'B':
                            return num;
                        case 'KB':
                            return num * 1024;
                        case 'MB':
                            return num * 1024 * 1024;
                        case 'GB':
                            return num * 1024 * 1024 * 1024;
                        case 'TB':
                            return num * 1024 * 1024 * 1024 * 1024;
                    }
                },
                // set type, either numeric or text 
                type: 'numeric'
            });

            $(".tablesort").tablesorter({
                sortList: [[0, 0]]
            });
        }

        $(window).resize(function () {
            Radiometer.pageHeight();
            //window.setTimeout(Radiometer.pageHeight, 75);
        });


        $('.spot-video a.spot-video-player').click(function (e) {
            var windowheight = 468;
            window.videoelm = $('' + $(this).attr('href'));
            window.videoelm.dialog({
                height: windowheight,
                width: 750,
                open: Radiometer.ecardVideoShow,
                close: Radiometer.videoStop,
                cancel: Radiometer.videoStop,
                modal: true
            });
            return false;
        });

        $('.posOpener').click(function (e) {
            e.preventDefault();
            $('#lightboxes').append('<div id="poscontent"><div id="posflashholder" /></div>');
            $("#poscontent").dialog({
                width: 990,
                height: 810,
                modal: true,
                close: function (ev, ui) { $(this).remove(); }
            });

            var flashvars = {};
            flashvars.config = "/handlers/RadiometerComCloneset/PosXmlHandler.ashx?lang=" + Radiometer.Context.Lang;
            var params = {
                quality: "high",
                bgcolor: "#FFFFFF",
                menu: "false",
                allowscriptaccess: "always",
                allowFullScreen: "false"
            };
            var attributes = { id: "posflash" };
            swfobject.embedSWF("/swf/pos.swf", "posflashholder", "956", "760", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
        });

        $('.firstAutoOpener').click(function (e) {
            e.preventDefault();
            $('#lightboxes').append('<div id="firstautocontent"><div id="firstautoflashholder" /></div>');
            $("#firstautocontent").dialog({
                width: 986,
                height: 894,
                modal: true,
                close: function (ev, ui) { $(this).remove(); }

            });

            var flashvars = {};
            flashvars.config = "/handlers/RadiometerComCloneset/FirstAutomaticXmlHandler.ashx?lang=" + Radiometer.Context.Lang;
            var params = {
                quality: "high",
                bgcolor: "#FFFFFF",
                menu: "false",
                allowscriptaccess: "always",
                allowFullScreen: "false"
            };
            var attributes = { id: "posflash" };
            swfobject.embedSWF("/swf/firstAutomaticApp.swf", "firstautoflashholder", "956", "844", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
        });

        var abl90VideoFlashvars = {};
        abl90VideoFlashvars.autoplay = "false";
        abl90VideoFlashvars.videoPath = "/swf/ABL90/video/1stAutomaticLocalization.flv";
        abl90VideoFlashvars.config = "/handlers/RadiometerComCloneset/ABL90.ashx?lang=" + Radiometer.Context.Lang;
        var abl90VideoFlashParams = { quality: "high", bgcolor: "#EEEEEE", menu: "false", allowscriptaccess: "always", allowFullScreen: "true" };
        var abl90VideoFlashAttributes = { id: "divABL90VideoFlash" };
        swfobject.embedSWF("/swf/ABL90/player.swf", "divABL90VideoFlash", "478", "269", "10.0.0", "expressInstall.swf", abl90VideoFlashvars, abl90VideoFlashParams, abl90VideoFlashAttributes);

        var radianceVideoFlashvars = {};
        radianceVideoFlashvars.config = "/handlers/RadiometerComCloneset/RadianceSystem.ashx?lang=" + Radiometer.Context.Lang;
        var radianceVideoFlashParams = { quality: "high", bgcolor: "#FFFFFF", menu: "false", allowscriptaccess: "always", allowFullScreen: "true" };
        var radianceVideoFlashAttributes = { id: "divRadianceVideoFlash" };
        swfobject.embedSWF("/swf/Radiance.swf", "divRadianceVideoFlash", "478", "330", "10.0.0", "expressInstall.swf", radianceVideoFlashvars, radianceVideoFlashParams, radianceVideoFlashAttributes);

        // 360 degree viewer using FSI Viewer
        $('a[href*=".fsi-viewer.com/fsicache"]').click(function (e) {
            e.preventDefault();
            var alternatemodeonly = false;


            $('#lightboxes').append('<div id="360content"></div>');
            var imageurl = $(this).attr('href');
            var w = $(window).width() - 100;
            var h = $(window).height() - 80;
            var t = document.title;
            t = (t.split('-').length > 0) ? t.split('-')[0] : t;

            if (!(swfobject.hasFlashPlayerVersion("9.0.18")) || alternatemodeonly) {
                // non flash content
                var serverurl = 'http://zoomcache-cdn-eu03.fsi-viewer.com/fsicache/h2fsi2?';
                var imageraw = getParameterByName('images3durl', imageurl);
                var listcmd = 'type=list&tpl=image_list3d&source=' + imageraw;
                $.ajax(serverurl + listcmd, {
                    success: function (data, textStatus, jqXHR) {
                        var xml = data;
                        var imgArray = [];
                        var img = '';
                        var images = $(xml).find('images3D image').each(function (i) {
                            //http://zoomcache-cdn-eu03.fsi-viewer.com/fsicache/h2fsi2?type=image&source=%2FSH%5FRadiometer%2FRadiometer%2FABL90%2FABL%5F90009%2Ejpg&width=80&height=54&rect=0,0,1,1&profile=fsi
                            img = $('<img id="radiometer3d" src="' + serverurl + '?type=image&source=' + $(this).attr('path') + '&width=' + (w - 100) + '&height=' + (h - 100) + '&rect=0,0,1,1" />');
                            imgArray[imgArray.length] = serverurl + '?type=image&width=' + (w - 100) + '&height=' + (h - 100) + '&rect=0,0,1,1&source=' + $(this).attr('path');
                        });
                        var settings = {
                            'images': imgArray,
                            cw: true,
                            hint: "Drag to rotate",
                            opening: 3
                        }
                        var xhtml = img.wrap('<div class="ipad3dcontainer" />');
                        $('#360content').html(xhtml).dialog({
                            width: w,
                            height: h,
                            title: t,
                            modal: true,
                            close: function (ev, ui) { $(this).remove(); }
                        });
                        window.setTimeout(function () { $('#radiometer3d').reel(settings); }, 500);
                    }
                });
            } else {
                // flash content (FSI)
                var xhtml = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,65,0" width="100%" height="95%">';
                xhtml += '<param name="movie" value="' + imageurl + '">';
                xhtml += '<param name="allowscriptaccess" value="always" />';
                xhtml += '<param name="allowfullscreen" value="true" />';
                xhtml += '<param name="quality" value="high" />';
                xhtml += '<embed src="' + imageurl + '" width="100%" height="95%" allowscriptaccess="always" allowfullscreen="true" quality="high" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer">';
                xhtml += '</embed>';
                xhtml += '</object>';

                $('#360content').html(xhtml).dialog({
                    width: w,
                    height: h,
                    title: t,
                    modal: true,
                    close: function (ev, ui) { $(this).remove(); }
                });
            }
            return false;
        });



        $('.scButtons').css('zoom', 1.0);
    },
    videoStop: function () {
        // remove former flash movie. This makes IE restart the movie, including sound
        $('.ui-dialog-content div#video1, .ui-dialog-content div#video2, .ui-dialog-content div#video3').html('');
        if (window.videoelm && window.videoelm.pause) {
            window.videoelm.stop();
        }
    },
    siteSelector: function () {
        $('.selected-site').click(function (e) {
            e.preventDefault();
            $(this).parent().toggleClass('toggled');
        });
    },
    initTabsWidth: function () {
        var pagewidth = $('div.tabcontainer').width();
        var $ullist = $('ul.focus-area-tabs,ul.product-tabs');
        var listitems = $ullist.children('li').size();
        var reserved = 0;
        var newpadding = 0;

        $ullist.children('li').each(function () {
            reserved += $(this).width();
        });

        var newpadding = Math.floor((pagewidth - reserved) / (listitems * 2));
        $ullist.children('li').children('a').css('paddingLeft', newpadding + 'px').css('paddingRight', newpadding + 'px').last().css('paddingRight', newpadding + 'px');

        //$('div.tabcontainer').css('backgroundImage', $('div.tabcontainer ul').children('li.last').css('backgroundImage'));
        //$('div.tabcontainer').css('backgroundPosition', $('div.tabcontainer ul').children('li.last').css('backgroundPosition'));
    },


    navigation: function () {
        $('#primary-nav').doOnce(function () {
            $(this)
      .find(' > li').each(function () { $(this).css('width', $(this).width()); }).end() /* Fixing menu hover in IE */
      .find('ul').parent().addClass('branch').hover(function () {
          $(this).addClass('hover');
      }, function () {
          $(this).removeClass('hover');
      }).end().find('a').hover(function () {
          $(this).parent().addClass('hover');
      }, function () {
          $(this).parent().removeClass('hover');
      });
        });
    },

    pageHeight: function () {
        if ($('#content, #container').length == 2 && !($('body').hasClass('frontpage'))) {
            var container = $('#container').outerHeight();
            var totalheight = $('body').innerHeight();
            var paddingbottom = Number($('#content').css('paddingBottom').replace('px', ''));
            var padding = container - paddingbottom;
            var endpadding = totalheight - padding;
            if (endpadding < 185 && container < 800) endpadding = 185;
            if (endpadding > 0) {
                if ($('#search-results').length) { endpadding = 290; }
                $('#content').css('paddingBottom', (endpadding) + 'px');
            }
        }
    },

    inputDefaultText: function () {
        $(".defaultText").focus(function (srcc) {
            if ($(this).val() == $(this).attr('title')) {
                $(this).removeClass("defaultTextActive");
                $(this).val("");
            }
        });

        $(".defaultText").blur(function () {
            if ($(this).val() == "") {
                $(this).addClass("defaultTextActive");
                $(this).val($(this).attr('title'));
            }
        });
        $(".defaultText").blur();
    },

    tabs: function () {
        $('div#tabs').doOnce(function () {
            $(this).tabs();
        });
    },

    /*
    * Animate Site Core Quick Poll votes
    */
    quickpoll: function () {
        $('.scPollOptionItemResult').each(function () {
            var $this = $(this);
            var _width = $this.find('.scPollVisualisation img').css('width');
            $this.find('img').width('0px').animate({ 'width': _width }, 2000);
        });
    },


    cufonInit: function () {
        var lang_code = $('html').attr('lang').toLowerCase()
        if (lang_code == "ja-jp" || lang_code=="zh-cn" || lang_code=="ru-ru" || lang_code=="cs-cz")
            return;
        var testimonial = ['', 'neutral', 'orange', 'purple', 'lightblue', 'purpleblue', 'red', 'green', 'blue'];
        var testimonialstr = '';
        for (var m = 0; m < testimonial.length; m++) {
            testimonialstr += ', .' + testimonial[m] + 'testimonial h3, .' + testimonial[m] + 'testimonial.loud .inner, .' + testimonial[m] + 'box h3';
            testimonialstr += ', .' + testimonial[m] + 'banner h3, .greybox' + testimonial[m] + ' h3';
        }

        var normalcufon = 'h1, .frontpage-slide-image, .block h3, .cufon-me, div.overlay-content h2, .cufon-my-h2 h2, .office-list h2, .teaser, .overlay-content p, .spot h3, .news-and-events h3, .in-your-department-sub li a, .rm-gallery li .text h2, .rm-gallery li .text p';
        var frontcufon = '.focus-block h3, .frontpage .rm-gallery .images .inner p';
        var newsroomcufon = '.top-news-story h2, .product-situations h2, .greybox h3, .testimonial h3, .colorbox h3';
        normalcufon += ', ' + testimonialstr;
        normalcufon += ', ' + frontcufon;
        normalcufon += ', ' + newsroomcufon;
        Cufon.replace('.scButtons a', { color: '#fff', hover: true });
        Cufon.replace(normalcufon);
    }
};

$(document).ready(Radiometer.init);

//closes the dialog window if the user clicks outside of the window.
$(".ui-widget-overlay").live("click", function () {
    $(":ui-dialog").each(function () {
        var $this = $(this);
        if ($this.dialog("isOpen")) {
            Radiometer.videoStop();
            $this.dialog("destroy");
        }
    });
});

// Remember: IE8 will NOT accept id's that is non-standard. E.g. must start with letters and can not contain { }.
function embedRmVideo(movieId, filePath, imagePath, width, height) {
    width = width || 478;
    height = height || 269;
    var movieVars = {}
    movieVars.autoPlay = "false";
    movieVars.videoPath = filePath;
    movieVars.imagePath = imagePath + "?mw=" + width + "&mh=" + height;
    var movieParms = { quality: "high", bgcolor: "#EEEEEE", menu: "false", allowscriptaccess: "always", allowFullScreen: "true" };
    var movieAttribs = { id: movieId };
    swfobject.embedSWF("/player/universal/player.swf", movieId, width, height, "10.0.0", "/flash/expressInstall.swf", movieVars, movieParms, movieAttribs);
}


//Infinite scroll on search result
function lastPostFunc() {
    $('div#lastPostsLoader').html('<img src="/images/rm.com/loading.gif" alt="loading">');
    var start;
    var liItem = $("#search-results li");
    var q = querySt('q');
    if (liItem[0]) {
        start = Number($("#search-results li:last").attr("data-id")) + Number(1);
    }else{
        start = Number(1);
    };
    $.post("/handlers/RadiometerComCloneset/SearchResult.ashx?q=" + q + "&start=" + start,
    function (data) {
        if (data.TotalResults != "0") {
            $("#search-results li:last").after(data.Content);
            var elementqq = $(".lastItem");
            if (elementqq[0]) {
                $("#showMoreResults").hide();
            }
        }
        $('div#lastPostsLoader').empty();
    });
};


//Get a param from the URL
function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

// query string parameter by name
function getParameterByName(name, str) {
    if (!str)
        str = window.location.href;
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(str);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

