var initControls = initControls || function(){
    jQuery(".main-nav li").hover(
        function() { 
            jQuery(this).children('ul').fadeIn("fast");
        },
        function() { 
            jQuery(this).children('ul').fadeOut("fast");
        }
    );
    jQuery("input.hand:not(.btn-calendar)").hover(
        function () {
            jQuery(this).addClass("btn-hover");
        },
        function () {
            jQuery(this).removeClass("btn-hover");
        }
    );
    jQuery(".bb-upgr-progr-link").hover(
        function () {
            jQuery(this).addClass("bb-upgr-progr-hover");
        },
        function () {
            jQuery(this).removeClass("bb-upgr-progr-hover");
        }
    );
    jQuery(".bb-get-career-link").hover(
        function () {
            jQuery(this).addClass("bb-get-career-hover");
        },
        function () {
            jQuery(this).removeClass("bb-get-career-hover");
        }
    );
    jQuery(".ebook").hover(
        function () {
            jQuery(this).addClass("ebook-hover");
        },
        function () {
            jQuery(this).removeClass("ebook-hover");
        }
    );
    jQuery(".bb-how-works-link").hover(
        function () {
            jQuery(this).addClass("bb-how-works-hover");
        },
        function () {
            jQuery(this).removeClass("bb-how-works-hover");
        }
    );
    jQuery(".sticker-box").hover(
        function () {
            jQuery(this).addClass("sticker-box-hover");
        },
        function () {
            jQuery(this).removeClass("sticker-box-hover");
        }
    );
    jQuery(".sticker-box-short").hover(
        function () {
            jQuery(this).addClass("sticker-box-short-hover");
        },
        function () {
            jQuery(this).removeClass("sticker-box-short-hover");
        }
    );
    jQuery(".sticker-box-sm").hover(
        function () {
            jQuery(this).addClass("sticker-box-sm-hover");
        },
        function () {
            jQuery(this).removeClass("sticker-box-sm-hover");
        }
    );
    jQuery(".sticker-box-big").hover(
        function () {
            jQuery(this).addClass("sticker-box-big-hover");
        },
        function () {
            jQuery(this).removeClass("sticker-box-big-hover");
        }
    );
    jQuery(".sticker-big-box-dark").hover(
        function () {
            jQuery(this).addClass("sticker-big-box-dark-hover");
        },
        function () {
            jQuery(this).removeClass("sticker-big-box-dark-hover");
        }
    );
    jQuery(".sticker-big-box-sktl").hover(
        function () {
            jQuery(this).addClass("sticker-big-box-sktl-hover");
        },
        function () {
            jQuery(this).removeClass("sticker-big-box-sktl-hover");
        }
    );
    jQuery(".sccs-story").hover(
        function () {
            jQuery(this).addClass("sccs-story-hover");
        },
        function () {
            jQuery(this).removeClass("sccs-story-hover");
        }
    );
    jQuery(".right-col .downl-ebook-big").hover(
        function () {
            jQuery(this).addClass("downl-ebook-big-hover");
        },
        function () {
            jQuery(this).removeClass("downl-ebook-big-hover");
        }
    );
    jQuery(".my-products h4").click(
        function () {
            jQuery(this).parent().children('ul').slideToggle(200);
            jQuery(this).parent().toggleClass("collapsed");
            if (!Arboreus.isAllowedCookie) {
                return;
            }
            if (jQuery(this).attr('id')) {
            	if (jQuery(this).parent().hasClass('collapsed')) {
            		if (jQuery(this).attr('id') != 'my_online_test') {
                        jQuery.cookie(jQuery(this).attr('id'), 1, {expires: 180});
            		} else {
            			jQuery.cookie(jQuery(this).attr('id'), 1, {expires: 180});
            		}
            	} else {
            		if (jQuery(this).attr('id') != 'my_online_test') {
            		  jQuery.cookie(jQuery(this).attr('id'), 0, {expires: 180});
            		} else {
            			jQuery.cookie(jQuery(this).attr('id'), 0, {expires: 180});
            		}
            	}
            }
        }
    );
    jQuery(".items-list:not(.skip) h3").click(
        toggleItemsContainer = function () {
            jQuery(this).children(".switch").toggleClass("expand");
            jQuery(this).parent().children('div').slideToggle(200);
            jQuery(this).toggleClass("mb-0");
        }
    );
    
    jQuery(".item h2").click(
        function () {
            jQuery(this).parent().children('div.container').slideToggle(200);
            jQuery(this).parent().toggleClass("collapsed");
        }
    );
    
    jQuery(".btn-show-all span").click(
        function () {
            jQuery(this).addClass("d-none");
            jQuery(this).parent().parent().children('div.container').removeClass("collapsed");
            jQuery(this).parent().parent().children('div.container').children('ul').fadeIn(200);
            jQuery(this).parent().children('b').removeClass("d-none");
            if (!Arboreus.isAllowedCookie) {
                return false;
            }
            jQuery.cookie('my_online_test', 0, {expires: 180});
            jQuery.cookie('my_online_courses', 1, {expires: 180});
            jQuery.cookie('my_job_ads', 1, {expires: 180});
        }
    );
    jQuery(".btn-show-all b").click(
        function () {
            jQuery(this).addClass("d-none");
            jQuery(this).parent().parent().children('div.container').addClass("collapsed");
            jQuery(this).parent().parent().children('div.container').children('ul').fadeOut(200);
            jQuery(this).parent().children('span').removeClass("d-none");
            if (!Arboreus.isAllowedCookie) {
                return false;
            }
            jQuery.cookie('my_online_test', 1, {expires: 180});
            jQuery.cookie('my_online_courses', 0, {expires: 180});
            jQuery.cookie('my_job_ads', 0, {expires: 180});
        }
    );

    jQuery(".items-list .btn-show-hide .hide-posit").click(
        function () {
            jQuery(this).addClass("d-none");
            jQuery(this).parent().parent().children('div.item').addClass("collapsed");
            jQuery(this).parent().parent().children('div.item').children('div.container').fadeOut(200);
            jQuery(this).parent().children('span.show-posit').removeClass("d-none");
        }
    );

    jQuery(".items-list .btn-show-hide .show-posit").click(
        function () {
            jQuery(this).addClass("d-none");
            jQuery(this).parent().parent().children('div.item').removeClass("collapsed");
            jQuery(this).parent().parent().children('div.item').children('div.container').fadeIn(200);
            jQuery(this).parent().children('span.hide-posit').removeClass("d-none");
        }
    );
    
    jQuery(".box-faq a.arr").click(
      		function () {
      			jQuery(this).parents("li").toggleClass("active");

                var id = jQuery(this).attr('name');
                jQuery.post(
                    oState.baseUrl + 'ajax/faq-count.php',
                    {'ids[]': id}
                )
    			return false
    		}
    	);
    	jQuery(".box-faq h2 .btn-show-hide .hide-posit").click(
      		function () {
      			jQuery(this).addClass("d-none");
      			jQuery(this).parent().parent().parent().children('div.in').children().children('li').removeClass("active");
      			jQuery(this).parent().children('span.show-posit').removeClass("d-none");
      		}
    	);
    	jQuery(".box-faq h2 .btn-show-hide .show-posit").click(
      		function () {
      			jQuery(this).addClass("d-none");
      			jQuery(this).parent().parent().parent().children('div.in').children().children('li').addClass("active");
      			jQuery(this).parent().children('span.hide-posit').removeClass("d-none");
                var ids = [];
                jQuery(this).parent().parent().parent().find('a.arr').each(function() {
                    ids.push(jQuery(this).attr('name'));
                })
                jQuery.post(
                    oState.baseUrl + 'ajax/faq-count.php',
                    {'ids[]': ids}
                )
      		}
    	);

    jQuery(".news-item").hover(
        function () {
            jQuery(this).addClass("news-item-hover");
        },
        function () {
            jQuery(this).removeClass("news-item-hover");
        }
    );
        
    jQuery(".forum-list").hover(
        function () {
            jQuery(this).addClass("forum-list-hover");
        },
        function () {
            jQuery(this).removeClass("forum-list-hover");
        }
    );
        
    jQuery(".browse-blog .content").hover(
        function () {
            jQuery(this).addClass("hover");
        },
        function () {
            jQuery(this).removeClass("hover");
        }
    );
        
    initControls.initCustomSelect = function (container) {
        if (container) {
            container = jQuery(container).find(".customSelect")
        } else {
            container = jQuery(".customSelect");
        }

        var cusSelN = 1;
        container.each(function(){
            var id = jQuery(this).attr('id');
            if (!id) {
                jQuery(this).attr("id", "cusSelect" + cusSelN);
                id = "cusSelect" + cusSelN
                cusSelN += 1;
            }
            var width = jQuery(this).width();

            jQuery("body").append("<script type='text/javascript'>new Select('" + id + "', {dropDownSize: 15, width: " + width + "});</script>")

        });
    }

    initControls.initCustomSelect();

    jQuery(".blueBox h3 .close").click(
        function () {
            jQuery(this).parents(".blueBox").slideUp(200);
        }
    );
    
	jQuery(".order-block h3").click(
  		function () {
			jQuery(this).parent().children('div.container').slideToggle(200);
			jQuery(this).toggleClass("border");
  		}
	);
	
    jQuery(".rates").each(function(){
        var el = jQuery(this);
        var id = el.attr('id');
        if (!id) {
            return;
        }
        el.children().each(function(){
           jQuery(this).click(function(){
               var stars = 0;
               var starEl = jQuery(this);
               jQuery.each([1,2,3,4,5], function (){
                   if (starEl.hasClass('st-' + this)) {stars = this;}
               })
               
               jQuery.post('study_material-vote.php',
                    {id: id,
                     stars: stars},
                    function (result){
                         switch (result) {
                              case "error-no-id":
                              case "error-is-guest":
                              case "error-not-downloaded":
                              case "error-wrong-stars":
                              case "error-was-woted":
                                  return false;
                                  break;
                              default:
                                 var voteResult = result.match(/(\d)\:(\d)/);
                                 jQuery.each(['s0','s1','s2','s3','s4','s5'],
                                             function() {
                                                 el.removeClass(this)
                                             }
                                 )
                                 el.addClass('s' + voteResult[1]);
                                 var voteText = 'votes';
                                 if (voteResult[2] == 1) {
                                     voteText = 'vote';
                                 }
                                 el.children('p').text(voteResult[2] + ' ' + voteText);
                                  break;
                         }
                    }, "text");
               return false;
           })
        })
    })
    
    jQuery(".online_courses_rates").each(function(){
        var el = jQuery(this);
        var id = el.attr('id');

        var div_body     = jQuery('body');
        var div_all     = jQuery('.all');
        var div_left    = jQuery(".left-col");
        var position    = div_body.position();
        var width       = div_all.width();
        var height      = div_left.height();
        var opaceEl     = jQuery('#load-tips-tricks');

        if (div_all.length === 0) {
            return;
        }

        opaceEl.css('left', (position.left) + 'px');
        opaceEl.css('top', (position.top) + 'px');

        if (!id) {
            return;
        }
        el.children().each(function(){
           jQuery(this).click(function(){
               var stars = 0;
               var starEl = jQuery(this);
               jQuery.each([1,2,3,4,5], function (){
                   if (starEl.hasClass('st-' + this)) {stars = this;}
               })
               //alert(typeof(stars));
               if (typeof(stars)=='object') {
                opaceEl.show();
                opaceEl.width(width);
                opaceEl.height(height);

        jQuery('#error_online_courses_vote_popup').css('top', (jQuery(".online_courses_rates#"+id).offset().top-120)+'px');
               jQuery.post( oState.baseUrl + 'online_courses_vote.php',
                    {id: id,
                     stars: stars},
                    function (result){
                         jQuery("#NO_ID").hide();
                         jQuery("#WRONG_STARS").hide();
                         jQuery("#IS_GUEST").hide();
                         jQuery("#is-not-purchased").hide();
                         jQuery("#WAS_VOTED").hide();
                         jQuery("#SUCCESS_VOTED").hide();
                         switch (result.result) {
                            case "error-no-id":
                                opaceEl.hide();
                                jQuery("#NO_ID").show();
                                jQuery('#error_online_courses_vote_popup').show();
                                break;
                            case "error-is-guest":
                                opaceEl.hide();
                                jQuery("#IS_GUEST").show();
                                jQuery('#error_online_courses_vote_popup').show();
                                break;
                            case "error-not-purchased":
                                opaceEl.hide();
                                jQuery("#is-not-purchased").show();
                                jQuery('#error_online_courses_vote_popup').show();
                                break;
                            case "error-wrong-stars":
                                opaceEl.hide();
                                jQuery("#WRONG_STARS").show();
                                jQuery('#error_online_courses_vote_popup').show();
                                break;
                            case "error-was-voted":
                                opaceEl.hide();
                                jQuery("#WAS_VOTED").show();
                                jQuery('#error_online_courses_vote_popup').show();
                                break;
                            default:
                                jQuery.each(['s0','s1','s2','s3','s4','s5'],
                                            function() {
                                                el.removeClass(this)
                                            }
                                )
                                el.addClass('s' + result.result);
                                var voteText = 'votes';
                                if (result.count == 1) {
                                    voteText = 'vote';
                                }
                                el.children('p').text(result.count + ' ' + voteText);
                                opaceEl.hide();
                                jQuery("#SUCCESS_VOTED").show();
                                jQuery('#error_online_courses_vote_popup').show();
                                break;
                         }
                         // var opaceEl     = jQuery('#load-tips-tricks');
                    }, "json");
           }
               return false;
           })
        })
    })


    jQuery('form#useful-video-form, form#useful-rss-form').submit(function(){
        var form = jQuery(this);
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        
        var url = form.find('input[name=url]').val();
        var type = form.find('input[name=type]').val();
        if (!regexp.test(url)){
            form.find('input[name=url]').val(form.find('.incorrect-url').text())
            setTimeout(function(){
                if (form.find('input[name=url]').val() == form.find('.incorrect-url').text()) {
                    form.find('input[name=url]').val(url)
                }
            }, 5000);
            return false;
        }
        
        jQuery.post(this.action,{
            url: url,
            type: type},
            function(result){
                    switch (result) {
                        case "ok":
                            form.find('input[name=url]').val('http://');
                            toggleQuitPopup();
                            break;
                        case "file not found":
                            //form.find('input[name=url]').val(form.find('.url-was-sended').text());
                            toggleErrorPopup();
                        default:
                            break;
                    }
                    return false;
            },
            'text'
        );
        return false;
    });

        function toggleQuitPopup()
        {
            if (jQuery('#quit-popup').hasClass('hidden')) {
                //hidden - then display
                //when IE - fade immediately
                if (jQuery.browser.msie) {
                    jQuery('#opaco').height(jQuery(document).height()).toggleClass('hidden')
                        .click(function(){toggleQuitPopup();});
                } else { //in all the rest browsers - fade slowly
                    jQuery('#opaco').height(jQuery(document).height()).toggleClass('hidden').fadeTo('slow', 0.7)
                        .click(function(){toggleQuitPopup();});
                }
                jQuery('#quit-popup')
                    .alignCenter()
                    .toggleClass('hidden');
            } else {
                jQuery('#opaco').toggleClass('hidden').removeAttr('style').unbind('click');
                jQuery('#quit-popup').toggleClass('hidden');
            }
        }
        jQuery('#quit-popup input[name=ok]').click(function(){
            toggleQuitPopup();
            return false;
        })

        function toggleErrorPopup()
        {
            if (jQuery('#error-popup').hasClass('hidden')) {
                //hidden - then display
                //when IE - fade immediately
                if (jQuery.browser.msie) {
                    jQuery('#opaco').height(jQuery(document).height()).toggleClass('hidden')
                        .click(function(){toggleQuitPopup();});
                } else { //in all the rest browsers - fade slowly
                    jQuery('#opaco').height(jQuery(document).height()).toggleClass('hidden').fadeTo('slow', 0.7)
                        .click(function(){toggleQuitPopup();});
                }
                jQuery('#error-popup')
                    .alignCenter()
                    .toggleClass('hidden');
            } else {
                jQuery('#opaco').toggleClass('hidden').removeAttr('style').unbind('click');
                jQuery('#error-popup').toggleClass('hidden');
            }
        }
        jQuery('#error-popup input[name=ok]').click(function(){
            toggleErrorPopup();
            return false;
        })

	jQuery("input[type='checkbox']").addClass('checkbox');
}

jQuery(document).ready(function ()
{
    initControls();

    if (Arboreus && Arboreus.Tooltip) {
        Arboreus.tooltips = new Arboreus.Tooltip('#tooltip-template', '*[rel=tooltip1]');
    }
});

(function($) {
     jQuery.fn.elHover = function() { 
        jQuery(this).hover(function () {
            if (!jQuery(this).hasClass('cur') && jQuery(this).parent().hasClass('main-nav')){
                jQuery(this).parent().find('li.cur').removeClass('cur').addClass('cur-nohover');
            }
            jQuery(this).addClass("hover");
        },
         function () {
            jQuery(this).removeClass("hover");
            if (!jQuery(this).hasClass('cur-nohover') && jQuery(this).parent().hasClass('main-nav')){
                jQuery(this).parent().find('li.cur-nohover').removeClass('cur-nohover').addClass('cur');
            }
        }
       );
     };
     jQuery.fn.elSlide = function() { 
        jQuery(this).click(function () {
            jQuery(this).parent().toggleClass("collapsed");
            jQuery(this).parent().children('div.container').slideToggle(200);
            jQuery(this).parent().children('div.he3').slideToggle(200);
            jQuery(this).parent().children('span.btn-show-all').slideToggle(200);
        }
       );
     };
})
(jQuery);

(function($) {
	$.fn.printElement = function(options) {
		var mainOptions = $.extend( {}, $.fn.printElement.defaults, options);
		$("[id^='printElement_']").remove();
		return this.each(function() {
			var opts = $.meta ? $.extend( {}, mainOptions, $this.data())
					: mainOptions;
			_printElement($(this), opts);
		});
	};
	$.fn.printElement.defaults = {
		printMode : 'popup',
		pageTitle : '',
		overrideElementCSS : [],
		printBodyOptions : {
			styleToAdd : 'padding:10px;margin:10px;',
			classNameToAdd : ''
		},
		leaveOpen : false,
		iframeElementOptions : {
			styleToAdd : 'position:absolute;width:0px;height:0px;',
			classNameToAdd : ''
		}
	};
	function _printElement(element, opts) {
		var $elementToPrint = $(element);
		var html = _getMarkup($elementToPrint, opts);
		var popupOrIframe = null;
		var documentToWriteTo = null;
		if (opts.printMode.toLowerCase() == 'popup') {
			popupOrIframe = window.open('', 'printElementWindow',
					'width=650,height=440,scrollbars=yes');
			documentToWriteTo = popupOrIframe.document;
		} else {
			var printElementID = "printElement_"
					+ (Math.random() * 99999).toString();
			iframe = document.createElement('IFRAME');
			$(iframe).attr( {
				style : opts.iframeElementOptions.styleToAdd,
				id : printElementID,
				className : opts.iframeElementOptions.classNameToAdd
			});
			document.body.appendChild(iframe);
			documentToWriteTo = iframe.contentWindow.document;
			var iframe = document.frames ? document.frames[printElementID]
					: document.getElementById(printElementID);
			popupOrIframe = iframe.contentWindow || iframe;
		}
		documentToWriteTo.open();
		documentToWriteTo.write(html);
		documentToWriteTo.close();
		popupOrIframe.focus();
	}
	;
	function _getMarkup(element, opts) {
		var $elementToPrint = $(element);
		var html = new Array();
		html.push('<html><head><title>' + opts.pageTitle + '</title>');
		if (opts.overrideElementCSS && opts.overrideElementCSS.length > 0) {
			for ( var x = 0; x < opts.overrideElementCSS.length; x++) {
				html
						.push('<link type="text/css" rel="stylesheet" href="' + opts.overrideElementCSS[x] + '" >');
			}
		} else {
			$(document)
					.find("link ")
					.filter(
							function() {
								return $(this).attr("rel").toLowerCase() == "stylesheet";
							})
					.each(
							function() {
								html
										.push('<link type="text/css" rel="stylesheet" href="' + $(
												this).attr("href") + '" >');
							});
		}
		html.push('</head><body onload="printPage();" style="'
				+ opts.printBodyOptions.styleToAdd + '" class="'
				+ opts.printBodyOptions.classNameToAdd + '">');
		html.push('<div class="' + $elementToPrint.attr("class") + '">'
				+ $elementToPrint.html() + '</div>');
		html
				.push('<script type="text/javascript">function printPage() { focus();print();' + (opts.leaveOpen ? ''
						: 'close();') + '}</script></body></html>');
		return html.join('');
	}
	;
})(jQuery);


jQuery(function(){
   jQuery('.main-nav li').elHover();
   jQuery('.footer ul li').elHover();
   jQuery('.inline-menu li').elHover();
   jQuery('.my-cart .container').elHover();
   jQuery('.blue-grad-bott .left .container').elHover();
   jQuery('.blue-grad-bott .right .container').elHover();
   jQuery('.tips-tricks-list .container').elHover();
   jQuery('.gray-grad .container').elHover();
   jQuery('.community-col-bott .container').elHover();
   jQuery('.news-col .container').elHover();
   jQuery('.grad-list .grad-list-bg ul li').elHover();
   jQuery('.my-cart .switch').elSlide();
   jQuery('.my-cart .switcher').elSlide();
//   jQuery('.my-products .switch').elSlide();
//   jQuery('.my-products .switcher').elSlide();
   //jQuery('.my-acc .switch').elSlide();
   //jQuery('.my-acc .switcher').elSlide();
   
   
    jQuery('.my-products .switch, .my-products .switcher').click(function(){
        jQuery(this).parent().toggleClass("collapsed");
        jQuery(this).parent().children('div.container').slideToggle(200);
        jQuery(this).parent().children('div.he3').slideToggle(200);
        jQuery(this).parent().children('span.btn-show-all').slideToggle(200);

        if (!Arboreus.isAllowedCookie) {
            return false;
        }
        if (jQuery(this).parent().hasClass('collapsed')) {
            jQuery.cookie('my_products', 1, {expires: 180});
        } else {
        	jQuery.cookie('my_products', 0, {expires: 180});
        }
   });
   
   jQuery('.my-acc .switch, .my-acc .switcher').click(function(){
        jQuery(this).parent().toggleClass("collapsed");
        jQuery(this).parent().children('div.container').slideToggle(200);
        jQuery(this).parent().children('div.he3').slideToggle(200);
        jQuery(this).parent().children('span.btn-show-all').slideToggle(200);
        if (!Arboreus.isAllowedCookie) {
           return false;
        }
        if (jQuery(this).parent().hasClass('collapsed')) {
            jQuery.cookie('my_acc', 0, {expires: 180});
        } else {
            jQuery.cookie('my_acc', 1, {expires: 180});
        }
   });
   
   
   });


var Exam = Exam || 
{
    iCenterIndex: 0, 
    iCurrentQuestion: 1, 
    iMaxWidth: 31, 
    bProcessing: false, 
    sBaseUrl: '/', 
    iDomainId: 0, 
    iMinutes: 0, 
    iSeconds: 0, 
    aQueue: [], 
    aQuestion2DomainId: {}, 
    iUnassignedNotes: 0, 
    bStopTimer: false, 

    initNavigation: function(sBaseUrl)
    {
        Trigger.addListener('selectDomain-change', function(oTrigger)
        {
            var iDomainId = document.getElementById('selectDomain').options[oTrigger.aArgs.index].value;

            Exam.setDomainId(iDomainId);
        });

        Exam.sBaseUrl = sBaseUrl;
        var oSelect   = new Select('selectDomain', {dropDownSize: 999});
        var $list     = jQuery('#navigation ul');
        var $elements = $list.find('li');

        if ($elements.length < Exam.iMaxWidth)
        {
            Exam.iMaxWidth = $elements.length;
        }

        $list.width(Exam.iMaxWidth * $elements.width()-3);

        Exam.iCenterIndex = Math.round(Exam.iMaxWidth / 2);

        $list.find('a').click(function()
        {
            Exam.gotoQuestion(jQuery(this).text());
        });

        Exam.reorderQuestions();
        
        jQuery('table.tl td.first').click(function()
        {
            Exam.gotoQuestion(1);
            
            return false;
        });

        jQuery('table.tl td.prev, input[name=prev]').click(function()
        {
            var iLength = jQuery('#navigation li').length;
            var iPrev   = (1 == Exam.iCurrentQuestion) ? jQuery('#navigation li').length : Exam.iCurrentQuestion - 1;

            if (Exam.iDomainId && Exam.aQuestion2DomainId[iPrev] != Exam.iDomainId)
            {
                var bFound = false;
                for (var i = Exam.iCurrentQuestion - 1; i > 0; i--)
                {
                    if (Exam.aQuestion2DomainId[i] == Exam.iDomainId)
                    {
                        bFound = true;
                        iPrev  = i;
                        break;
                    }
                }

                if (!bFound)
                {
                    for (var i = iLength; i >= Exam.iCurrentQuestion; i--)
                    {
                        if (Exam.aQuestion2DomainId[i] == Exam.iDomainId)
                        {
                            iPrev = i;
                            break;
                        }
                    }
                }
            }

            Exam.gotoQuestion(iPrev);

            return false;
        });

        jQuery('table.tl td.next, input[name=next], input[name=skip]').click(function()
        {
            var iLength = jQuery('#navigation li').length;
            var iNext   = (iLength == Exam.iCurrentQuestion) ? 1 : Exam.iCurrentQuestion + 1;

            if (Exam.iDomainId && Exam.aQuestion2DomainId[iNext] != Exam.iDomainId)
            {
                var bFound = false;
                for (var i = Exam.iCurrentQuestion + 1; i <= iLength; i++)
                {
                    if (Exam.aQuestion2DomainId[i] == Exam.iDomainId)
                    {
                        bFound = true;
                        iNext  = i;
                        break;
                    }
                }

                if (!bFound)
                {
                    for (var i = 1; i <= Exam.iCurrentQuestion; i++)
                    {
                        if (Exam.aQuestion2DomainId[i] == Exam.iDomainId)
                        {
                            iNext = i;
                            break;
                        }
                    }
                }
            }

            Exam.gotoQuestion(iNext);

            return false;
        });

        jQuery('table.tl td.last').click(function()
        {
            Exam.gotoQuestion(jQuery('#navigation li').length);
            
            return false;
        });

        $elements.find('a').click(function()
        {
            Exam.gotoQuestion(jQuery(this).text());

            return false;
        });

        Exam.initQuestion();

        jQuery('input[name=submit_test]').click(function()
        {
            jQuery('#submit_confirm').togglePopup();

            jQuery('#popup div.unanswered').hide();
            var iUnanswered = jQuery('#navigation li').length - jQuery('#navigation li.dark').length;
            if (iUnanswered)
            {
                jQuery('#popup div.unanswered').show();
                jQuery('#popup span.unanswered').html(iUnanswered);
            }
            jQuery('#popup input[name=submit]').click(Exam.submitResults);
        });

        jQuery('#quit').click(function()
        {
            jQuery.get(Exam.sBaseUrl + 'test/ajax_tracktime.php', {
                getm: Exam.iMinutes, 
                gets: Exam.iSeconds
                });

            try 
            {
                opener.location.href = Exam.sBaseUrl + 'compose_test';
            }
            catch (oError) 
            {
                opener.location.replace(Exam.sBaseUrl + 'compose_test');
            }

            window.close();

            return false;
        });

        jQuery('ul.tabs span.ico-add-note').click(function()
        {
            Exam.editNote();
        });

        jQuery('ul.tabs li.ico-my-notes a').click(function()
        {
            jQuery('#test-question').hide();
            jQuery('#all-test-notes').show();
            jQuery('ul.tabs li.ico-my-notes').addClass('cur');
            jQuery('ul.tabs li.ico-my-test').removeClass('cur');

            Exam.loadAllNotes();
        });

        jQuery('ul.tabs li.ico-my-test a').click(function()
        {
            jQuery('#test-question').show();
            jQuery('#all-test-notes').hide();
            jQuery('ul.tabs li.ico-my-notes').removeClass('cur');
            jQuery('ul.tabs li.ico-my-test').addClass('cur');
        });

        jQuery('input[name=autoshow-correct]').change(function()
        {
            jQuery.get(Exam.sBaseUrl + 'test/ajax_autoshowanswers.php', {hide: this.checked ? '' : '1'});
        });

        Exam.refreshProgress();
        Exam.initReportError();
    }, 

    gotoQuestion: function(iQuestion)
    {
        jQuery('#test-question').show();
        jQuery('#all-test-notes').hide();
        jQuery('ul.tabs li.ico-my-notes').removeClass('cur');
        jQuery('ul.tabs li.ico-my-test').addClass('cur');

        if (Exam.bProcessing)
        {
            Exam.aQueue.push(iQuestion);
        }
        else
        {
            Exam.bProcessing = true;
            Exam.realGotoQuestion(iQuestion);
        }

        Exam.iCurrentQuestion = new Number(iQuestion);
        Exam.reorderQuestions();
    }, 

    realGotoQuestion: function(iQuestion, aArgs)
    {
        aArgs = aArgs || {};

        jQuery.post(Exam.sBaseUrl + 'ajax_questions.php', jQuery.extend(aArgs, {
            q: new Number(iQuestion) - 1, 
            checkedOptionID: 0, 
            questionID: 0, 
            domainID: Exam.iDomainId, 
            getm: Exam.iMinutes, 
            gets: Exam.iSeconds
            }), 
            function(sResponse) 
            {
                jQuery('#test-question').html(sResponse);
                Exam.initQuestion();
                Exam.bProcessing = false;

                if (Exam.aQueue.length)
                {
                    Exam.bProcessing  = true;
                    var iLastQuestion = Exam.aQueue.pop();
                    Exam.aQueue       = [];
                    Exam.realGotoQuestion(iLastQuestion);
                }
            });
    }, 

    reorderQuestions: function()
    {
        var $list      = jQuery('#navigation ul');
        var $elements  = $list.find('li');
        var $current   = $list.find('li.question' + Exam.iCurrentQuestion);
        var iIndex     = $elements.index($current) + 1;
        var iEnd       = $elements.length;

        if (iIndex < Exam.iCenterIndex)
        {
            iEnd = iEnd - Exam.iCenterIndex + iIndex;
        }
        else if (iIndex > Exam.iCenterIndex)
        {
            iEnd = iIndex - Exam.iCenterIndex;
        }

        $elements.slice(0, iEnd).appendTo($list);
        $elements.removeClass('cur');
        $list.find('li.question' + Exam.iCurrentQuestion).addClass('cur');

        var $elements = $list.find('li');
        $elements.slice(0, Exam.iMaxWidth).show();
        $elements.slice(Exam.iMaxWidth, $elements.length).hide();
    }, 

    initQuestion: function()
    {
        jQuery(".answer").hover(
            function () {
                jQuery(this).addClass("sel-answered");
                },
            function () {
                jQuery(this).removeClass("sel-answered");
                }
            );

        jQuery(".answer.big").hover(
            function () {
                jQuery(this).addClass("sel-big-answered");
                },
            function () {
                jQuery(this).removeClass("sel-big-answered");
                }
            );

        var aValues = [];
        $inputs = jQuery('#test-question input');
        $inputs.each(function()
        {
            if (this.checked)
            {
                aValues.push(this.value);
            }
        });

        if (!jQuery('#show-answer').val())
        {
            jQuery('input[name=show_answer]')
                .attr('disabled', false)
                .attr('src',      Exam.sBaseUrl + 'images/new/btn_show-answer.gif');
        }

        jQuery('input[name=show_answer]').click(function()
        {
            if (this.disabled)
            {
                return false;
            }

            jQuery('#test-question').show();
            jQuery('#all-test-notes').hide();
            jQuery('ul.tabs li.ico-my-notes').removeClass('cur');
            jQuery('ul.tabs li.ico-my-test').addClass('cur');

            this.disabled = true;
            this.src = Exam.sBaseUrl + 'images/new/btn_show-answer_dsbl.gif';

            Exam.showAnswer();

            jQuery.get(Exam.sBaseUrl + 'test/ajax_showanswer.php', {q: jQuery('#question-id').val()});

            return false;
        });

        jQuery('div.answer').click(function()
        {
            
            var thisInput = jQuery(this).find('input')[0];
            thisInput.checked = 1;
            var sOption = thisInput.value;

            if ('checkbox' == thisInput.type)
            {
                var aOption = [];
                jQuery('#test-question input').each(function()
                {
                    if (this.checked)
                    {
                        aOption.push(this.value);
                    }
                });

                sOption = aOption.join(',');

                $answer = $('#test-question div.answer' + thisInput.value);
                var sClass = 'answered';
                if ($answer.hasClass('big'))
                {
                    sClass = 'big-answered';
                }

                $span = $answer.find('td.last span');
                if (thisInput.checked)
                {
                    $answer.addClass(sClass);
                    $span.addClass('display');
                }
                else
                {
                    $answer.removeClass(sClass);
                    $span.removeClass('display');
                }
            } else {
                
                $answer = $('#test-question div.answer' + thisInput.value);

                var sClass = 'answered';
                if ($answer.hasClass('big'))
                {
                    sClass = 'big-answered';
                }

                $('#test-question div.answer').removeClass(sClass);
                $('#test-question div.answer td.last span').removeClass('display');

                if (thisInput.checked)
                {
                    $answer.addClass(sClass);
                    $answer.find('td.last span').addClass('display');
                }
            }

            if (sOption)
            {
                jQuery('#navigation li.question' + Exam.iCurrentQuestion).addClass('dark');
            }
            else
            {
                jQuery('#navigation li.question' + Exam.iCurrentQuestion).removeClass('dark');
            }

            Exam.refreshProgress();

            jQuery.get(Exam.sBaseUrl + 'insert_question.php', {
                question: jQuery('#question-id').val(), 
                option: sOption,
                getm: Exam.iMinutes, 
                gets: Exam.iSeconds
                });
        });

        jQuery('#popup_note input.note_question_id_current').attr('value', jQuery('#question-id').val());

        jQuery("#test-question div.btn-have-note div").click(function() 
        {
            jQuery(this).parent().children('table.yell-popup').fadeIn(200);
        });

        jQuery("#test-question div.btn-have-note .yell-popup .bg span").click(function() 
        {
            jQuery(".btn-have-note").children('table.yell-popup').fadeOut(200);
        });

        jQuery('#edit-existent-note').click(function()
        {
            Exam.editNote(true);
        });

        jQuery('#delete-note').click(function()
        {
            Exam.deleteNote();
        });

        jQuery('#test-question div.btn-calculator').toggle(
            function()
            {
                jQuery('#calculator-container').calculator();
            }, 
            function()
            {
                jQuery('#calculator-container').calculator('destroy');
            });

        Exam.refreshNotes();

        jQuery('#test-question div.right-col-test').find('a.zoom, a.move').click(function()
        {
            var sSrc = jQuery('#test-question div.pic-test-' + jQuery(this).attr('rel') + ' img').attr('src');

            jQuery('#popup-pic img').attr('src', sSrc);

            jQuery('#popup-pic').togglePopup();

            return false;
        });
    }, 

    showAnswer: function()
    {
        jQuery('#test-question div.explan-inactive').removeClass('explan-inactive');

        var aCorrect = [];
        if (jQuery('#correct-answers').val())
        {
            aCorrect = jQuery('#correct-answers').val().split(',');
        }

        jQuery('#test-question div.answer').each(function()
        {
            if (-1 != jQuery.inArray($(this).find('input').val(), aCorrect))
            {
                if (jQuery(this).hasClass('big'))
                {
                    jQuery(this).addClass('big-right');
                }
                else
                {
                    jQuery(this).addClass('right');
                }
                

                if (jQuery(this).hasClass('answered') || jQuery(this).hasClass('big-answered'))
                {
                    jQuery(this).find('table td.last span').addClass('display');
                }
            }
            else if (jQuery(this).hasClass('answered') || jQuery(this).hasClass('big-answered'))
            {
                if (jQuery(this).hasClass('big'))
                {
                    jQuery(this).removeClass('big-answered').addClass('big-wrong');
                }
                else
                {
                    jQuery(this).removeClass('answered').addClass('wrong');
                }
            }
        });

        jQuery('#test-question input[type=radio]').attr('disabled', true);
    }, 

    initTimer: function(bIncrease)
    {
        var sMinutes = Exam.iMinutes;
        if (Exam.iMinutes < 10)
        {
            sMinutes = '0' + Exam.iMinutes;
        }
        jQuery('#time-minutes').text(sMinutes);

        var sSeconds = Exam.iSeconds;
        if (Exam.iSeconds < 10)
        {
            sSeconds = '0' + Exam.iSeconds;
        }
        jQuery('#time-seconds').text(sSeconds);

        setTimeout(function()
        {
            if (0 == Exam.iMinutes && 0 == Exam.iSeconds)
            {
                jQuery('input').attr('disabled', true);
                Exam.submitResults();
            }
            else
            {
                if (!Exam.bStopTimer)
                {
                    if (bIncrease)
                    {
                        if (0 == Exam.iSeconds % 10)
                        {
                            jQuery.get(Exam.sBaseUrl + 'test/ajax_tracktime.php', {
                                getm: Exam.iMinutes, 
                                gets: Exam.iSeconds
                                });
                        }
    
                        if (59 <= Exam.iSeconds)
                        {
                            Exam.iMinutes++;
                            Exam.iSeconds = 0;
                        }
                        else
                        {
                            Exam.iSeconds++;
                        }
                    }
                    else
                    {
                        if (0 == Exam.iSeconds % 10)
                        {
                            jQuery.get(Exam.sBaseUrl + 'test/ajax_tracktime.php', {
                                getm: Exam.iMinutes, 
                                gets: Exam.iSeconds
                                });
                        }
    
                        if (0 == Exam.iSeconds)
                        {
                            Exam.iMinutes--;
                            Exam.iSeconds = 59;
                        }
                        else
                        {
                            Exam.iSeconds--;
                        }
                    }
                }

                Exam.initTimer(bIncrease);
            }
        }, 1000);
    }, 

    submitResults: function()
    {
        jQuery.get(Exam.sBaseUrl + 'test_statistics.php', {}, function(sResponse)
        {
            jQuery('#popup_stats').append(sResponse).togglePopup();
            jQuery('#popup').find('#statistics').show();
            jQuery('#popup').find('input[name=stats_close]').click(function()
            {
                window.opener.location.href = Exam.sBaseUrl + 'compose_test';
                window.close();
            });
        });
    }, 

    refreshProgress: function()
    {
        jQuery('div.line').css('width', Math.round(jQuery('#navigation li.dark').length * 145 / jQuery('#navigation li').length) + 'px');
    }, 

    setDomainId: function(iDomainId)
    {
        var iCurrentDomainId = Exam.aQuestion2DomainId[Exam.iCurrentQuestion] || 0;
        Exam.iDomainId       = iDomainId;

        if (iCurrentDomainId != iDomainId)
        {
            jQuery('input[name=next]').trigger('click');
        }
    }, 

    refreshNotes: function()
    {
        var iCount = jQuery('#navigation li.corner').length;
        jQuery('#notes-count').html(iCount + Exam.iUnassignedNotes);

        if (iCount)
        {
            jQuery('#notes-count-p').show();
        }
        else
        {
            jQuery('#notes-count-p').hide();
        }
    }, 

    editNote: function(bEdit, iNoteId, sNote)
    {
        var iNoteId = iNoteId || 0;
        jQuery('#popup_note').togglePopup();

        if (bEdit)
        {
            sNote = sNote || jQuery('table.yell-popup p.note-content').text();

            jQuery('#popup textarea').val(sNote);
            jQuery('#popup p').hide();
        }

        jQuery('#popup input[name=save-note]').click(function()
        {
            var sNote           = jQuery.trim(jQuery('#popup textarea').val());
            var iNoteQuestionId = jQuery('#popup input[name=note_question_id]:checked').val();

            if (0 == sNote.length)
            {
                jQuery('#popup div.note-error').show();
                return false;
            }

            if (iNoteQuestionId)
            {
                jQuery('#navigation li.question' + Exam.iCurrentQuestion).addClass('corner');
            }
            else 
            {
                Exam.iUnassignedNotes++;
            }

            Exam.realGotoQuestion(Exam.iCurrentQuestion, {
                note             : sNote, 
                note_question_id : iNoteQuestionId, 
                note_id          : iNoteId
                });

            Exam.loadAllNotes();

            jQuery('#popup_note').togglePopup();
            return false;
        });
    }, 

    deleteNote: function()
    {
        jQuery('#navigation li.question' + Exam.iCurrentQuestion).removeClass('corner');
        jQuery('div.btn-have-note').hide().remove();

        jQuery.get(Exam.sBaseUrl + 'enter_note.php', {
            delete_note_id: jQuery('#question-id').val()
            });

        Exam.refreshNotes();
        Exam.loadAllNotes();
    }, 

    loadAllNotes: function()
    {
        jQuery.get(Exam.sBaseUrl + 'display_single_note.php', {}, 
            function(sResponse) 
            {
                jQuery('#all-test-notes').html(sResponse);

                jQuery('#all-test-notes a.edit-existent-note').click(function()
                {
                    Exam.editNote(
                        true, 
                        jQuery(this).attr('rel').split(':')[0], 
                        jQuery('#all-test-notes div.note-' + jQuery(this).attr('rel').split(':')[0] + ' p.note-content').text()
                        );

                    return false;
                });

                jQuery('#all-test-notes a.delete-note').click(function()
                {
                    var iQuestionId = jQuery(this).attr('rel').split(':')[1];
                    jQuery('#navigation li.question' + iQuestionId).removeClass('corner');

                    if (jQuery('#question-id').val() == iQuestionId)
                    {
                        jQuery('div.btn-have-note').hide().remove();
                    }

                    jQuery.get(Exam.sBaseUrl + 'enter_note.php', {
                        note_id: jQuery(this).attr('rel').split(':')[0]
                        }, 
                        function()
                        {
                            if (!iQuestionId)
                            {
                                Exam.iUnassignedNotes--;
                            }

                            Exam.refreshNotes();
                            Exam.loadAllNotes();
                        });

                    return false;
                });
            });
    }, 

    initStopTimer: function()
    {
        jQuery('div.progress-bar div.bg a').click(function()
        {
            Exam.bStopTimer = !Exam.bStopTimer;

            return false;
        });
    }, 

    initReportError: function()
    {
        jQuery('#error-report-button').click(function()
        {
            jQuery('#error-report').togglePopup();

            jQuery('#popup input[name=error-report-submit]').click(function()
            {
                var sMessage = jQuery('#popup textarea').val();

                jQuery('#popup div.error-report-error, #popup div.error-report-success').hide();

                if (0 == sMessage.length)
                {
                    jQuery('#popup div.error-report-error').show();
                }
                else
                {
                    jQuery.post(Exam.sBaseUrl + 'error_report.php', {
                        error_text  : sMessage 
                        }, 
                        function()
                        {
                            jQuery('#popup div.error-report-success').show();
                            jQuery('#popup textarea').val('');
                        });
                }

                return false;
            });

            return false;
        });

        jQuery('#help').click(function()
        {
            jQuery.get(Exam.sBaseUrl + 'help.php', {}, function(sResponse)
            {
                jQuery('#help-content').html(sResponse);
                jQuery('#help-content').togglePopup();
                jQuery('#popup input[name=help-close]').click(function()
                {
                    jQuery('#help-content').togglePopup();
                });

                jQuery('#help-search').submit(function()
                {
                    jQuery.get(
                        Exam.sBaseUrl + 'help.php', 
                        {search: jQuery('#popup input[name=search-text]').val()}, 
                        Exam.initHelpContent);

                    return false;
                });
            });

            return false;
        });
    }, 
    
    initHelpContent: function(sResponse)
    {
        jQuery('#popup').html(sResponse);

        jQuery('#popup input[name=help-close]').click(function()
        {
            jQuery('#help-content').togglePopup();
        });

        jQuery('#help-search').submit(function()
        {
            jQuery.get(
                Exam.sBaseUrl + 'help.php', 
                {search: jQuery('#popup input[name=search-text]').val()}, 
                Exam.initHelpContent);

            return false;
        });
    }
}

