$(document).ready(function(){
    $('div.advFlsh').flash(null, { version: 8 }, function(htmlOptions) {
        var $this = $(this);
        var params = $this.attr('rel').split(':');
        htmlOptions.src = RootHTTP+"image/adv/adv_"+params[0]+".swf";
        htmlOptions.width = params[1];
        htmlOptions.height = params[2];
        $this.addClass('flash-replaced').prepend($.fn.flash.transform(htmlOptions));
    });
});

text_exceeds_symbol_limit= ['','Допустимый объем превышен на %s знак.','Допустимый объем превышен на %s знака.','Допустимый объем превышен на %s знаков.'];
text_N_symbols_remain= ['','Остался %s знак.','Осталось %s знака.','Осталось %s знаков.'];


function isArray(obj) { 
	return Object.prototype.toString.call(obj) === "[object Array]"; 
}
function langNumeric(count, variants) {
 if (!variants) {
  return count;
 }
 var result;
 if (isArray(variants)) {
  result = slavicNumbers(count, variants);
 } else {
   result = variants;
 }

 result = (result || '%s').replace('%s', count);
 return result;
}


function slavicNumbers(count, variants) {
 try { count = parseFloat(count); } catch(e) { return variants[3] || variants[1]; }
 if (count != Math.round(count)) {
   return variants[2] || variants[1];
 }
 count %= 100;
 if (count > 4 && count < 21) {
  return variants[3] || variants[1];
 }
 count %= 10;
 switch (count) {
  case 1: return variants[1]; break;
  case 2:
  case 3:
  case 4: return variants[2] || variants[1]; break;
  default: return variants[3] || variants[1];
 }
}


utils = {
	lastLength:0,
	checkTextLength:function(max_len, val, boxId){
		if(this.lastLength==val.length)return;
		this.lastLength=val.length;
		n_len = this.replaceChars(val).length;
		if (n_len > max_len) {
			var n_plus = n_len - max_len;
			document.getElementById(boxId).style.display = "";
			document.getElementById(boxId).innerHTML = langNumeric(n_plus, text_exceeds_symbol_limit);
		} else if (n_len > max_len - 100) {
			var n_rem = max_len - n_len;
			document.getElementById(boxId).style.display = "";
			document.getElementById(boxId).innerHTML = langNumeric(n_rem, text_N_symbols_remain);
		} else {
			document.getElementById(boxId).style.display = "none";
			document.getElementById(boxId).innerHTML = '';
		}
	},
	replaceChars:function(text){
		var res = "";
		temp = "";
		for(var i =0; i<text.length; i++){
			var c = text.charCodeAt(i);
			temp+=c+",";
			switch(c){
				default:res+=text.charAt(i);break;
			}
		}
		return res;
	}
}


function feedback(){
	formFB = '<h1>Форма обратной связи!</h1><table width="100%" cellspacing="10"><tr><td width="60%"><input type="text" name="name" id="name" style="width:100%;" /></td><td>* Ваше имя</td></tr><tr><td><input type="text" name="email" id="email" style="width:100%;" /></td><td>* Ваш e-mail</td></tr><tr><td><textarea name="text" id="text" style="width:100%;" rows="5" onkeyup="utils.checkTextLength(1000, this.value, \'error_text_inFeedBack\')"></textarea></td><td valign="top">* Ваше сообщение<br>(максимум 1000 знаков)</td></tr><tr><td colspan="2"><div id="error_text_inFeedBack" style="color:#666666;margin:5px 0px;display:none"></div></td></tr></table>';
	feedbackHTML = {
		stateFB0: {
			html: formFB,
			focus: 1,
			buttons: { 'Закрыть': false, 'Отправить': true },
			submit: function(v, m, f){
				e='';
				if(!v){
					return true;
				}else{
					
					if(f.name.length == 0)
					e += "Пожалуйста, введите Ваше имя.\n";
					if(f.email.length == 0)
					e += "Пожалуйста, введите контактные e-mail.\n";
					if(f.text.length == 0)
					e += "Пожалуйста, введите текст сообщения.\n";
					
					
					if (e == ""){
						$.prompt.close();
						par = {'act': 'feedback', 'name':f.name, 'email':f.email, 'text':f.text}
						$.ajax({
							url: RootHTTP+"adm.ajax.php",
							dataType: "text",
							type: 'POST',
							data: par,
							success: function(data) {
										//alert(data);
										json = eval("(" + data + ")");
										rAJ = (json.res == true) ? 'Сообщение отправленно администрации!':'Ошибка!'+json.mes;
										$.prompt(rAJ, {top:'30%'});
										setTimeout('$.prompt.close();', 4000);
									}
						});
					}else{
						alert(e);
					}
					return false;
				}
			}
		}
	};
				
	$.prompt(feedbackHTML, {top:'43%'});
}
function replace(search, replace, subject){
       var ra = replace instanceof Array,
               sa = subject instanceof Array,
               l = (search = [].concat(search)).length,
               replace = [].concat(replace),
               i = (subject = [].concat(subject)).length;
       while(j = 0, i--)
               while(subject[i] = subject[i].split(search[j]).join(ra ? replace[j] || "" : replace[0]), ++j < l);
       return sa ? subject : subject[0];
}

(function () {
    $.fn.infiniteCarousel = function () {
        function repeat(str, n) {
            return new Array( n + 1 ).join(str);
        }
        
        return this.each(function () {
            // magic!
            var $wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul').width(9999),
                $items = $slider.find('> li'),
                $single = $items.filter(':first')
                
                singleWidth = $single.outerWidth(),
                visible = Math.ceil($wrapper.innerWidth() / singleWidth),
                currentPage = 1,
                pages = Math.ceil($items.length / visible);
                
            /* TASKS */
            
            // 1. pad the pages with empty element if required
            if ($items.length % visible != 0) {
                // pad
                $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
                $items = $slider.find('> li');
            }
            
            // 2. create the carousel padding on left and right (cloned)
            $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
            $items = $slider.find('> li');
            
            // 3. reset scroll
            $wrapper.scrollLeft(singleWidth * visible);
			
            // 4. paging function
            function gotoPage(page) {
                var dir = page < currentPage ? -1 : 1,
                    n = Math.abs(currentPage - page),
                    left = singleWidth * dir * visible * n;
                
                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft : '+=' + left
                }, 500, function () {
                    // if page == last page - then reset position
                    if (page > pages) {
                        $wrapper.scrollLeft(singleWidth * visible);
                        page = 1;
                    } else if (page == 0) {
                        page = pages;
                        $wrapper.scrollLeft(singleWidth * visible * pages);
                    }
                    
                    currentPage = page;
                });
            }
            
           
            // 6. bind the back and forward links
            $('a.back', this).click(function () {
                gotoPage(currentPage - 1);
                return false;
            });
            
            $('a.forward', this).click(function () {
                gotoPage(currentPage + 1);
                return false;
            });
            
            $(this).bind('goto', function (event, page) {
                gotoPage(page);
            });
            
            // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
            $(this).bind('next', function () {
                gotoPage(currentPage + 1);
            });
        });
    };
})(jQuery);

function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};