(function( $ ) {
    var SEARCHTOOLTIPHIDEDELAY = 500,
        ALERTHIDEDELAY = 2500,
        GALLERY_MENU_SLIDE_DELAY = 40,
        AWARDS_MENU_SLIDE_DELAY = 40;

    if (undefined == window.console) {
        console = {
            log : function(e) {}
        }
    }
    var checkAgeAndShow = function(node) {
        var ageForm = $("div.age-verification form");
        var allowedAge = parseInt($(node).attr('rel'));
        ageForm.find('input[name=allowed]').val(allowedAge);
        if (!allowedAge || parseInt($.getCookie('age')) >= allowedAge) {
            $("div.age-verification").hide();
            $("div.age-verification-fail").hide();
            $("#flashContent").show();
            $.cryPlayer.write("flashContent");
        } else {
            $("#flashContent").hide();
            $("div.age-verification-fail").hide();
            $("div.age-verification").show();
        }
    };
    var _checkAgeAndShowCallback = function(e){
            if ($.browser.msie) {
                // Support for IE 8
                event.returnValue = false;
            } else {
                e.preventDefault();
            };
            var ageForm = $(this);
            var allowedAge = ageForm.find('input[name=allowed]').val();
            var realAge = parseInt(ageForm.find('input[name=age]').val());
            if ( realAge >= allowedAge) {
                 $("div.age-verification").hide();
                 $("div.age-verification-fail").hide();
                 $("#flashContent").show();
                 $.cryPlayer.write("flashContent");
                 $.setCookie('age', realAge);
            } else {
                $("div.age-verification").hide();
                $("div.age-verification-fail").show();
            }
    };
    
    $.prevSibling = function(elem) {
        do {
            elem = elem.previousSibling;
        } while (elem && elem.nodeType != 1);
        return elem;
    }

    $.setCookie = function(c_name, value, expiredays) {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+
        ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
    };
    
    $.getCookie = function(c_name)
    {
        if (document.cookie.length>0)
          {
          c_start=document.cookie.indexOf(c_name + "=");
          if (c_start!=-1)
            {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
            }
          }
        return "";
    };

    $.cryPlayer = null;

    $.checkAgeAndShow = function() {
        $('div.gallery > div.close').click(function() {
           window.location.href = "/";
        });
        $('.age-verification form').unbind('submit').bind('submit', _checkAgeAndShowCallback);
        checkAgeAndShow($('#flashContent'));
    };
    

    var messageWindow = {};
    messageWindow.center = function() {
        var w = $(window).width();
	var h = $(window).height();

        var scrollTop, scrollLeft;

	// Compliance with HTML 4/XHTML
	if(document.documentElement && document.documentElement.scrollTop)
            scrollTop = document.documentElement.scrollTop;
	else
            scrollTop = document.body.scrollTop;

	// Compliance with HTML 4/XHTML
	if(document.documentElement && document.documentElement.scrollLeft)
            scrollLeft = document.documentElement.scrollLeft;
	else
            scrollLeft = document.body.scrollLeft;

        $('body div.alert').css("left", Math.ceil(w  / 2 + scrollLeft) + "px");
        $('body div.alert').css("top", Math.ceil(h / 2 + scrollTop) + "px");
    };
    messageWindow.show = function(text) {
          if ($('body div.alert').length) {
                return;
          }
          $('body').append('<div class="alert">' + text + '</div>');
          messageWindow.center();
          $('body div.alert').fadeIn('fast');
    };
    messageWindow.hide = function() {
        $('body div.alert').fadeOut('slow', function(){$('body div.alert').remove();});
    };


    var awards = function() {
        this.init();
    };
    awards.prototype = {
        slideFrame : null,
        pagination : null,
        prevBtn : null,
        nextBtn : null,
        page : 1,
        pages : 5,
        init : function() {
            this.slideFrame = $('.content-type27 div.frame');
            this.pagination = $('.content-type27 div.pagination div.page');
            this.prevBtn = $('.content-type27 div.pagination div.prev');
            this.nextBtn = $('.content-type27 div.pagination div.next');
            this.pages = $('.content-type27 input[name=awardPageNum]').val();

            this.prevBtn.live('click', this, function(e) {
                if (e.data.page > 1) {                    
                    e.data.scrollRight(function(e){
                        e.data.page --;
                        e.data.showPage();                        
                    });
                }
            });
            this.nextBtn.live('click', this, function(e) {
                if (e.data.page < e.data.pages) {                                    
                    e.data.scrollLeft(function(e){
                        e.data.page ++;
                        e.data.showPage();                            
                    });
                }
            });
        },
        showPage : function() {
            this.pagination.html(this.page * 1 + ('/' + this.pages));
        },
        scrollLeft : function(callback) {
            var node = this.slideFrame;
            var scope = this;
            var i = 1;
            (function(counter){
                setTimeout( function() {
                    node.scrollLeft(((scope.page - 1) * 980) + 98 * counter);
                    if (counter++ <= 9) {
                        setTimeout(arguments.callee, AWARDS_MENU_SLIDE_DELAY);
                    } else {
                        callback({data:scope});
                    }
                }, AWARDS_MENU_SLIDE_DELAY);
            })(i);
        },


        scrollRight : function(callback) {
            var node = this.slideFrame;
            var scope = this;
            var i = 10;
            (function(counter){
                setTimeout( function() {
                    node.scrollLeft(((scope.page - 2)* 980) + 98 * counter);
                    if (counter-- > 0) {
                        setTimeout(arguments.callee, AWARDS_MENU_SLIDE_DELAY);
                    } else {
                        callback({data:scope});
                    }
                }, AWARDS_MENU_SLIDE_DELAY);
            })(i);
        }
    }

    /**
     * Object invokes gallery, either image or video gallery depending on options
     *
     * @param (object) options
     *      options.boundingBox -  wrapper node
     */
    var gallery = function(options) {
        this.init(options);
    };
    gallery.prototype = {
        // Nodes
        boundingBox : null,
        imageFrame : null,
        image : null,
        slideFrame : null,
        shadowNode : null,
        slides : null,
        pagination: null,
        nextBtn : null,
        prevBtn : null,
        prevBigBtn: null,
        nextBigBtn: null,
        closeBtn : null,
        // Variables
        offset : 0,
        limit : 6,
        page : 1,
        pageNum: 0,
        activeSlide : 0,
        hovered: false,
        
        init : function(options) {
            this.shadowNode = $('div.gallery-shadow');
            this.boundingBox = options.boundingBox;
            if (undefined === this.boundingBox || this.boundingBox.length == 0) {
                throw 'No bounding box specified for the gallery';
            }
            this.shadowNode.show();
            this.boundingBox.show();
            this.renderUI();
            this.syncUI();
            this.showImage(this.slides[0]);
        },

        renderUI : function() {
            this.imageFrame = this.boundingBox.find("div.gallery > div.image");
            this.image = this.boundingBox.find("div.gallery > div.image > img");
            this.slideFrame = this.boundingBox.find("div.gallery > div.toolbar > div.slides");
            this.slides = this.boundingBox.find("div.gallery > div.toolbar > div > ul > li");
            this.pagination = this.boundingBox.find("div.gallery > div.toolbar > div.pagination");
            this.nextBtn = this.boundingBox.find("div.gallery > div.toolbar > div.next");
            this.prevBtn = this.boundingBox.find("div.gallery > div.toolbar > div.prev");
            this.prevBigBtn = this.boundingBox.find("div.gallery > div.image > div.prev-big");
            this.nextBigBtn = this.boundingBox.find("div.gallery > div.image > div.next-big");
            this.closeBtn = this.boundingBox.find("div.gallery > div.close");

        },
        syncUI : function() {
            this.closeBtn.live('click', this, this._onClickClose);

            this.nextBigBtn.live('mouseover', this, this._onMouseOverNext);
            this.prevBigBtn.live('mouseover', this, this._onMouseOverPrev);
            this.nextBigBtn.live('mouseout', this, this._onMouseOutImageFrame);
            this.prevBigBtn.live('mouseout', this, this._onMouseOutImageFrame);

            this.prevBigBtn.live('click', this, this._onClickBigPrevBtn);
            this.nextBigBtn.live('click', this, this._onClickBigNextBtn);

            
            this.slides.live('click'
                , this, this._onClickGalleryThumbnail);
            this.nextBtn.live('click', this, this._onClickGalleryNext);
            this.prevBtn.live('click', this, this._onClickGalleryPrev);

            $('.age-verification form').unbind('submit').bind('submit', _checkAgeAndShowCallback);

            // Init pagination
            this.pageNum = Math.ceil((this.slides.length-1) / this.limit);
            
            this.pagination.css("width", (this.pageNum * 8) + "px");
            // @TODO: causes error in IE 8
            if (!$.browser.msie) {
                this.pagination.css("padding-left", "-" + (this.pageNum * 4) + "px");
            }
            
            this.actualizatePagination();
            this.actualizateNavState();

        },

        _onClickClose: function(e) {
            e.data.shadowNode.hide();
            e.data.boundingBox.hide();
            // delete this;
        },
        _onClickBigPrevBtn: function(e) {
            if (e.data.activeSlide == (e.data.page -1) * e.data.limit &&
                e.data.activeSlide > 1
            ) {
                e.data._onClickGalleryPrev(e);
            }
            if (e.data.activeSlide > 0) {
                e.data.showImage(e.data.slides[e.data.activeSlide - 1]);
                e.data.activeSlide --;
                e.data.makeSlidesInactive();
                e.data.makeSlideActive();
            }
        },
        _onClickBigNextBtn: function(e) {
            if (e.data.activeSlide + 1 == e.data.page * e.data.limit &&
                e.data.activeSlide + 1 < e.data.slides.length
                ) {
                e.data._onClickGalleryNext(e);
            }
            if (undefined !== e.data.slides[e.data.activeSlide + 1]) {
                e.data.showImage(e.data.slides[e.data.activeSlide + 1]);
                e.data.makeSlidesInactive();
                e.data.makeSlideActive();
            }
        },

        _onMouseOutImageFrame : function(e) {
            e.data.hovered = false;
             e.data.prevBigBtn.find('div').hide();
             e.data.nextBigBtn.find('div').hide();
        },
        _onMouseOverNext : function(e) {
             e.data.hovered = true;
             if (undefined !== e.data.slides[e.data.activeSlide + 1]) {
                 e.data.nextBigBtn.find('div').show();
             } else {
                 e.data.nextBigBtn.find('div').hide();
             }
        },
        _onMouseOverPrev : function(e) {
             e.data.hovered = true;
             if (e.data.activeSlide > 0) {
                 e.data.prevBigBtn.find('div').show();
             } else {
                 e.data.prevBigBtn.find('div').hide();
             }             
        },

        actualizatePagination : function() {
            var offset = (this.page - 1) * 8;
            this.pagination.css("background-position", "-" + (82 - offset) + "px 0");
        },

        makeSlidesInactive : function() {
            this.slides.each(function(i){
                $(this).removeClass("active");
            });
        },
        actualizateActive : function() {
            this.slides.each($.proxy(function(i, el){
                if($(el).hasClass("active")){
                    this.activeSlide = i;
                }
            }, this));
        },
        makeSlideActive : function() {
            $(this.slides[this.activeSlide]).addClass("active");
        },

        scrollGalleryLeft : function(callback) {
            var node = this.slideFrame;
            var scope = this;
            var i = 1;
            (function(counter){
                setTimeout( function() {
                    node.scrollLeft(((scope.page - 1) * 846) + Math.ceil(846 / 10 * counter));
                    if (counter++ <= 9) {
                        setTimeout(arguments.callee, GALLERY_MENU_SLIDE_DELAY);
                    } else {
                        callback({data:scope});
                    }
                }, GALLERY_MENU_SLIDE_DELAY);
            })(i);
        },

        actualizateNavState : function() {
            if (this.activeSlide + this.limit >= this.slides.length) {
                this.nextBtn.find('div').css('background-image', 'url(/assets/gallery-next-btn-inactive.png)');
            } else {
                this.nextBtn.find('div').css('background-image', 'url(/assets/gallery-next-btn.png)');
            }
            if (this.activeSlide <= 0 ) {
                this.prevBtn.find('div').css('background-image', 'url(/assets/gallery-prev-btn-inactive.png)');
            } else {
                this.prevBtn.find('div').css('background-image', 'url(/assets/gallery-prev-btn.png)');
            }
        },

        scrollGalleryRight : function(callback) {
            var node = this.slideFrame;
            var scope = this;
            var i = 10;
            (function(counter){
                setTimeout( function() {
                    node.scrollLeft(((scope.page - 2)* 846) + Math.ceil(846 / 10 * counter));
                    if (counter-- > 0) {
                        setTimeout(arguments.callee, GALLERY_MENU_SLIDE_DELAY);
                    } else {
                        callback({data:scope});
                    }
                }, GALLERY_MENU_SLIDE_DELAY);
            })(i);
        },

        _onClickGalleryPrev : function(e) {
            e.preventDefault();
            if (e.data.page <= 0 ) {
                return;
            }
            e.data.scrollGalleryRight($.proxy(function(e){
                this.page --;
                this.activeSlide = (this.page * this.limit) - 1;
                this.makeSlidesInactive();
                this.makeSlideActive();
                this.actualizatePagination();
                this.actualizateNavState();
            }, e.data));
        },

        _onClickGalleryNext : function(e) {
            e.preventDefault();
            if (e.data.page >= e.data.pageNum) {
                return;
            }
            e.data.scrollGalleryLeft($.proxy(function(e){
                this.page ++;
                this.activeSlide = (this.page - 1) * this.limit;
                this.makeSlidesInactive();
                this.makeSlideActive();
                this.actualizatePagination();
                this.actualizateNavState();
            }, e.data));
        },
        showImage : function(node) {
            var oldImgSrc = this.image.attr("src");
            $(node).addClass("active");
            this.actualizateActive();
            this.actualizatePagination();

            if (this.boundingBox.attr('id') == 'video-gallery') {
                var url = '/' + $(node).find('div').attr('rel');
                $.cryPlayer.addVariable("video_url", url);
                checkAgeAndShow(node);
            } else {
                this.imageFrame.css("background-image", "url(" + oldImgSrc + ")");
                this.image.hide();
                this.image.attr("src", $(node).find("img").attr("src").replace(/thumbnails\//, ""));
                var scope = this;
                $(node).find("img").ready(function(e){
                    scope.image.attr("title", $(node).find("img").attr("title"));
                    scope.image.attr("alt", $(node).find("img").attr("title"));
                    scope.image.fadeIn('slow', function(){
                        scope.imageFrame.css("background-image", "none");
                    });
                });
                
            }
        },
        _onClickGalleryThumbnail : function(e) {
            e.preventDefault();
            e.data.makeSlidesInactive();
            e.data.showImage(this);
        }
    };

    var desktop = function() {
        this.init();
    };

    var util = {
        redirect : function(ext) {
            var addr = window.location.href;
            addr = addr.replace(/(&.*?)$/gi, '') + ext;
            window.location.href = addr;
        }
    }


    desktop.prototype = {
        // Placeholders
        searchTooltipNode : null,
        searchInput : null,
        searchTooltipTimer : null,
        dropdownTimer: null,
        cnTooltipTimer: [],
        init : function() {
            this.searchTooltipNode = $("#searchForm div.tooltip");
            this.searchInput = $('#searchForm input[name=keys]');
            this.syncUI();
            this.applyRouter();
        },
        renderUI : function() {

        },

        syncUI : function() {
            $("body .header .logo").click(function(e){
                window.location.href = "/";
            });
            $("li.clickable").live('click', this, function(e){
                e.preventDefault();
                window.location.href = $(this).find('a').attr('href');
            });

            // Emails in the content
            $("a[rel=mailto]").live('click', this, function(e){
                e.preventDefault();
                var addr = $(this).html().replace(/(<.*?>)/, "@");
                // For the Contact Form, we take subject from DT inner HTML of the previous node
                var prevNode = $.prevSibling(this.parentNode);
                if (prevNode && prevNode.nodeName == 'DT') {
                    window.location.href = "mailto:" + addr + '?subject=' + $(prevNode).html();
                } else {
                    window.location.href = "mailto:" + addr;
                }
                
            });
            
            $("div.admin-toolbar button").live('click', this, function(e){
                e.preventDefault();
                $("div.admin-toolbar").hide();
            });



            $('#searchForm').submit(this._submitSearchForm);
            $('select[name=searchIn]').change(this._changeSearchIn);

            // Gallery launch
            $('li.image-gallery-launch').click(function() {
                new gallery({
                    boundingBox : $('#image-gallery')
                });
            });
            $('li.video-gallery-launch').click(function() {
                new gallery({
                    boundingBox : $('#video-gallery')
                });
            });

            
            // Awards
            if ($(".content-type27").length) {
                new awards();
            }

            // Page teaser onClick handler (<a><div /></a> is prohibited
            // so, in use is <div><a class="hidden"><!-- --></a></div>)

            $("body div.preloader > div.clickable").click(function(e){
		 e.preventDefault();
               if ($(this).find("a.hidden").length) {
                   var href = $(this).find("a.hidden").attr("href");
                   var patt = /http:/g;
                   // Local link
                   if (!patt.test(href)) {
                       window.location.href = href;
                       return;
                   }
                   var patt = /crytek\.com/g;
                   if (patt.test(href)) {
                        window.location.href = href;
                   } else {
                       window.open (href, "blank");
                   }
               }
            });

            // Hover effect - glowing
            $("body div.cryengine-teaser").mouseover(function(e){
                $(e.currentTarget).css("background-image", "url(/assets/teaser/cryengine-active.png)");
            });
            $("body div.cryengine-teaser").mouseleave(function(e){
                $(e.currentTarget).css("background-image", "url(/assets/teaser/cryengine.png)");
            });
            $("body div.crysis2-teaser").mouseover(function(e){
                $(e.currentTarget).css("background-image", "url(/assets/teaser/crysis2-active.png)");
            });
            $("body div.crysis2-teaser").mouseleave(function(e){
                $(e.currentTarget).css("background-image", "url(/assets/teaser/crysis2.png)");
            });

            // Apply specified effect to page teaser
            $("body div.teaser-effect").mouseover(this._mouseOverPageTeaser);
            $("body div.teaser-effect").mouseleave(this._mouseOutPageTeaser);


            // Job applicant form
            var jobForm = $("ul.apply-form form");

            jobForm.find('select[name=how]').change(function(e) {
                if ($(this).val() == 'Advertisement'
                    || $(this).val() == 'Job Fair'
                    || $(this).val() == '(other)')
                {
                    jobForm.find('div.specified').show();
                } else {
                    jobForm.find('div.specified').hide();
                }
            });


            jobForm.find('div#uploadedFile > button').click(function(e) {
                    e.preventDefault();                    
                    $.post("/service/form", { deleteFile:
                        jobForm.find('input[name=attachment]').val() });
                    jobForm.find('div#uploadedFile').hide();
                    jobForm.find('input[name=uploads]').show();
            });

            jobForm.find('input[name=uploads]').live('change', function() {
                jobForm.find("#loading")
                    .ajaxStart(function(){
                        $(this).show();
                    })
                    .ajaxComplete(function(){
                        $(this).hide();
                    });

		$.ajaxFileUpload
		(
                    {
                        url: "/service/form",
                        secureuri:false,
                        fileElementId:'fileToUpload',
                        dataType: 'json',
                        success: function (data, status)
                        {
                            if (data.redirect) {
                                util.redirect('&errorCode=' + data.redirect);
                                return;
                            }
                            jobForm.find('input[name=uploads]').hide();
                            jobForm.find('input[name=uploads]').val('');
                            jobForm.find('div#uploadedFile').show();
                            jobForm.find('input[name=attachment]').val(data.filename);
                            jobForm.find('div#uploadedFile > a').html(data.displayname);

                        }
                    }
		)
            
            });

            jobForm.submit(function(e){
                if (jobForm.attr('rel') == 'valid') {
                    return;
                }
                e.preventDefault();
                $.post(
                    "/service/form",
                    jobForm.serialize(),
                    function(data) {
                        $("ul.apply-form p.error-msg").hide();
                        jobForm.find("input").each(function(){
                            $(this).removeClass('invalid');
                        });
                        jobForm.find("select").each(function(){
                            $(this).removeClass('invalid');
                        });
                        if (data.redirect.length > 0) {
                            if (data.redirect == 'success') {
                                window.location.href = '/career/apply/overview&state=success';
                                return;
                            }
                            util.redirect('&errorCode=' + data.redirect);
                            return;
                        }
                        if (data.fields.length) {
                            if (data.form.length) {
                                jobForm.find("div.specified.captcha").html(data.form);
                            }
                            $.each(data.fields, function(key, val){
                                jobForm.find("input[name=" + val + "]").addClass('invalid');
                                jobForm.find("select[name=" + val + "]").addClass('invalid');
                            });
                            $("ul.apply-form p.error-msg").html('Please fill out all requested fields');
                            $("ul.apply-form p.error-msg").show();

                        } 
                    }
                );
            });

            

            // Info overlay for admin panel
            $("div.admin-toolbar a[name=info]").click(function(e){
                e.preventDefault();
                $(this).siblings("div.overlay").show();
            });
            $("div.admin-toolbar div.overlay > a").click(function(e){
                e.preventDefault();
                $(this).parent().hide();
            });

            // Company : Partnership content block
            $("li.content-type24").delegate('.tooltiped', 'mouseover', this, function(e){
                var tooltip = $(this).find('.tooltip');
                if (tooltip.hasClass('hidden')) {
                    tooltip.removeClass('hidden');
                    tooltip.unbind("mouseover").bind("mouseover", e.data, e.data.cancelCnTooltipHide);
                    tooltip.unbind("mouseleave").bind("mouseleave", e.data, e.data.hideCnTooltip);
                } else {
                    e.currentTarget = tooltip;
                    e.data.cancelCnTooltipHide(e);
                }
            });
            $("li.content-type24").delegate('.tooltiped', 'mouseleave', this, function(e) {
                e.currentTarget = $(this).find('.tooltip');
                e.data.hideCnTooltip(e);
            });
            $("li.content-type24").delegate('.tooltip', 'click', this, function(e) {
                var link = 'http://' + $(this).text().replace(/\s/g, '').toLowerCase();
                window.open (link);
            });
            
            // Company : Awards
            $("li.content-type27").delegate('div.tooltiped', 'mouseover', this, function(e){
                var tooltip = $(this).find('.tooltip');
                if (tooltip.hasClass('hidden')) {
                    tooltip.removeClass('hidden');
                    tooltip.unbind("mouseover").bind("mouseover", e.data, e.data.cancelCnTooltipHide);
                    tooltip.unbind("mouseleave").bind("mouseleave", e.data, e.data.hideCnTooltip);
                } else {
                    e.currentTarget = tooltip;
                    e.data.cancelCnTooltipHide(e);
                }
            });
            $("li.content-type27").delegate('div.tooltiped', 'mouseleave', this, function(e) {
                e.currentTarget = $(this).find('.tooltip');
                e.data.hideCnTooltip(e);
            });


            // Company : Envision / Trust, Enable / Collaborate, Achieve / Respect content block
            $("li.content-type26 .menu1").click(function() {
                var item = $(this).parent();
                item.css('background-image', 'url(/assets/content/pic-envision-menu.jpg)');
                item.find('div.item').html( item.find('.hidden div.text-menu1').html() + '' );
            });
            $("li.content-type26 .menu2").click(function() {
                var item = $(this).parent();
                item.css('background-image', 'url(/assets/content/pic-enable-menu.jpg)');
                item.find('div.item').html( item.find('.hidden div.text-menu2').html() + '' );
            });
            $("li.content-type26 .menu3").click(function() {
                var item = $(this).parent();
                item.css('background-image', 'url(/assets/content/pic-achieve-menu.jpg)');
                item.find('div.item').html( item.find('.hidden div.text-menu3').html() + '' );
            });
            

            // Archive toggling Older
            $("body .archive-expander").toggle(
                function() {$('#archive-older').show();$(this).removeClass('down').addClass('up');},
                function() {$('#archive-older').hide();$(this).removeClass('up').addClass('down');}
            );
            // Attachments toggling blocks
            $("body .expander").toggle(
                function() {$(this).siblings('.expandable').show();$(this).removeClass('down').addClass('up');},
                function() {$(this).siblings('.expandable').hide();$(this).removeClass('up').addClass('down');}
            );

            // Social sharing
            $("body").delegate('a.share', 'click', this, function(e){
                var dropdown = $(this).parent().siblings('div.dropdown');
                if ($(this).hasClass('up')) {
                    $(this).removeClass('up').addClass('down');
                    dropdown.hide();
                } else {                    
                    $(this).removeClass('down').addClass('up');
                    dropdown.show();
                    dropdown.unbind("mouseover").bind("mouseover", e.data, e.data.cancelDropdownHide);
                    dropdown.unbind("mouseleave").bind("mouseleave", e.data, e.data.hideDropdown);
                }
            });
            // Job dropdown
            $("body").delegate('a.job-drop', 'click', this, function(e){
                e.preventDefault();
                var dropdown = $('#' + $(this).attr('rel'));
                dropdown.show();
                dropdown.unbind("mouseover").bind("mouseover", e.data, e.data.cancelDropdownHide);
                dropdown.unbind("mouseleave").bind("mouseleave", e.data, e.data.hideDropdown);
            });


            $("div.dropdown > ul > li").live('mouseover', this, this._onMouseoverDropdown);
            $("div.dropdown > ul > li").live('mouseout', this, this._onMouseoutDropdown);

            // Dropdown onlick behaivor when in breadcrumbs Office/Position switch
            $("div.breadcrumbs div.dropdown > ul > li").live('click', this, function(e){
                window.location.href = $(this).attr('rel');
            });
            // Dropdown onlick behaivor when in content News/Presentation/Job sharing
            $("div.contents div.dropdown > ul > li").live('click', this, this._onClickDropdown);


            // carousel
            var boundingBox = $('body div.preloader');
            var iterator = {
                pointer: 0,
                nodes : [ boundingBox.find('#s1 , #t1'), boundingBox.find('#s2 , #t2')
                , boundingBox.find('#s3 , #t3'), boundingBox.find('#s4 , #t4') ]
            };

            (function(delay, iterator){
                setTimeout(function(){
                    iterator.pointer ++;
                    if (iterator.pointer >= iterator.nodes.length) {
                        iterator.pointer = 0;
                    }
                    for (var i in iterator.nodes) {
                        if (i == 0) {
                            iterator.nodes[iterator.nodes.length - 1].fadeOut('slow');
                        } else
                        if (i == iterator.pointer) {
                            iterator.nodes[i].fadeIn('slow', function() {
                                for (var i in iterator.nodes) {
                                    if (i != iterator.pointer) {
                                        iterator.nodes[i].hide();
                                    }
                                }
                            });
                        } 
                    }
                    setTimeout(arguments.callee, delay);
                }, delay);
            })(3500, iterator);

        },
        _onClickDropdown : function (e) {
          if ($(e.currentTarget).parent().parent().parent().find('dfn.hidden a').length) {
            var headerNode = $(e.currentTarget).parent().parent().parent().find('dfn.hidden a');
          } else if ($(e.currentTarget).parent().parent().parent().find('h1').length) {
            var headerNode = $(e.currentTarget).parent().parent().parent().find('h1 a');
          } else {
            var headerNode = $(e.currentTarget).parent().parent().parent().find('h2 a');
          }
          var title  = encodeURIComponent(headerNode.html());
          var link  = encodeURIComponent(headerNode.attr('href'));
          if (undefined === headerNode.attr('href')) {
              link  = encodeURIComponent(headerNode.attr('rel'));
          }
          var item = $(e.currentTarget).find('div > div > div');
          var windowOptions = "status=0,toolbar=0, width=500, height=500";

          if (item.hasClass('email')) {
              window.location.href = 'mailto:?subject=' + title + '&body=Please, follow the link ' + link;
          } else if (item.hasClass('facebook')) {
              window.open ("http://www.facebook.com/sharer.php?u=" + link + "&t=" + title, "Facebook Share", windowOptions);
          } else if (item.hasClass('digg')) {
              window.open ("http://digg.com/submit?phase=2&title=" + title+ "&url=" + link);
          } else if (item.hasClass('twitter')) {
              window.open ("http://twitthat.com/go?url=" + link+ "&title=" + title);
          } else if (item.hasClass('stumble')) {
              window.open ("http://www.stumbleupon.com/submit?title=" + title + "&url=" + link);
          } else if (item.hasClass('linkedin')) {
              var summary = headerNode.parent().parent().find('div#leftContent').text();
              window.open ("http://www.linkedin.com/shareArticle?mini=true&url=" + link + "&title="
                  + title + "&source=Crytek.com" + (encodeURIComponent(summary) ? "&summary="
                  + summary.substr(0,255) : ""));
          }

        },
        _onMouseoverDropdown : function (e) {
            $(this).addClass('active');
        },
        _onMouseoutDropdown : function (e) {
            $(this).removeClass('active');
        },

        /* Implementation rev. 2  */
        applyRouter : function() {

          if (document.location.hash && document.location.hash != '#') {
                var param = document.location.hash.substring(1);
                if (param == 'video') {
                    new gallery({
                        boundingBox : $('#video-gallery')
                    });
                }
            }
        },
        cancelCnTooltipHide : function(e) {
            var id = $(e.currentTarget).attr('id');
            if (e.data.cnTooltipTimer[id]) {
                window.clearTimeout(e.data.cnTooltipTimer[id]);
                e.data.cnTooltipTimer[id] = null;
            }
        },
        hideCnTooltip : function(e) {
          var el = $(e.currentTarget);
          var id = el.attr('id');
          e.data.cnTooltipTimer[id] = window.setTimeout($.proxy(function(){
                el.addClass('hidden');
          }, e.data), 100);
        },

        cancelDropdownHide : function(e) {
            if (e.data.dropdownTimer) {
                window.clearTimeout(e.data.dropdownTimer);
                e.data.dropdownTimer = null;
            }
        },
        hideDropdown : function(e) {
          $(this).parent().find('a.share').removeClass('up').addClass('down');
          var el = $(e.currentTarget);
          e.data.dropdownTimer = window.setTimeout($.proxy(function(){
                el.hide();
          }, e.data), 100);
        },

        cancelTooltipHide : function() {
            if (this.searchTooltipTimer) {
                window.clearTimeout(this.searchTooltipTimer);
                this.searchTooltipTimer = null;
            }
        },
        hideTooltip : function() {
          this.searchTooltipTimer = window.setTimeout($.proxy(function(){
                this.searchTooltipNode.addClass("hidden");
          }, this), SEARCHTOOLTIPHIDEDELAY);
        },
        _changeSearchIn : function(e) {
            $('#searchForm input[name=op]').attr('value', 'Advanced search');
            if ($(e.currentTarget).val() == 'blog') {
                $('#searchForm input.blog').attr('value', 'blog');
                $('#searchForm input.page').attr('value', '');
            }
            if ($(e.currentTarget).val() == 'page') {
                $('#searchForm input.blog').attr('value', '');
                $('#searchForm input.page').attr('value', 'page');
            }
        },
        _submitSearchForm : function(e) {
            e.preventDefault();
            window.location.href = '/search/node/'
                + $(e.currentTarget).find('input[name=keys]').attr('value');
        },
        _mouseOverPageTeaser : function(e) {
            if ($(e.currentTarget).hasClass("fade")) {
                $(e.currentTarget).find("div.overlay").fadeTo(450, 0.99);
            } else
            if ($(e.currentTarget).hasClass("hover")) {
                $(e.currentTarget).find("div.overlay").show();
            }
        },
        _mouseOutPageTeaser : function(e) {
            if ($(e.currentTarget).hasClass("fade")) {
                $(e.currentTarget).find("div.overlay").fadeTo(450, 0);
            } else
            if ($(e.currentTarget).hasClass("hover")) {
                $(e.currentTarget).find("div.overlay").hide();
            }
        },
        _keypressSearch : function(e) {
            e.data.searchTooltipNode.removeClass("hidden");
            e.data.searchTooltipNode.die("mouseover").live("mouseover", e.data, function(e){
               e.data.cancelTooltipHide();
            });
            e.data.searchTooltipNode.die("mouseleave").live("mouseleave", e.data, function(e){
                e.data.hideTooltip();
            });
            e.data.searchInput.die("blur").live("blur", e.data, function(e){
                e.data.hideTooltip();
            });
        }
    };

    $(document).ready(function(){
        new desktop();        
    });

})( jQuery );
