var LazyLoader = {}; //namespace
LazyLoader.timer = {}; // contains timers for scripts
LazyLoader.scripts = []; // contains called script references
LazyLoader.load = function (url, context, callback) {
    //console.log("Load");
    // handle object or path
    var classname = null,
        properties = null;
    try {

        // make sure we only load once
        // note that we loaded already
        LazyLoader.scripts.push(url);
        var script = document.createElement("script");
        script.src = url;
        script.type = "text/javascript";
        context.get(0).appendChild(script); // add script tag to head element
        // was a callback requested
        if (callback) {
            // test for onreadystatechange to trigger callback
            script.onreadystatechange = function () {
                if (script.readyState === 'loaded' || script.readyState === 'complete') {
                    callback();
                    jQuery(script).remove();
                }
            };
            // test for onload to trigger callback
            script.onload = function () {
                callback();
                jQuery(script).remove();
                return;
            };
            // safari doesn't support either onload or readystate, create a timer
            // only way to do this in safari
            try {
                if (($.browser.webkit && !navigator.userAgent.match(/Version\/3/)) || $.browser.opera) { // sniff
                    LazyLoader.timer[url] = setInterval(function () {
                        if (/loaded|complete/.test(document.readyState)) {
                            clearInterval(LazyLoader.timer[url]);
                            callback(); // call the callback handler
                        }
                    }, 10);
                }
            } catch (e) {}
        }
    } catch (er) {
        alert(er);
    }
};


(function ($) {

    $.lazyLoadAdRunning = false;
    $.lazyLoadAdTimers = [];

    $.fn.lazyLoadAd = function () {
        var settings = {
            failurelimit: 1,  //??? Что это
            event: "scroll",
            viewport: window,
//            placeholder: false,
            // Can specify a picture to replace media while loading
//            onLoad: false,
//            onComplete: false,
            timeout: 1500  // ???? Зачем
        };

//        if (options) {
//            $.extend(settings, options);
//        }

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        var elements = this;
//        console.log ("elements: ",elements);
        $(settings.viewport).bind("checkLazyLoadAd", function () {
            var counter = 0;
            elements.each(function () {
                if ($.lazyLoadAdRunning) {
                    if ($.lazyLoadAdTimers.runTimeOut) {
                        clearTimeout($.lazyLoadAdTimers.runTimeOut);
                    }

                    $.lazyLoadAdTimers.runTimeOut = setTimeout(function () {
                        $(settings.viewport).trigger("checkLazyLoadAd");
                    }, 300);
                    return false;
                } else if (!$.belowthefold(this, settings) && !$.abovethetop(this, settings)) {
                    $(this).trigger("load");
                } else {
                    if (counter++ > settings.failurelimit) {
                        return false;
                    }
                }
            });

            /* Remove element from array so it is not looped next time. */
            // Удаляем из массива элементы с атрибутом
            var temp = $.grep(elements, function (element) {
                return !(($(element).data('loaded') === 'true') ? true : false);
            });
            elements = $(temp);
        });

        // Когда скролл, проверяем
        // нет ли элементов рекламы
        $(settings.viewport).bind("scroll", function (event) {
            if (elements.length === 0) {
                return false;
            }

            $(settings.viewport).trigger("checkLazyLoadAd");
        });



        // -- Bind each element
        this.each(function (_index, _value) {

            var self = $(this);

            /* Save original only if it is not defined in HTML. */
            if (undefined === self.attr("original")) {
                self.attr("original", self.attr("src"));
            }

            /* Test if element is loaded */
            self.isLoaded = function () {
                return ((self.data('loaded') === 'true') ? true : false);
            };


            /* On ad Load successful */
            self.one('onComplete', function () {

                // -- Remove original attr
                $(self).removeAttr("original");

                // -- Set as loaded
                $.lazyLoadAdRunning = false;
                self.data('loaded', 'true');

            });


            /* Launch the makina !! */
            self.stack = [];
            self.makinaBlock = false;
            self.bind('makina_go', function () {

                if (self.makinaBlock) {
                    return false;
                }

                if (self.stack.length > 0) {
                    var el = self.stack.shift();

                    var wrapAd = self.find('.wrapAd');
                    if (!wrapAd.length) {
                        wrapAd = $('<div class="wrapAd"></div>').clone();
                        wrapAd.appendTo(self);
                    }

                    var wrap = $('<div>').clone().appendTo(wrapAd);

                    if (typeof el === 'string') {
                        wrap.replaceWith(el);
                    } else if (typeof el === 'object') {
                        if (el.is('script')) {

                            // -- Load JS and block makina until script is loaded
                            if (el.attr('src')) {
                                //self.makinaBlock = true ;
                                LazyLoader.load(el.attr('src'), self, function () {
                                    self.makinaBlock = false;
                                    self.trigger('makina_go');
                                });
                            }

                            // -- Write JS code in wrapper
                            else {
                                wrap.replaceWith(el);
                            }
                        } else {
                            wrap.replaceWith(el);
                        }
                    }

                    self.trigger('makina_go');
                } else {
                    if ($.lazyLoadAdTimers.loadJS) {
                        clearTimeout($.lazyLoadAdTimers.loadJS);
                    }
                    $.lazyLoadAdTimers.loadJS = setTimeout(function () {
                        self.trigger('onComplete');
                    }, settings.timeout);
                }

            });

            /* Write directly in DOM : tag is html valid */
            self.bind('docWrite_direct', function (e, html) {
                var el = $(html);
                $.each(el, function () {
                    self.stack.push($(this));
                });
                self.trigger('makina_go');
            });

            /* Write directly in DOM : tag is html valid */
            self.bind('docWrite_delayed', function (e, html) {
//                _debug('Fragment Delayed Write : ', html);

                self.numWrappers--;
//                _debug("Fragment append : ", self.numWrappers, html);
                self.docHtmlCurrent += html;
                if (self.numWrappers === 0) {
                    html = self.docHtmlCurrent;
                    self.docHtmlCurrent = '';
                    setTimeout(function () {
                        self.stack.push(html);
                        self.docHtmlCurrent = '';
                        self.trigger('makina_go');
                    }, 0);
                }
            });



            /* Overload the default document.write */
            self.numWrappers = 0;
            self.docHtmlCurrent = '';
            self.bind('docWrite_overload', function () {

                // -- Overload default document.write function
                document._writeOriginal = document.write;
                document.write = document.writeln = function () {

                    var args = arguments,
                        id = null;
                    var html = '';
                    for (var i = 0; i < args.length; i++) {
                        html += args[i];
                    }

                    // -- Check if html to write is valid
                    var testHTML = '',
                        directWrite = false;

                    try {
                        testHTML = $(html);
                        directWrite = ((testHTML.is('div') || testHTML.is('script')) ? true : false);
                    } catch (e) {}

                    self.history[self.fragmentId] = self.history[self.fragmentId] || {};
                    if (self.history[self.fragmentId][html] === undefined) {
                        self.history[self.fragmentId][html] = true;
                        if (directWrite) {
                            self.trigger('docWrite_direct', html);
                        } else {
                            self.numWrappers++;
                            setTimeout(function () {
                                self.trigger('docWrite_delayed', html);
                            }, 0);

                        }
                    }
                };
            });


            /* Eval Script into <code> tags */
            self.bind('evalCode', function () {
                var scripts = [],
                    script, regexp = /<code[^>]*>([\s\S]*?)<\/code>/gi;

                while ((script = regexp.exec(self.html()))) {
                    var _s = script[1];
                    _s = _s.replace('<!--//<![CDATA[', '').replace('//]]>-->', '').replace('<!--', '').replace('//-->', '');
                    _s = _s.replace(/\&gt\;/g, '>').replace(/\&lt\;/g, '<');
                    scripts.push($.trim(_s));
                }

                // -- Eval param code before calling ad script                    
                try {
                    scripts = (scripts.length ? scripts.join('\n') : '');
//                    _debug('Script to eval : ', scripts);
                    if (scripts !== '') {
                        eval(scripts);
                    }
                } catch (e) {}
            });


            /* Load a JS and wait for callback */
            self.bind('loadJS', function (e, js2load) {

                var callback = null,
                    script = null;
                if (js2load.src) {
                    callback = js2load.callback ||  null;
                    js2load = js2load.src;
                }

                // Add an anticache 
                if (js2load.indexOf('?') === -1) {
                    js2load += '?_=' + (new Date().getTime());
                } else {
                    js2load += '&_=' + (new Date().getTime());
                }

//                _debug('loadJS :: ', js2load);

                // Request JS
                LazyLoader.load(js2load, self, function () {
//                    _debug('loadJS COMPLETE :: ' + js2load);
                    if (callback) {
                        callback();
                    } 
                    else {
                        $.lazyLoadAdTimers.loadJS = setTimeout(function () {
                            self.trigger('onComplete');
                        }, settings.timeout);
                    }
                });

            });


            /* When appear is triggered load ad. */
            self.one("load", function () {

//                console.log("load",self);

                // Detect if element is already loaded
                if (!self.isLoaded()) {

//                    console.log("isLoaded",self);

                    // Lock other adverts load
                    $.lazyLoadAdRunning = true;

                    // Have to load the current ad...
                    self.data('loading', 'true');

                    // Get original source to load
                    var srcOriginal = $(self).attr("original");

                    // Set fragmentId
                    self.history = {};

                    // Bind document.write overload
                    self.trigger('docWrite_overload');

                    // Eval code
                    self.trigger('evalCode');

                    // Eval attached script
                    if (srcOriginal) {
                        self.trigger('loadJS', srcOriginal);
                    }

                }
            });



            /* When wanted event is triggered load ad */
            /* by triggering appear.                              */
            if ("scroll" !== settings.event) {
                self.bind(settings.event, function (event) {
                    if (!self.isLoaded()) {
                        self.trigger("load");
                    }
                });
            }
        });

        /* Force initial check if images should appear. */
        $(settings.viewport).trigger("checkLazyLoadAd");

        return this;

    };

    /* Convenience methods in $ namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function (element, settings) {
        var fold = 0;
        if (settings.viewport === undefined || settings.viewport === window) {
            fold = $(window).height() + $(window).scrollTop();
        } else {
            fold = $(settings.viewport).offset().top + $(settings.viewport).height();
        }
        return fold <= $(element).offset().top;
    };

    $.abovethetop = function (element, settings) {
        var fold = 0;
        if (settings.viewport === undefined || settings.viewport === window) {
            fold = $(window).scrollTop();
        } else {
            fold = $(settings.viewport).offset().top;
        }
        return fold >= $(element).offset().top + $(element).height();
    };

})(jQuery);

function niceThumb () {
    $("ul.thumb li").hover(function() {
        var thumbinal = $(this);
        thumbinal.css({'z-index' : '10'});
        thumbinal.find('img').addClass("hover")
                .animate({
                        marginTop: '-100px',
                        marginLeft: '-160px',
                        top: '50%',
                        left: '50%',
                        width: '300px',
                        height: '200px'

                }, 200);

        thumbinal.find('.info').addClass("hover")
                .animate({
                        marginTop: '71px',
                        marginLeft: '-160px',
                        top: '50%',
                        left: '50%',
                        width: '300px'

                }, 200);

         thumbinal.find('.text').addClass("hover")
                .animate({
                        marginTop: '76px',
                        marginLeft: '-160px',
                        top: '50%',
                        left: '50%',
                        width: '300px'

                }, 200);

        } , function() {
        var thumbinal = $(this);
        thumbinal.css({'z-index' : '0'});
        thumbinal.find('img').removeClass("hover").stop()
                .animate({
                        marginTop: '0',
                        marginLeft: '0',
                        top: '0',
                        left: '0',
                        width: '174px',
                        height: '117px'

                }, 200);

        thumbinal.find('.info').addClass("hover").stop()
                .animate({
                        marginTop: '25px',
                        marginLeft: '-91px',
                        top: '50%',
                        left: '50%',
                        width: '174px'

                }, 200);

         thumbinal.find('.text').addClass("hover").stop()
                .animate({
                        marginTop: '30px',
                        marginLeft: '-91px',
                        top: '50%',
                        left: '50%',
                        width: '161px'

                }, 200);

       });
};


$(function(){

    // Tabs
    $('#tabs').tabs();


    // Dialog
    $('#dialog').dialog({
        autoOpen: false,
        width: 'auto',
        title: 'Login with:'
    });
    $('#what_is_players_choice').dialog({
        autoOpen: false,
        width: 500,
        title: 'What is "Players\' choice"?'
    });

    // Dialog Link
    $('#login_panel').click(function(){
        $("#dialog").load('login_panel_new.php');
        $('#dialog').dialog('open');
        return false;
    });
    $('#what_is_players_choice_button a').click(function(){
        $('#what_is_players_choice').dialog('open');
        return false;
    });
    $('#language_select_button').click(function(){
        $('#language').dialog('open');
        return false;
    });

});




