/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(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);

// model page shops
function initModelShops () {
	// added 2010 06 25 start
	$('div.item-more-similar').each(function () {
		var _holder =  $(this);
		var _opener = $('div.l-more-similar a', _holder);
		var _slidePane = $('div.slider-pane', _holder);
		_slidePane.hide();
		_opener.live("click", function () {
			if (!$(this).parents('div.item-more-similar').hasClass('opened')) {
				$(this).parents('div.item-more-similar').find('div.slider-pane').slideDown(300, function () {
					$(this).parents('div.item-more-similar').addClass('opened');
				});
				$(this).text("Скрыть дополнительные предложения");
			} else {
				$(this).parents('div.item-more-similar').find('div.slider-pane').slideUp(300 ,function () {
					$(this).parents('div.item-more-similar').removeClass('opened');
				});
				$(this).text("Показать еще раз");
			}
			return false;
		});

	});
	// added 2010 06 25 end

	// 2010 08 03 start
	$('div.b-delivery-list').each(function () {
		var _deliveryOpener =  $('a.l-delivery-exp', $(this));
		var _deliveryPane = $('ul', $(this));
		if (_deliveryPane.length) {
			_deliveryPane.hide();
			_deliveryOpener.live("click", function () {
				if ($(this).parents('div.b-delivery-list').hasClass('opened')) {
					$(this).parents('div.b-delivery-list').removeClass('opened');
					$(this).parents('div.b-delivery-list').find('ul').slideUp(200);
				} else {
					$(this).parents('div.b-delivery-list').addClass('opened');
					$(this).parents('div.b-delivery-list').find('ul').slideDown(200);
				}
				return false;
			});
		}
	});
	// 2010 08 03 end

	$('div.phone-ads').each(function () {
		var _shops = $(this);
		$('div.link-shops-all a', _shops).each(function () {
			var _pricesId = $(this).attr('href');
			var _atab =  $('.tabset a');
			if (_pricesId && $(_pricesId).length && _atab.length) {
				// click 'all prices' link
				$(this).click(function () {
					_atab.each(function () {
						var _tabId = $(this).attr('href');
						if($(_tabId).length){
							if (_pricesId == _tabId) {
								$(_tabId).css({
									position:'static',
									left:0,
									top:0
								});
								$(this).addClass('active');
								$(window).scrollTo(_tabId, 600, {
									onAfter:function(){
										window.location.hash = _tabId;
									}
								});
							} else {
								$(_tabId).css({
									position:'absolute',
									left:'-7777px',
									top:'-7777px'
								});
								$(this).removeClass('active');
							}
						}
					});
					return false;
				});
			}
		});
	});
}

// star rating ajax tooltip
function initShopInfo(){
	var _shopTip = false;
	$('a.shop-inf').each(function(){
		var _url = $(this).attr('rel');
		var _load = $(this).attr('href');
		var _par = $(this).parent().parent();
		$(this).click(function(){
			if (_url && _load) {
				hideShopTips();
				var _tl = $('<div class="shop-inf-tltp"><div class="bg clearfix"><img src="' + _load + '" alt=""/></div></div>');
				_tl.css('opacity',.6);
				_par.append(_tl);
				$.ajax({
					url: _url,
					type: "POST",
					success: function(msg){
						_par.find('div.bg').html(msg);
						_tl.css('opacity',1);
						_shopTip = _tl;
					}
				});
			}
			return false;
		});
	});
	$('div.shop-inf-tltp a.x').live('click',function(){
		hideShopTips();
		return false;
	})
	function hideShopTips(){
		if(_shopTip) _shopTip.remove();
	}
	// hide tooltip by clickin' the document
	$(document).click(function(e){
		if($(e.target).parents('.shop-inf-tltp').length==0 && !$(e.target).hasClass('shop-inf-tltp')) {
			hideShopTips();
		}
	});
}

// tabs
function initTabs(){
	var _atab = $('.tabset a');
	// reset
	_atab.each(function(){
		if($(this).attr('href') == window.location.hash) {
			_atab.removeClass('active')
			$(this).addClass('active');
		}
	});

	function setTabs(){
		_atab.each(function(){
			var _tabId = $(this).attr('href');
			if($(_tabId).length){
				if($(this).hasClass('active')) $(_tabId).css({
					position:'static',
					left:0,
					top:0
				});
				else $(_tabId).css({
					position:'absolute',
					left:'-7777px',
					top:'-7777px'
				});
			}
		});
	}
	setTabs();
	_atab.click(function(){
		if($(this).hasClass('active')) return false;
		_atab.removeClass('active');
		$(this).addClass('active');
		setTabs();
		// 2010 06 23 start
		var _href = $(this).attr('href');
		$(window).scrollTo(_href, 600, {
			onAfter: function(){
				window.location.hash = _href;
			}
		});
		// 2010 06 23 end
		return false;
	});

	//Переход на игры
	_a = $('div.content div.pagination a');
	_a.live('click', function(){
		window.location='/playfon/pf_model_check_redir.php'+$(this).attr('rel');
		return false;
	});
}

// popups scrolling functionality
function initPopupScroll(){
	$('div.popup-win').each(function(){
		var _popup = $(this);
		function initPopupPos(){
			var _height = 0;
			if (window.innerHeight) {
				_height = window.innerHeight;
			} else {
				_height = document.documentElement.clientHeight;
			}
			var _thisHeight = _popup.outerHeight();
			var _page = $('body');
			if (_popup.length) {
				if (_height > _thisHeight) {
					if (!window.innerHeight) {
						_popup.css({
							position:'absolute',
							top: (document.documentElement.scrollTop + (_height - _thisHeight) / 2)+"px"
						});
					} else {
						_popup.css({
							position:'fixed',
							top: ((_height - _popup.outerHeight()) / 2)+"px"
						});
					}
				}
				else {
					_popup.css({
						position:'absolute',
						top: 0
					});
				}
			}
		}
		initPopupPos();
		$(window).scroll(function(){
			if(!_popup.is(':hidden')){
				initPopupPos();
			}
		}).resize(function(){
			if(!_popup.is(':hidden')){
				initPopupPos();
			}
		});
	});
}

// select model popup
function initModelSelector(_selector){
	$(_selector).each(function(xnumb){
		// vars
		var _ms = $(this);
		var _holder = $('div.model-selector:eq(0)',_ms);
		var _loading = $('div.loading:eq(0)',_ms);
		var _ajaxLink = $('div.heading a, div.selector a, div.sort a',_holder);
		var _allModels = $('div.model-popup-all a',_holder);
		var _ajaxCont = $('div.ajax-content:eq(0)',_holder);
		var _closeLink = $('a.close-link',_holder);
		var _par1 = false; // manufacturer
		var _par2 = false; // model
		var _phm = $('#phone-model');
		var _phmf = $('#phone-mf');
		var _aopener = $('a.model-sel-opener',_ms);
		if(_ajaxCont.length && _loading.length) {

			// ajax
			_ajaxLink.live('click',function(){
				if(!$(this).parents('ul.mod-li').length) {
					var _url = $(this).attr('href');
					var _hidden = $(this).attr('rel');
					if(_hidden) {
						_par1 = _hidden;
						_par2 = false;
					}
					if(_url && _url.indexOf('#')==-1) {
						_loading.show();
						_ajaxCont.css('opacity',0.3);
						$.ajax({
							url: _url,
							success: function(msg){
								_loading.hide();
								_closeLink.css('position','static');
								_ajaxCont.html(msg).css('opacity',1).show();
								_closeLink.css('position','absolute');
							}
						});
					}
					return false;
				}else{
					var _url = $(this).attr('href');
					if(_url && _url.indexOf('#')!=-1){
						var _hidden = $(this).attr('rel');
						if(_hidden && _phmf.length && _phm.length) {
							_par2 = _hidden;
							if(_par1 && _par2){
								_phmf.val(_par1);
								_aopener.eq(0).text(_par1);
								_phm.val(_par2);
								_aopener.eq(1).text(_par2);
							}else if(_par2){
								_phm.val(_par2);
								_aopener.eq(1).text(_par2);
							}
							_holder.fadeOut(250);
						}
						return false;
					}
				}
			});

            //show all or old models
			_allModels.live('click',function(){
				var _url = $(this).attr('href');
					_loading.show();
					_ajaxCont.css('opacity',0.3);
				$.ajax({
					url: _url,
					success: function(msg){
						_loading.hide();
						_closeLink.css('position','static');
						_ajaxCont.html(msg).css('opacity',1).show();
						_closeLink.css('position','absolute');
					}
				});
				return false;
			});

			// close
			_closeLink.click(function(){
				_holder.fadeOut(250);
				return false;
			});

			// open
			_aopener.click(function(){
				$('div.filter-show').css({
					position:'relative',
					zIndex:1
				}).find('div.model-selectr').hide();
				_loading.show();
				_ajaxCont.css('opacity',0.3);
				_ajaxCont.hide();
				var _url = $(this).attr('rel');
				if(_url && _url.indexOf('#')==-1) {
					$.ajax({
						url: _url,
						success: function(msg){
							_loading.hide();
							_closeLink.css('position','static');
							_ajaxCont.html(msg).css('opacity',1).show();
							_closeLink.css('position','absolute');
						}
					});
				}
				_holder.fadeIn(250,function(){
					_par1 = false;
					_par2 = false;
				});
				return false;
			});

			// hide popup by clickin' the document
			$(document).click(function(e){
				if($(e.target).parents('.model-selector').length==0) {
					_holder.fadeOut(200);
				}
			});
		}
	});
}

// select model popup
function initModelSrc(_selector){
	$(_selector).each(function(xnumb){
		// vars
		var _ms = $(this);
		var _holder = $('div.model-selectr:eq(0)',_ms);
		var _loading = $('div.loading:eq(0)',_ms);
		var _ajaxLink = $('div.headng a, div.selectr a, div.srt a',_holder);
		var _allModels = $('div.modl-popup-all a',_holder);
		var _ajaxCont = $('div.ajax-contnt:eq(0)',_holder);
		var _closeLink = $('a.close-link',_holder);
		var _par1 = false; // manufacturer
		var _par2 = false; // model
		var _phm = _ms.find('#phone-m');
		var _phmf = _ms.find('#phone-f');
		var _aopener = $('a.model-sel-opener',_ms);
		var _pageName = $('input#PageName').val();
		if(_ajaxCont.length && _loading.length){

			// ajax
			_ajaxLink.live('click',function(){
				if(!$(this).parents('ul.mod-li').length) {
					var _url = $(this).attr('href');
					var _hidden = $(this).attr('rel');
					if(_hidden) {
						_par1 = _hidden;
						_phmf.val(_par1);
						_aopener.eq(0).text(_par1);
						_par2 = false;
						_aopener.eq(1).text('Любой модели');
						_phm.val('');
					}
					if(_url) {
						_loading.show();
						_ajaxCont.css('opacity',0.3);
						$('div.filter-show').css({
							position:'relative',
							zIndex:1
						});
						$.ajax({
							url: _url,
							success: function(msg){
								_loading.hide();
								_closeLink.css('position','static');
								_ms.filter('.filter-show').css({
									position:'relative',
									zIndex:2
								});
								_ajaxCont.html(msg).css('opacity',1).show();
								_closeLink.css('position','absolute');
							}
						});
					}
					return false;
				}else{
					var _url = $(this).attr('href');
					if(_url){
						var _hidden = $(this).attr('rel');
						if(_hidden && _phmf.length && _phm.length) {
							_par2 = _hidden;
							if(_par2){
								_phm.val(_par2);
								if (_pageName == "games")
									window.location = "/playfon/pf_model_check.php?model="+_phmf.val()+"+"+_phm.val();
								_aopener.eq(1).text(_par2);
							}
							_holder.fadeOut(250);
						}
						return false;
					}
				}
				return false;
			});

            //show all or old models
			_allModels.live('click',function(){
				var _url = $(this).attr('href');
				_loading.show();
				_ajaxCont.css('opacity',0.3);
				$.ajax({
					url: _url,
					success: function(msg){
						_loading.hide();
						_closeLink.css('position','static');
						_ajaxCont.html(msg).css('opacity',1).show();
						_closeLink.css('position','absolute');
					}
				});
				return false;
			});

			// close
			_closeLink.click(function(){
				_holder.fadeOut(250);
				return false;
			});

			// open
			_aopener.click(function(){
				_loading.show();
				_ajaxCont.css('opacity',0.3);
				$('div.filter-show').css({
					position:'relative',
					zIndex:1
				});
				_ajaxCont.hide();
				var _url = $(this).attr('rel');
				if(_url && _url.indexOf('#')==-1) {
					$.ajax({
						url: _url,
						success: function(msg){
							_loading.hide();
							_closeLink.css('position','static');
							_ms.filter('.filter-show').css({
									position:'relative',
									zIndex:2
								});
							_ajaxCont.html(msg).css('opacity',1).show();
							_closeLink.css('position','absolute');
						}
					});
				}
				_holder.fadeIn(250,function(){
					_par1 = false;
					_par2 = false;
				});
				return false;
			});

			// hide popup by clickin' the document
			$(document).click(function(e){
				if($(e.target).parents('.model-selectr').length==0) {
					_holder.fadeOut(200,function(){
						_ms.filter('.filter-show').css({
							position:'relative',
							zIndex:1
						});
					});
				}
			});
		}
	});
}

// model description
function initDescription(){
	$('div.phone-descr span#more-link a').click(function(){
		$('div.phone-descr span#more-link').hide();
		$('div.phone-descr span#second-part').show('slow');
		return false;
	});
}

// model post comments
function initComments(){
	$('div.add-opinion div.add-link a').click(function(){
		if($(this).hasClass('opened')){
			$(this).removeClass('opened');
			$(this).parent().next('div.pic-uploader').hide();
		}else{
			$(this).addClass('opened');
			$(this).parent().next('div.pic-uploader').show();
		}
		return false;
	});
}

// answers
function initAnswers(){
	var _url = "/act/DoAnswers/?do=answers&parent=";
	var _urlpage = "/act/DoAnswers/?do=questions&model="+$("#ModelId").attr("value")+"&page=";
	var _urladd = "/act/DoAnswers/";
	var _answerstab = $('#answers');
	var _holder = $('#questions');
	var _loading = $('.loading', _answerstab);
	var _questionadd = $('#questionadd', _answerstab);

	_answerstab.find('.item').each(function(){
		$(this).removeClass('opened')
			.removeClass('answer-open');
	});

	function xpandAnswer(_obj,_classNam){
		if(_obj.parents('.item').hasClass(_classNam)) {
			_obj.parents('.item').removeClass(_classNam);
		}else{
			_obj.parents('.item').addClass(_classNam);
		}
	}

	$('a.opener').live("click", function(){
		xpandAnswer($(this),'opened');
		var _question = $(this).parents('.item');
		var id = _question.attr("id");
		var _answers = $('.all-answers',_question);
		var _loading = $('.loading',_question);
			_loading.show();
			_answers.hide();

			$.ajax({
			url: _url+id,
			cache: false,
			success: function(msg){
				_loading.hide();
				_answers.html(msg);
				_answers.slideDown("slow");
			}
		});
		return false;
	});
	_answerstab.find('a.hider').live("click", function(){
		var _question = $(this).parents('.item');
		var _answers = $('.all-answers',_question);
		_answers.hide(300);
		xpandAnswer($(this),'opened');
		return false;
	});

	_answerstab.find('div.expander a').live("click", function(){
		var _question = $(this).parents('.item');
		var _answers = $('.all-answers',_question);
		var _loading = $('.loading',_question);
		var id = _question.attr("id");

		if (_question.hasClass('opened')) {
			_answers.hide(300);
			_question.removeClass('opened');
		} else {
			_question.addClass('opened');
			_loading.show();
			_answers.hide();

			$.ajax({
			url: _url+id,
			cache: false,
			success: function(msg){
				_loading.hide();
				_answers.html(msg);
				_answers.slideDown("slow");
			}
		});
		}
		return false;
	});
	_answerstab.find('a.add-answer-link, a.answer-link').live("click", function(){
		xpandAnswer($(this),'answer-open');
        return false;
	});
	_answerstab.find('a.add-answer-link-top').live("click", function(){
		xpandAnswer($(this),'answer-open');
		var _href = $(this).attr('href');
		$(window).scrollTo(_href, 600, {
//			onAfter: function(){
//				window.location.hash = _href;
//			}
		});
        return false;
	});
	//pagination
	$('div#answers div.pagination a').live("click", function() {
			document.location.href="#answers";
			_holder.hide();
			_loading.show();
			$.ajax({
			url: _urlpage+$(this).attr("page"),
			cache: false,
			success: function(msg){
				_loading.hide();
				_holder.html(msg)
				_holder.show();
			}
		});
		return false;
	});
    //add question
	_questionadd.submit(function() {
      if ($('#questiontext', _questionadd).val() == "") {
        alert("Вы забыли задать вопрос!");
        return false;
      }
    });
    //add answer
	_answerstab.find('input.submit').live("click", function() {
		var _t = $(this).parents('.add-answer-box');
		var _item = $(this).parents('.item');
		var _url = "/act/DoAnswers/?do=answeradd&typ=js&parent="+$('input[name=parent]', _t).val()+"&text="+$('.text', _t).val();
      if ($('.text', _t).val() == "") {
      	alert("Вы забыли задать вопрос!");
        return false;
      }
      else {
		$.post("/act/DoAnswers/", {"do": "answeradd", typ: "js", parent: $('input[name=parent]', _t).val(), text: $('.text', _t).val() },
		  function(data){
		  	if ($('.all-answers', _item).html() == "") {
            	$('.all-answers', _item).html(data);
		  	}
		  	else {
			    $('.all-answers .answers:last', _item).after(data);
		    }
			    $('.text', _t).val("");
			    _item.removeClass('answer-open');
            	_item.addClass('opened');
		  });
      }
    return false;
    });
    //load edit form for question
	_answerstab.find('a[name=question-edit]').live("click", function(){
		var _ask = $(this).parents('.ask');
		$.get("/act/DoAnswers/?do=edit-form&typ=ask&id="+$(this).parents('.item').attr('id'), function(data){
  			$('.text', _ask).html(data);
		});
		return false;
	});
    //load edit form for answer
	_answerstab.find('a[name=answer-edit]').live("click", function(){
		_answer = $(this).parents('.answers');
		$.get("/act/DoAnswers/?do=edit-form&typ=answer&id="+_answer.attr('id'), function(data){
  			$('.text', _answer).html(data);
		});
		return false;
	});
    //edit
	_answerstab.find('input[name=edit]').live("click", function() {
 	 if ($(this).parents('.ask').find('input[name=typ]').val() == "ask")
			var _ask = $(this).parents('.ask');
     if ($(this).parents('.answers').find('input[name=typ]').val() == "answer")
      		var _ask = $(this).parents('.answers');
     if ($(this).parents('.quest').find('input[name=typ]').val() == "quest")
      		var _ask = $(this).parents('.quest');
     if ($(this).parents('.item').find('input[name=typ]').val() == "item")
      		var _ask = $(this).parents('.item');
      if ($('textarea[name=text]', _ask).val() == "") {
      	alert("Пустое поле!");
        return false;
      }
      else {
		$.post("/act/DoAnswers/", {"do": "edit", text: $('textarea[name=text]', _ask).val(), id: $('input[name=id]', _ask).val() },
		  function(data){
			$('.text', _ask).html(data);
		  });
      }

    return false;
    });
    //delete are you sure
	_answerstab.find('a[name=delete]').live("click", function(){
		return confirm("Вы уверены?");
	});

	//thanks
	$('a.give', _holder).live("click", function() {
		var _link = $(this);
		var _p = $(this).parents('.tnx').find('p.amount');
			$.ajax({
			url: $(this).attr("href")+'&j=1',
			cache: false,
			success: function(msg){
				_link.hide();
				_p.html(msg);
			}
		});
		return false;
	});
}
// reviews
function initReviews(){
	// vars
	var _holder = $('div#items');
	var _loading = $('div.loading',_holder);
	var _url = "/act/ReviewsDo/?do=show&model="+$("#ModelId").attr("value")+"&page=";
	$('div#opinions div.pagination a').live("click", function() {
			document.location.href="#opinions";
			_loading.show();
			$.ajax({
			url: _url+$(this).attr("page"),
			cache: false,
			success: function(msg){
				_loading.hide();
				_holder.html(msg).show();
			}
		});
		return false;
	});
	$('a.give', _holder).live("click", function() {
		var _link = $(this);
		var _p = $(this).parents('.tnx').find('p.amount');
			$.ajax({
			url: $(this).attr("href")+'&j=1',
			cache: false,
			success: function(msg){
				_link.hide();
				_p.html(msg);
			}
		});
		return false;
	});
	$('a.delete', _holder).live("click", function() {
		return confirm("Вы уверены?");
	});

}

// comments
function initMyAnswers(){
	$('div.my-comments').each(function(){
		var _holder = $(this);
		var _opener = $('div.my-answer',_holder);
		_opener.each(function(){
			$('div.pop',$(this)).hide();
		});
		$('div.my-answer a.ans', _holder).live("click", function(){
			if($(this).parent().hasClass('my-answer-open')) {
				$(this).parent().removeClass('my-answer-open').find('div.pop').fadeOut(200);
			}else{
				_opener.each(function(){
					$('div.pop',$(this)).hide();
					$(this).removeClass('my-answer-open');
				});
				$(this).parent().addClass('my-answer-open').find('div.pop').fadeIn(200);
			}
			return false;
		});
		$('div.my-answer a.del', _holder).live("click", function(){
			var _url = $(this).attr("href");
			var _item = $(this).parents(".item");

			if (confirm("Вы уверены?")) {
				$.ajax({
					url: _url+"&j=1",
					cache: false,
					success: function(msg){
						if (msg == "OK") {
							_item.hide("slow");
						}
					}
				})
			}
			return false;
		});
	});

	$('div.info').each(function(){
		var _holder = $(this);
		var _opener = $('div.btns',_holder);
		_opener.each(function(){
			$('div.pop',$(this)).hide();
		});
		$('> input.pmb',_opener).click(function(){
			$(this).hide();
			_opener.each(function(){
				$('div.pop',$(this)).hide();
				$('> input.pm',$(this)).show();
				$(this).removeClass('my-pm-open');
			});
			var _btns = $(this).parents(".btns");
			$("form:eq(0)", _btns).hide();
			$(this).parent().addClass('my-pm-open').find('div.pop').fadeIn(200);
			return false;
		});
	});
    //send comment for ad
	$('div.my-answer input.but').live("click", function() {
		var _item = $(this).parents("div.item");
		var _holder = $(this).parents("form");
		var _pop = $(this).parents(".pop");
		var _url = _holder.attr("action");
		var _parent = $("input[name=parent]", _holder).val();
		var _pre = $("input[name=pre]", _holder).val();
		var _text = $("textarea", _holder).val();
		var _id = $("input[name=ad_id]").val();
		if (_text == "") alert("Вы забыли написать сообщение!");
		else {
			_pop.hide();
			$("textarea", _holder).val("");
			$.ajax({
				type: "POST",
				url: _url,
				cache: false,
				data: "j=1&do=addcomment&parent="+_parent+"&pre="+_pre+"&text="+_text+"&id="+_id,
				success: function(msg){
					// post
					_item.after(msg);
					$(this).parents('.my-answer-open').removeClass('my-answer-open');
					$(this).parents('div.pop').fadeOut(200);
				}
			})
		}
		return false;
	})
    //send email for ad
	$('div.btns .pop input').live("click", function() {
		var _holder = $(this).parents("div.bg");
		var _text = $("textarea", _holder).val();
		var _id = $("input[name=ad_id]").val();
		var _url = "/act/DoAds/?do=sendemail";
		if (_text.length < 5) alert("Сообщение слишком короткое!");
		else {
			_holder.html("Отправка...");
			$.ajax({
				type: "POST",
				url: _url,
				cache: false,
				data: "j=1&id="+_id+"&text="+_text,
				success: function(msg){
					_holder.html(msg);
				}
			})
		}
		return false;
	})
}
// photo window
function initMyPhoto(){
	$('div.my-photo').each(function(){
		var _holder = $(this);
		var _img = $('div.my-img img',_holder);
		$('div.my-thumb a',_holder).click(function(){
			var _src = $(this).attr('href');
			if(_src && _src!='' && _src!='#') {
				_img.attr('src',_src);
			}
			return false;
		});
	});
}
// Search form
function initSearchForm(){
	$("div.side-select label.what2show a").click(function(){
		var _val = $(this).attr("rel");
		$("div.side-select input[name=all]").val(_val);

  		if (_val == 1) {
  			$("a[rel=1]").addClass("active");
  			$("a[rel=0]").removeClass("active");
  		}
  		if (_val == 0) {
  			$("a[rel=1]").removeClass("active");
  			$("a[rel=0]").addClass("active");
  		}
		return false;
	})
}

// games compatibility
function initGameComp(){
	$('div.game-compatible').each(function(){
		var _holder = $(this);
		var _slide = $('div.slide',_holder);
		var _opener = $('h3 a',_holder);
		_slide.hide();
		_opener.click(function(){
			var _url = $(this).attr('href');
			var _rel = $(this).attr('rel');
			$(this).attr('rel',$(this).text());
			$(this).text(_rel);
			if($(this).hasClass('opened')){
				$(this).removeClass('opened');
				_slide.hide();
			}else{
				$.ajax({
					type: "GET",
					url: _url,
					cache: false,
					success: function(msg){
						_slide.html(msg);
					}
				})
				$(this).addClass('opened');
				_slide.show();
			}
			return false;
		});
	});
}

// star rating
function initStars(){
	$('ul.stars').each(function(){
		var _rate = $(this);
		var _state = $(this).parent().find('.phone-condition');
		if(!_rate.hasClass('stars-disabled')){
			var _rateLi = _rate.find('li');
			var _rateA = _rate.find('a');
			_rate.hover(function(){
				_rateLi.each(function(_el){
					if($(this).hasClass('hover')) {
						_rate.attr('_hover',_el);
						$(this).removeClass('hover');
					}
					if($(this).hasClass('active')) {
						_rate.attr('_active',_el);
						$(this).removeClass('active');
					}
				});
			},function(){
				if($(this).attr('_hover') && !_rateLi.eq($(this).attr('_hover')).hasClass('hover') && !$(this).attr('_active')) {
					_rateLi.eq($(this).attr('_hover')).addClass('hover');
				}
				if($(this).attr('_active') && !_rateLi.eq($(this).attr('_active')).hasClass('active')) {
					_rateLi.eq($(this).attr('_active')).addClass('active');
				}
				return false;
			});
			_rateA.click(function(){
				_rate.attr('_active',_rateLi.index(this.parentNode));
				if(!_rateLi.eq(_rate.attr('_active')).hasClass('active')) _rateLi.eq(_rate.attr('_active')).addClass('active');
				if(_state.length) _state.text(_rateLi.eq(_rate.attr('_active')).find('a').attr('title'));
				var _rel = $(this).attr('rel');
				if(_rel) {
					// ajax star rating
					var _this = $(this);
					$.ajax({
						type:"POST",
						url:_rel,
						success:function(msg){
							_this.parent().parent().parent().prepend(msg);
							_this.parent().parent().remove();
							alert('Спасибо за Вашу оценку!')
						}
					});
				}else{
					// static star rating
					$('#star-rating').val(parseInt(_rate.attr('_active'))+1);
				}
				// star rating confirm function
				$(this).blur();
				return false;
			});
		}
	});
}

// phone prices tab
function initPrices(){
	// vars
	var _holder = $('div#phone_prices div.items');
	var _loading = $('div#phone_prices .loading');
	var _url = "/act/DoPrices/";

	$('div#phone_prices div.pagination a').live("click", function() {
		// scroll
		var _href = "#phone_prices";
		$(window).scrollTo(_href, 600, {
			onAfter: function(){
				window.location.hash = _href;
			}
		});
		// scroll end
			_loading.show();
			$.ajax({
			url: _url,
			data: "do=show&id="+$("#ModelId").attr("value")+"&sort="+$("#sortval").val()+"&avail="+$("#in_stock:checked").val()+"&waranty="+$("#warranty:checked").val()+"&page="+$(this).attr("page"),
			cache: false,
			success: function(msg){
				_loading.hide();
				_holder.html(msg);
			}
		});
		return false;
	});

	//Сортировочка
	$('div#phone_prices div.sortby a').live("click", function() {
		var _t = $(this).parents('div.sortby').find('a');
		_t.each(function () {
			$(this).removeClass('active');
		});
        if (!$(this).hasClass('active'))
        	$(this).addClass('active');
        else
        	$(this).removeClass('active');
        $('#sortval').val($(this).attr('rel'));

		_loading.show();
		$.ajax({
			url: _url,
			data: "do=show&id="+$("#ModelId").attr("value")+"&sort="+$("#sortval").val()+"&avail="+$("#in_stock:checked").val()+"&waranty="+$("#warranty:checked").val()+"&page="+$(this).attr("page"),
			cache: false,
			success: function(msg){
				_loading.hide();
				_holder.html(msg);
			}
		});
		return false;
	});

	//Чекбоксы
	$('div#phone_prices div.sort-chks input').change(function(e){
		_loading.show();
		$.ajax({
			url: _url,
			data: "do=show&id="+$("#ModelId").attr("value")+"&sort="+$("#sortval").val()+"&avail="+$("#in_stock:checked").val()+"&waranty="+$("#warranty:checked").val()+"&page="+$(this).attr("page"),
			cache: false,
			success: function(msg){
				_loading.hide();
				_holder.html(msg);
			}
		});
		return false;
	});
}

// 2010 08 05 start
function initCustomLocation () {
	$('div.b-select-region').each(function () {
		var _selectRegion = $(this);
		var _activeRowClass = 'active-row';
		var _row = $('div.row', _selectRegion);
		var _parentInp = $(' > input', _row);
		var _parentInpCustom = $(' > div', _row);
		var _childInp = $('ul li', _row);
		_childInp.click(function () {
			var _parent = $(this).parents('div.row');
			if (_parent.length) {
				if (!_parent.hasClass(_activeRowClass)) {
					_row.removeClass(_activeRowClass)
					_parent.addClass(_activeRowClass);
					resetRegRow();
				}
			}
		});
		_parentInp.click(function () {
			_row.removeClass(_activeRowClass);
			$(this).parents('div.row').addClass(_activeRowClass);
			resetRegRow();
		});
		_parentInpCustom.click(function () {
			_row.removeClass(_activeRowClass);
			$(this).parents('div.row').addClass(_activeRowClass);
			resetRegRow();
		});
		function resetRegRow () {
			_row.each(function () {
				var _parInp = $(' > input', $(this));
				if ($(this).hasClass(_activeRowClass)) {
					$(' > div.customRadio', $(this)).attr('class', 'customRadioChecked');
					_parInp.attr('checked', true);
				} else {
					$(' > div.customRadioChecked', $(this)).attr('class', 'customRadio');
					_parInp.attr('checked', false);
					$('ul div.customRadioChecked', $(this)).attr('class', 'customRadio');
					$('ul input', $(this)).attr('checked', false);
				}
			});
		}
	});
}
// 2010 08 05 end

// domready function
$(function(){
	initTabs(); // tabs
	initPopupScroll(); // popups scrolling functionality
	// select model popup
	initModelSelector('div.select-model');
	initModelSelector('div.rig');
	initModelSrc('div.filter-show');
	initComments(); // model post comments
	initAnswers(); // answers
	initReviews(); // reviews
	initDescription(); // model description
	initMyAnswers(); // comments
	initMyPhoto(); // photo
	initSearchForm(); // searchform
	initGameComp(); // games
	initStars(); //stars rate
	initModelShops(); // model page shops
	initShopInfo(); // shop rating info
	initPrices(); // phone prices tab
	initCustomLocation(); // 2010 08 05

	if(jQuery.ui && typeof(jQuery.ui.slider)=='function') {
		var _minPrice = 0; // min price value
		var _maxPrice = 50000; // max price value
		var _minPriceAct = $('#price-from').val(); // min price value actual
		var _maxPriceAct = $('#price-to').val(); // max price value actual

		if (_minPriceAct == 0) _minPriceAct = _minPrice;
		if (_maxPriceAct == 0) _maxPriceAct = _maxPrice;

		$('#price-slider').slider({
			range: true,
			min: _minPrice,
			max: _maxPrice,
			step: 5000,
			values: [_minPriceAct, _maxPriceAct],
			slide: function(event, ui) {
				$("#price-slider a.ui-slider-handle").eq(0).find('span').eq(1).text(ui.values[0]);
				$("#price-slider a.ui-slider-handle").eq(1).find('span').eq(1).text(ui.values[1]);
				if($('#price-from').length) $('#price-from').val(ui.values[0]);
				if($('#price-to').length) $('#price-to').val(ui.values[1]);
			}
		});
		$("#price-slider a.ui-slider-handle").eq(0).find('span').eq(1).text(_minPriceAct);
		$("#price-slider a.ui-slider-handle").eq(1).find('span').eq(1).text(_maxPriceAct);

	}
});

// model page gallery
function initModelGallery(){
	// vars
	var _photo = $('div.photo-gallery');
	var _prevLink = $('a.prev-btn',_photo);
	var _nextLink = $('a.next-btn',_photo);
	var _img = $('div.slicer img',_photo);
	var _closeLink = $('a.close-link',_photo);
	var _currItem = 0;

	function showImg(){
		_img.hide();
		_img.eq(_currItem).show();
	}
	showImg();

	// click 'prev' button
	_prevLink.click(function(){
		if(_currItem>0) _currItem--
		else _currItem = _img.length-1;
		showImg();
		return false;
	});

	// click 'next' button
	_nextLink.click(function(){
		if(_currItem<_img.length-1) _currItem++
		else _currItem = 0;
		showImg();
		return false;
	});

	// show gallery
	$('a.call-model-gall').click(function(){
		_photo.fadeIn(200);
		return false;
	});

	// hide gallery
	_closeLink.click(function(){
		_photo.fadeOut(200);
		return false;
	});

	// hide popup by clickin' the document
	$(document).click(function(e){
		if($(e.target).parents('.gallery-holder').length==0 && !$(e.target).hasClass('gallery-holder')) {
			_photo.fadeOut(200);
		}
	});

}
// window load function
function initWinLoad(){
	initModelGallery(); // model page gallery
}
if (window.addEventListener)
	window.addEventListener("load", initWinLoad, false);
else if (window.attachEvent)
	window.attachEvent("onload", initWinLoad);