/* user func */

$(function() {
   $(".sort").click(function(){
      doSortSelect ();
   });
function doSortSelect () { 
   var sortedVals = $.makeArray($('.hlist')).sort(function(a,b){ 
   var aa = $(a).find(".ratingcount").text();
   var bb = $(b).find(".ratingcount").text();
   return aa < bb ? 1 : aa < bb ? -1 : 0;
});

$('#content').empty().html(sortedVals); 
}
});




$(function() {
    $("head").contents().filter(function() {
        return this.nodeType == 8;
    }).each(function(i, e) {
        a = (e.nodeValue);
		if ((i==0) && (a!='  ')) {
        $('div.tabs div > a[href *= '+a+']').css("color", "#075e9e");
		}
    });
});




$(function(){
//	$('.txpCommentInputMessage').autogrow({
//		maxHeight: 200,
//		minHeight: 40,
//		lineHeight: 20
//	});

var comments_form			= '#comments-wrapper';
var comments_errors			= '#CommentsError';
var comments_parent			= 'div.allcomments'; // don't forget to set tags name (i.e. "div.class", but not only ".class")
var comments_subitem		= 'div.onecomment';  // don't forget to set tags name (i.e. "div.class", but not only ".class")
var comments_new_parent		= '<div class="allcomments"></div>';
var comments_new_subitem	= '<div class="onecomment"></div>';
var comment_posted			= ''; // if omitted default gTxt("comment_posted") would be shown
var comment_posted_wrap		= '<div class="postedOK"></div>'// container to show posted 'OK' message

	$('#txpCommentSubmit').click(function(){
		var $data = $(':input, :checkbox, :hidden', comments_form).serialize();
		var $form = $(comments_form); // obj containing form
		var $errors = $(comments_errors);  // obj for errors
		var $overlay;
		var $wait;

		$.ajax({
			url: '/ajax',
			type: 'post',
			dataType: 'json',
			data: $data,
			beforeSend: function(){
				$errors.text('').hide();
				$overlay = $('<div id="AjaxOverlay"></div>').css('opacity', '.5').appendTo(comments_form);
				$wait = $('<div id="AjaxWait"></div>').appendTo(comments_form);
				$loader = $('<div id="AjaxLoader"></div>').appendTo($wait);
			},
			success: function($ret, $status){
				$overlay.remove();
				$wait.remove();

				if(!$ret.errors) {
					if($ret.status == 'OK'){
						if($(comments_parent +" "+comments_subitem).length == 0) { // check for length - use plus if subitem hasn't uniq attr
							//$('<div id="Comments"><ul class="comments"></ul></div>').insertBefore($form);
							$(comments_new_parent).insertBefore($form);
						}
						//var $preview = $('<li></li>').appendTo('#Comments ul').hide();
						var $preview = $(comments_new_subitem).appendTo(comments_parent).hide(); // insert parsed html of comment into single comment container
						//console.log($preview);
						//$preview.html($ret.html).show('slide', {direction: 'down'}, 1000);
						//$form.hide('slide', {direction: 'down'}, 1000);
						//console.log(newHtml);
						$preview.addClass("last_added").html($ret.html).slideDown();
						$form.slideUp();
						
						// add thank-message - if comment_posted mesasge is redefined - use it, else use gTxt("comment_posted") provided from ajax
						$(comment_posted_wrap).html( (comment_posted ? comment_posted : $ret.comment_posted) ).insertBefore($form).fadeIn();
					}
				} else {

					$.each($ret.error_msg, function(i, el){
						$('<p></p>').text(el).appendTo($errors);
					});
					$errors.fadeIn();

					if($ret.errors.name) {
						$('#name', $form).addClass('error');
					}
					if($ret.errors.email) {
						$('#email', $form).addClass('error');
					}
					if($ret.errors.message) {
						$('#message', $form).addClass('error');
					}
				}
			}
		});
		return false;
	});
});





img1 = new Image(128, 15);
img1.src="/pic/ajax.gif";

$(function() {


    $("#login > form").submit(function() {

        $('#login form').css("display", "none");
        $('<img id="ajaxloader" src="/pic/ajax.gif" alt="" width="128" height="15" />').replaceAll("#login > p");

        var str = $(this).serialize();

        // -- Start AJAX Call --
        $.ajax({
            type: "POST",
            url: '/extmsg/do-login.php',
            data: str,
            success: function(msg) {
                $('#ajaxloader').hide();
                if (msg == 'login') {
                    $('<span>Авторизация произведена</span>').replaceAll("#login > img");
                    setTimeout('reload_page()', 1000);
                } 
				else if (msg == 'reg') {
                    $('<span>Регистрация произведена</span>').replaceAll("#login > img");
                    setTimeout('reload_page()', 1000);
                }
				else if (msg == 'mail') {				
                    $('<p style="color: red;" id="error">Ошибка! <b>E-mail некорректен</b>, находится в бан-листе, уже используется или запрещен к регистрации. Воспользуйтесь этой <a href="http://forum.goodmagic.ru/ucp.php?mode=login">ссылкой</a>.</p>').replaceAll("#login > img");
                    $('#login form').css("display", "block");
                }
				else if (msg == 'pass') {				
                    $('<p style="color: red;" id="error">Ошибка! <b>Пароль некорректен</b> или содержит недопустимые символы. Воспользуйтесь этой <a href="http://forum.goodmagic.ru/ucp.php?mode=login">ссылкой</a>.</p>').replaceAll("#login > img");
                    $('#login form').css("display", "block");
                }
				else if (msg == 'user') {				
                    $('<p style="color: red;" id="error">Ошибка! <b>Имя пользователя некорректно</b>, находится в бан-листе, уже используется или запрещено к регистрации. Воспользуйтесь этой <a href="http://forum.goodmagic.ru/ucp.php?mode=login">ссылкой</a>.</p>').replaceAll("#login > img");
                    $('#login form').css("display", "block");
                }
				else {
                    $('<p style="color: red;" id="error">Ошибка! Попробуйте еще раз или воспользуйтесь этой <a href="http://forum.goodmagic.ru/ucp.php?mode=login">ссылкой</a>.</p>').replaceAll("#login > img");
                    $('#login form').css("display", "block");
                }
            },
			error: function() {
$('<p style="color: red;" id="error">Ошибка! Попробуйте еще раз или воспользуйтесь этой <a href="http://forum.goodmagic.ru/ucp.php?mode=login">ссылкой</a>.</p>').replaceAll("#login > img");
                    $('#login form').css("display", "block");	
			}
        });

        return false;

    });
});


function reload_page()
{
location.reload();
};


$(function() {
	$("a[href='#enter']").click(function() {
		 $("#login").slideDown();
		 $('input[name=name]').focus();
		 return false;
		 }
	),
$("#close").click(function() {
		 $("#regmail").css('display', 'none');
		 $("#login").slideUp();
 		 $('<input id="btn" value="" src="/pic/enter.png" type="image">').replaceAll("#btn").css('display', 'block');
		 $("#reg").attr("src", "/pic/register.png").css('display', 'block');
		 $('<p>* Если вы забыли пароль или возникли другие проблемы с авторизацией или регистрацией, воспользуйтесь этой <noindex><a href="http://forum.goodmagic.ru/ucp.php?mode=login" rel="nofollow">ссылкой</a></noindex>.</p>').replaceAll("#login p");
		 $('input[name=mail]').val('');
		 });
});


$(function() {
    $("#reg").click(function() {
		 $("#regmail").css('display', 'block');
		 $('<input id="btn" value="" src="/pic/reg.png" type="image">').replaceAll("#btn");
		 $("#reg").css('display', 'none');		 
		 $('input[name=mail]').focus();
		 $('<p>* Если вы забыли пароль или возникли другие проблемы с авторизацией или регистрацией, воспользуйтесь этой <noindex><a href="http://forum.goodmagic.ru/ucp.php?mode=login" rel="nofollow">ссылкой</a></noindex>.</p>').replaceAll("#error");		 
		 });
});




$(function() {
	$('.add').click(function() {
        $('#sign_up').lightbox_me({
		centered: true, lightboxSpeed: 900,
		onLoad: function() { 
		$('#sign_up').load('/extmsg/addfokus.html');		
		},
		onClose: function() { 
		$('#sign_up').empty();		
		}});
		return false;
            });
        });
$(function() {
	$('.logout').click(function() {
        $('#sign_up').lightbox_me({
		centered: true, lightboxSpeed: 900, metimeout: 6000,
		onLoad: function() { 
		$('#sign_up').load('/extmsg/logout.php');
		},
		onClose: function() { 
		$('#sign_up').empty(); $('#frame').remove();
		}});
		return false;
            });
        });





$(document).ready(function() {
    var timer;
    $("#frame").hover(
        function() {
            $("#userinfo").slideDown();
            if (timer) {
                clearTimeout(timer);
            }
        }, function() {
            timer = setTimeout(function() {
                $("#userinfo").slideUp();
            }, 5000);
        }
    );
});



$(function () {
    var tabContainers = $('div.tabs > div'); // ïîëó÷àåì ìàññèâ êîíòåéíåðîâ
	var saved_tab = parseInt($.cookie('saved_tab')) || 0;     
    tabContainers.hide().filter(':eq('+saved_tab+')').show(); // ïðÿ÷åì âñå, êðîìå ïåðâîãî
    // äàëåå îáðàáàòûâàåòñÿ êëèê ïî âêëàäêå
    $('div.tabshead a').click(function () {
		var index = $('div.tabshead a').index(this);
		$.cookie('saved_tab', index, { path: '/'} );
		tabContainers.hide(); // ïðÿ÷åì âñå òàáû
        tabContainers.filter(':eq('+index+')').fadeIn('slow'); // ïîêàçûâàåì ñîäåðæèìîå òåêóùåãî
        $('div.tabshead a').removeClass('selected'); // ó âñåõ óáèðàåì êëàññ 'selected'
        $(this).addClass('selected'); // òåêóøåé âêëàäêå äîáàâëÿåì êëàññ 'selected'
        return false;
    }).filter(':eq('+saved_tab+')').click();
});


$(function () {

$(".bestfbox").each(function(){
  $(this).find("a").eq(0).css({'color' : '#fcbf00'});
  $(this).find("a").eq(1).css({'color' : '#60c17c'});
  $(this).find("a").eq(2).css({'color' : '#b5033f'});
})
});




(function($) {

    $.fn.lightbox_me = function(options) {

        return this.each(function() {

            var
                opts = $.extend({}, $.fn.lightbox_me.defaults, options),
                $overlay = $('div.' + opts.classPrefix + '_overlay'),
                $self = $(this),
                $iframe = $('iframe#lb_iframe'),
                ie6 = ($.browser.msie && $.browser.version < 7);
            
            if ($overlay.length > 0) {
                $overlay[0].removeModal(); // if the overlay exists, then a modal probably exists. Ditch it!
            } else {
                $overlay =  $('<div class="' + opts.classPrefix + '_overlay" style="display:none;"/>'); // otherwise just create an all new overlay. 
            }

            $iframe = ($iframe.length > 0) ? $iframe : $iframe = $('<iframe id="lb_iframe" style="z-index: ' + (opts.zIndex + 1) + '; display: none; border: none; margin: 0; padding: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0;"/>');

            /*----------------------------------------------------
               DOM Building
            ---------------------------------------------------- */
            if (ie6) {
                var src = /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank';
                $iframe.attr('src', src);
                $('body').append($iframe);
            } // iframe shim for ie6, to hide select elements
            $('body').append($self).append($overlay);

            /*----------------------------------------------------
               CSS stuffs
            ---------------------------------------------------- */

            // set css of the modal'd window

            setSelfPosition();
            $self.css({left: '50%', marginLeft: ($self.outerWidth() / 2) * -1,  zIndex: (opts.zIndex + 3) });

            // set css of the overlay

            setOverlayHeight(); // pulled this into a function because it is called on window resize.
            $overlay.css({ position: 'absolute', width: '100%', top: 0, left: 0, right: 0, bottom: 0, zIndex: (opts.zIndex + 2) })
                    .css(opts.overlayCSS);

            /*----------------------------------------------------
               Animate it in.
            ---------------------------------------------------- */

            if ($overlay.is(":hidden")) {
                $overlay.fadeIn(opts.overlaySpeed, function() {
                    $self[opts.appearEffect](opts.lightboxSpeed, function() { setOverlayHeight(); opts.onLoad()});
                });
            } else {
                $self[opts.appearEffect](opts.lightboxSpeed, function() { setOverlayHeight(); opts.onLoad()});
            }

            /*----------------------------------------------------
               Bind Events
            ---------------------------------------------------- */

            $(window).resize(setOverlayHeight)
                     .resize(setSelfPosition)
                     .scroll(setSelfPosition)
                     .keydown(observeEscapePress);
            $self.find(opts.closeSelector).click(function() { removeModal(true); return false; });
            $overlay.click(function() { if(opts.closeClick){ removeModal(true); return false;} });

            $self.bind('close', function() { removeModal(true) });
            $self.bind('resize', setSelfPosition);
            $overlay[0].removeModal = removeModal;
			
			if (opts.metimeout) {
			setTimeout(function() {removeModal(true);} ,opts.metimeout);
			};
			
			

            /*----------------------------------------------------------------------------------------------------------------------------------------
              ---------------------------------------------------------------------------------------------------------------------------------------- */

            /*----------------------------------------------------
               Private Functions
            ---------------------------------------------------- */

            function removeModal(removeO) {
                // fades & removes modal, then unbinds events
                $self[opts.disappearEffect](opts.lightboxDisappearSpeed, function() {
                    if (removeO) {
                      removeOverlay(); 
                    } 
                    
                    opts.destroyOnClose ? $self.remove() : $self.hide()
                    
                    
                    $self.find(opts.closeSelector).unbind('click');
                    $self.unbind('close');
                    $self.unbind('resize');
                    $(window).unbind('scroll', setSelfPosition);
                    $(window).unbind('resize', setSelfPosition);
                    
                    
                });
            }
            
            
            function removeOverlay() {
                // fades & removes overlay, then unbinds events
                $overlay.fadeOut(opts.overlayDisappearSpeed, function() {
                    $(window).unbind('resize', setOverlayHeight);

                    $overlay.remove();
                    $overlay.unbind('click');
                    
                    
                    opts.onClose();

                })
            }
            


            /* Function to bind to the window to observe the escape key press */
            function observeEscapePress(e) {
                if((e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which==0)) && opts.closeEsc) removeModal(true);
            }

            /* Set the height of the overlay
                    : if the document height is taller than the window, then set the overlay height to the document height.
                    : otherwise, just set overlay height: 100%
            */
            function setOverlayHeight() {
                if ($(window).height() < $(document).height()) {
                    $overlay.css({height: $(document).height() + 'px'});
                } else {
                    $overlay.css({height: '100%'});
                    if (ie6) {$('html,body').css('height','100%'); } // ie6 hack for height: 100%; TODO: handle this in IE7
                }
            }

            /* Set the position of the modal'd window ($self)
                    : if $self is taller than the window, then make it absolutely positioned
                    : otherwise fixed
            */
            function setSelfPosition() {
                var s = $self[0].style;

                if (($self.height() + 80  >= $(window).height()) && ($self.css('position') != 'absolute' || ie6)) {
                    var topOffset = $(document).scrollTop() + 40;
                    $self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})
                    if (ie6) {
                        s.removeExpression('top');
                    }
                } else if ($self.height()+ 80  < $(window).height()) {
                    if (ie6) {
                        s.position = 'absolute';
                        if (opts.centered) {
                            s.setExpression('top', '(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"')
                            s.marginTop = 0;
                        } else {
                            var top = (opts.modalCSS && opts.modalCSS.top) ? parseInt(opts.modalCSS.top) : 0;
                            s.setExpression('top', '((blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"')
                        }
                    } else {
                        if (opts.centered) {
                            $self.css({ position: 'fixed', top: '50%', marginTop: ($self.outerHeight() / 2) * -1})
                        } else {
                            $self.css({ position: 'fixed'}).css(opts.modalCSS);
                        }
                    }
                }
            }
        });
    };


    $.fn.lightbox_me.defaults = {
		
	metimeout: 0,

        // animation when appears
        appearEffect: "fadeIn",
        overlaySpeed: 300,
        lightboxSpeed: "fast",
        
        // animation when dissapears
        disappearEffect: "fadeOut",
        overlayDisappearSpeed: 300,
        lightboxDisappearSpeed: "fast",

        // close
        closeSelector: ".close",
        closeClick: true,
        closeEsc: true,

        // behavior
        destroyOnClose: false,

        // callbacks
        onLoad: function() {},
        onClose: function() {},

        // style
        classPrefix: 'lb',
        zIndex: 999,
        centered: false,
        modalCSS: {top: '40px'},
        overlayCSS: {background: 'black', opacity: .8}
    }


})(jQuery);


/* user func */
               
$(document).ready(function(){

$.easing.easeOutQuad = function (x, t, b, c, d) {return -c *(t/=d)*(t-2) + b;};

	$('.article_rating').jRating({
		step: true,
		rateMax: 5,
		length:	5
	});
$('#up').css('cursor', 'pointer').click(function(){
$.scrollTo( '.headwrap', 900, {easing:'easeOutQuad'} );
return false;
});
});


/*
@Name :       	jRating - jQuery Plugin
@Revison :    	2.0
*/

(function($) {
	$.fn.jRating = function(op) {
		var defaults = {
			/** String vars **/
			bigStarsPath : 'jquery/icons/stars.png', // path of the icon stars.png
			smallStarsPath : 'jquery/icons/small.png', // path of the icon small.png
			phpPath : '/rating', // path of the php file jRating.php
			type : 'big', // can be set to 'small' or 'big'
			
			/** Boolean vars **/
			step:false, // if true,  mouseover binded star by star,
			isDisabled:false,
			
			/** Integer vars **/
			length:5, // number of star to display
			decimalLength : 0, // number of decimals.. Max 3, but you can complete the function 'getNote'
			rateMax : 20, // maximal rate - integer from 0 to 9999 (or more)
			rateInfosX : -45, // relative position in X axis of the info box when mouseover
			rateInfosY : 35, // relative position in Y axis of the info box when mouseover
			
			/** Functions **/
			onSuccess : null,
			onError : null
		}; 
		
		if(this.length>0)
		return this.each(function() {
			var opts = $.extend(defaults, op),    
			newWidth = 0,
			starWidth = 0,
			starHeight = 0,
			bgPath = '';

			if($(this).hasClass('jDisabled') || opts.isDisabled)
				var jDisabled = true;
			else
				var jDisabled = false;

			getStarWidth();
			$(this).height(starHeight);

			var average = parseFloat($(this).attr('data').split('_')[0]),
			idBox = parseInt($(this).attr('data').split('_')[1]), // get the id of the box
			widthRatingContainer = starWidth*opts.length, // Width of the Container
			widthColor = average/opts.rateMax*widthRatingContainer, // Width of the color Container
			
			quotient = 
			$('<div>', 
			{
				'class' : 'jRatingColor',
				css:{
					width:widthColor
				}
			}).appendTo($(this)),
			
			average = 
			$('<div>', 
			{
				'class' : 'jRatingAverage',
				css:{
					width:0,
					top:- starHeight
				}
			}).appendTo($(this)),

			 jstar =
			$('<div>', 
			{
				'class' : 'jStar',
				css:{
					width:widthRatingContainer,
					height:starHeight,
					top:- (starHeight*2),
					background: 'url('+bgPath+') repeat-x'
				}
			}).appendTo($(this)),
			
			 result =
			$('<div>',
			{
				'class' : 'result',
				css:{
					float:'left',
					'margin-left':15
				}
			}).insertAfter($(this));



			$(this).css({width: widthRatingContainer,overflow:'hidden',zIndex:1,position:'relative',float:'left'});

			if(!jDisabled)
			$(this).bind({
				mouseenter : function(e){
					var realOffsetLeft = findRealLeft(this);
					var relativeX = e.pageX - realOffsetLeft;
					
					//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//					$(".result").html('Ваша оценка: ' + getNote(newWidth));
					
//					var tooltip = 
//					$('<p>',{
//						'class' : 'jRatingInfos',
//						html : getNote(relativeX)+' <span class="maxRate">/ '+opts.rateMax+'</span>',
//						css : {
//							top: (e.pageY + opts.rateInfosY),
//							left: (e.pageX + opts.rateInfosX)
//						}
//					}).appendTo('body').show();
				},
				mouseover : function(){
					$(this).css('cursor','pointer');	
				},
				mouseout : function(){
					$(this).css('cursor','default');
					average.width(0);
				},
				mousemove : function(e){
					var realOffsetLeft = findRealLeft(this);
					var relativeX = e.pageX - realOffsetLeft;
					if(opts.step) newWidth = Math.floor(relativeX/starWidth)*starWidth + starWidth;
					else newWidth = relativeX;
					average.width(newWidth);					
//					$("p.jRatingInfos")
//					.css({
//						left: (e.pageX + opts.rateInfosX)
//					})
//					.html('Оценка ' + getNote(newWidth) +' <span class="maxRate">из '+opts.rateMax+'</span>');
					
					//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
					$(".result").html('Ваша оценка: ' + getNote(newWidth));					
					
					
				},
				mouseleave : function(){
//					$("p.jRatingInfos").remove();
					$(".result").html('&nbsp;');
				},
				click : function(e){
					$(this).unbind().css('cursor','default').addClass('jDisabled');
					//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@					
					$(".result").fadeOut('fast',function(){$(this).html('&nbsp;');}).fadeIn();
					//,show(function(){$(this).html('&nbsp;');}));
//					$("p.jRatingInfos").fadeOut('fast',function(){$(this).remove();});
					e.preventDefault();
					var rate = getNote(newWidth);
					average.width(newWidth);
					
					/** ONLY FOR THE DEMO, YOU CAN REMOVE THIS CODE **/
						$('.datasSent p').html('<strong>idBox : </strong>'+idBox+'<br /><strong>rate : </strong>'+rate+'<br /><strong>action :</strong> rating');
						$('.serverResponse p').html('<strong>Loading...</strong>');
					/** END ONLY FOR THE DEMO **/
						
					$.post(opts.phpPath,{
							idBox : idBox,
							rate : rate,
							action : 'rating'
						},
						function(data) {
							if(!data.error)
							{
								/** ONLY FOR THE DEMO, YOU CAN REMOVE THIS CODE **/
									$('.result').html(data.message);
								/** END ONLY FOR THE DEMO **/
								
								
								/** Here you can display an alert box, 
									or use the jNotify Plugin :) http://www.myqjqueryplugins.com/jNotify
									exemple :	*/
								if(opts.onSuccess) opts.onSuccess();
							}
							else
							{
								
								/** ONLY FOR THE DEMO, YOU CAN REMOVE THIS CODE **/
									$('.result').html(data.message);
								/** END ONLY FOR THE DEMO **/
								
								/** Here you can display an alert box, 
									or use the jNotify Plugin :) http://www.myqjqueryplugins.com/jNotify
									exemple :	*/
								if(opts.onError) opts.onError();
							}
						},
						'json'
					);
				}
			});

			function getNote(relativeX) {
				var noteBrut = parseFloat((relativeX*100/widthRatingContainer)*opts.rateMax/100);
				switch(opts.decimalLength) {
					case 1 :
						var note = Math.round(noteBrut*10)/10;
						break;
					case 2 :
						var note = Math.round(noteBrut*100)/100;
						break;
					case 3 :
						var note = Math.round(noteBrut*1000)/1000;
						break;
					default :
						var note = Math.round(noteBrut*1)/1;
				}
				return note;
			};

			function getStarWidth(){
				switch(opts.type) {
					case 'small' :
						starWidth = 12; // width of the picture small.png
						starHeight = 10; // height of the picture small.png
						bgPath = opts.smallStarsPath;
					break;
					default :
						starWidth = 23; // width of the picture stars.png
						starHeight = 20; // height of the picture stars.png
						bgPath = opts.bigStarsPath;
				}
			};
			
			function findRealLeft(obj) {
			  if( !obj ) return 0;
			  return obj.offsetLeft + findRealLeft( obj.offsetParent );
			};
		});

	}
})(jQuery);

/* jquery.scrollTo-1.4.2-min.js */

;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/*jslint browser: true */ /*global jQuery: true */

jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

