/*
jquery.main.js
inputs.js
sitemap.js
resize.js
script.js
jquery-ui-1.8.9.custom.min.js
jquery.history.js
countdown.js
zakaz-zvonka.js
*/

/*--------------------------jquery.main.js------------------------------*/

//init page
$(function(){

	initPopups();
	hideFormText();
	resize();
});

// popups function
function initPopups() {
	var _zIndex = 1000;
	var _fadeSpeed = 350;
	var _faderOpacity = 0.95;
	var _faderBackground = '#000';
	var _faderId = 'lightbox-overlay';
	var _closeLink = 'a.btn-close, a.close, a.cancel';
	var _fader;
	var _lightbox = null;
	var _ajaxClass = 'ajax-load';
	var _openers = jQuery('a.open-popup');
	var _page = jQuery(document);
	var _minWidth = jQuery('body > div:eq(0)').outerWidth();
	var _scroll = false;

	// init popup fader
	_fader = jQuery('#'+_faderId);
	if(!_fader.length) {
		_fader = jQuery('<div />');
		_fader.attr('id',_faderId);
		jQuery('body').append(_fader);
	}
	_fader.css({
		opacity:_faderOpacity,
		backgroundColor:_faderBackground,
		position:'absolute',
		overflow:'hidden',
		display:'none',
		top:0,
		left:0,
		zIndex:_zIndex
	});

	// IE6 iframe fix
	if(jQuery.browser.msie && jQuery.browser.version < 7) {
		if(!_fader.children().length) {
			var _frame = jQuery('<iframe src="javascript:false" frameborder="0" scrolling="no" />');
			_frame.css({
				opacity:0,
				width:'100%',
				height:'100%'
			});
			var _frameOverlay = jQuery('<div>');
			_frameOverlay.css({
				top:0,
				left:0,
				zIndex:1,
				opacity:0,
				background:'#000',
				position:'absolute',
				width:'100%',
				height:'100%'
			});
			_fader.empty().append(_frame).append(_frameOverlay);
		}
	}

	// lightbox positioning function
	function positionLightbox() {
		if(_lightbox) {
			//alert(_lightbox.outerHeight()+'  '+jQuery(window).height());
			var _windowHeight = jQuery(window).height();
			var _windowWidth = jQuery(window).width();
			var _lightboxWidth = _lightbox.outerWidth();
			var _lightboxHeight = _lightbox.outerHeight();
			var _pageHeight = _page.height();

			if (_windowWidth < _minWidth) _fader.css('width',_minWidth);
				else _fader.css('width','100%');
			if (_windowHeight < _pageHeight) _fader.css('height',_pageHeight);
				else _fader.css('height',_windowHeight);

			_lightbox.css({
				position:'absolute',
				zIndex:(_zIndex+1)
			});

			// vertical position
			if (_windowHeight > _lightboxHeight) {
				if (jQuery.browser.msie && jQuery.browser.version < 7) {
					_lightbox.css({
						position:'absolute',
						top: parseInt(jQuery(window).scrollTop()) + (_windowHeight - _lightboxHeight) / 2
					});
					//alert('1');
				} else {
					_lightbox.css({
						position:'fixed',
						top: (_windowHeight - _lightboxHeight) 
					});
					//alert('2');
				}
				//alert('1');
			} else {
				var _faderHeight = _fader.height();
				if(_faderHeight < _lightboxHeight) _fader.css('height',_lightboxHeight);
				if (!_scroll) {
					if (_faderHeight - _lightboxHeight > parseInt(jQuery(window).scrollTop())) {
						_faderHeight = parseInt(jQuery(window).scrollTop())
						_scroll = _faderHeight;
					} else {
						_scroll = _faderHeight - _lightboxHeight;
					}
				}
				_lightbox.css({
					position:'absolute',
					top: _scroll
				});
				//alert('2');
			}

			// horizontal position
			if (_fader.width() > _lightbox.outerWidth()) _lightbox.css({left:(_fader.width() - _lightbox.outerWidth()) / 2});
			else _lightbox.css({left: 0});
		}
	}

	// show/hide lightbox
	function toggleState(_state) {
		if(!_lightbox) return;
		if(_state) {
			_fader.fadeIn(_fadeSpeed,function(){
				_lightbox.fadeIn(_fadeSpeed);
			});
			_scroll = false;
			positionLightbox();
		} else {
			_lightbox.fadeOut(_fadeSpeed,function(){
				_fader.fadeOut(_fadeSpeed);
				_scroll = false;
			});
		}
	}

	// popup actions
	function initPopupActions(_obj) {
		if(!_obj.get(0).jsInit) {
			_obj.get(0).jsInit = true;
			// close link
			_obj.find(_closeLink).click(function(){
				_lightbox = _obj;
				toggleState(false);
				return false;
			});
		}
	}

	// lightbox openers
	_openers.each(function(){
		var _opener = jQuery(this);
		var _target = _opener.attr('href');

		// popup load type - ajax or static
		if(_opener.hasClass(_ajaxClass)) {
			_opener.click(function(){
				// ajax load
				if(jQuery('div[rel*="'+_target+'"]').length == 0) {
					jQuery.ajax({
						url: _target,
						type: "POST",
						dataType: "html",
						success: function(msg){
							// append loaded popup
							_lightbox = jQuery(msg);
							_lightbox.find('img').load(positionLightbox)
							_lightbox.attr('rel',_target).hide().css({
								position:'absolute',
								zIndex:(_zIndex+1),
								top: -9999,
								left: -9999
							});
							jQuery('body').append(_lightbox);

							// init js for lightbox
							initPopupActions(_lightbox);

							// show lightbox
							toggleState(true);
						},
						error: function(msg){
							alert('AJAX error!');
							return false;
						}
					});
				} else {
					_lightbox = jQuery('div[rel*="'+_target+'"]');
					toggleState(true);
				}
				return false;
			});
		} else {
			if(jQuery(_target).length) {
				// init actions for popup
				var _popup = jQuery(_target);
				initPopupActions(_popup);
					// open popup
					_opener.click(function(){
					if(_lightbox) {
						_lightbox.fadeOut(_fadeSpeed,function(){
							_lightbox = _popup.hide();
							toggleState(true);
						})
					} else {
						_lightbox = _popup.hide();
						toggleState(true);
					}
					return false;
				});
			}
		}
	});

	// event handlers
	jQuery(window).resize(positionLightbox);
	jQuery(window).scroll(positionLightbox);
	jQuery(document).keydown(function (e) {
		if (!e) evt = window.event;
		if (e.keyCode == 27) {
			toggleState(false);
		}
	})
	_fader.click(function(){
		if(!_fader.is(':animated')) toggleState(false);
		return false;
	})
}
//clear inputs
function hideFormText() {
	var _inputs = document.getElementsByTagName('input');
	var _txt = document.getElementsByTagName('textarea');
	var _value = [];
	
	if (_inputs) {
		for(var i=0; i<_inputs.length; i++) {
			if (_inputs[i].type == 'text' || _inputs[i].type == 'password') {
				
				_inputs[i].index = i;
				_value[i] = _inputs[i].value;
				
				_inputs[i].onfocus = function(){
					if (this.value == _value[this.index])
						this.value = '';
						//alert('q');
				}
				_inputs[i].onblur = function(){
					if (this.value == '')
						this.value = _value[this.index];
						//alert('qq');
				}
			}
		}
	}
	if (_txt) {
		for(var i=0; i<_txt.length; i++) {
			_txt[i].index = i;
			_value['txt'+i] = _txt[i].value;
			
			_txt[i].onfocus = function(){
				if (this.value == _value['txt'+this.index])
					this.value = '';
			}
			_txt[i].onblur = function(){
				if (this.value == '')
					this.value = _value['txt'+this.index];
			}
		}
	}
}
//resize
function resize(){
	var _hold = document.getElementById('list');
	if (_hold) {
		var _list = _hold.getElementsByTagName('li');
		if(typeof(_list[0])!='undefined'){
		    var _width = _hold.offsetWidth;
		    var _wl = _list[0].offsetWidth;
		    var _vis = Math.floor(_width / _wl);
		    var _marg = Math.floor((_width - _vis * _wl - 2) / (_vis * 2));
		    if (_marg < 2) {
			    _vis = _vis - 1;
			    _marg = Math.floor((_width - _vis * _wl - 2) / (_vis * 2));
		    }
		    for (var i = 0; i < _list.length; i++) {
			    _list[i].style.marginLeft = _marg + 'px';
			    _list[i].style.marginRight = _marg + 'px';
		    }
		}
	}
}

/*------------------------inputs.js-------------------------*/

function hideFormText() {
	var _inputs = document.getElementsByTagName('input');
	var _txt = document.getElementsByTagName('textarea');
	var _value = [];
	
	if (_inputs) {
		for(var i=0; i<_inputs.length; i++) {
			if ((_inputs[i].type == 'text' || _inputs[i].type == 'password') && _inputs[i].className.indexOf('nohidetxt')==-1) {
				
				_inputs[i].index = i;
				_value[i] = _inputs[i].value;
				
				_inputs[i].onfocus = function(){
					if (this.value == _value[this.index]){
						this.value = '';
						this.style.color = 'black';
					}
					else{
						
					}
				}
				_inputs[i].onblur = function(){
					if (this.value == ''){
						this.value = _value[this.index];
						this.style.color = '#939598';
					}
					else{
						//this.style.color = '#939598';
					}
				}
			}
		}
	}
	if (_txt) {
		for(var i=0; i<_txt.length; i++) {
			_txt[i].index = i;
			_value['txt'+i] = _txt[i].value;
			
			_txt[i].onfocus = function(){
				if (this.value == _value['txt'+this.index]){
					this.value = '';
					this.style.color = 'black';
				}
			}
			_txt[i].onblur = function(){
				if (this.value == ''){
					this.value = _value['txt'+this.index];
					this.style.color = '#939598';
				}
			}
		}
	}
}
if (window.addEventListener)
	window.addEventListener("load", hideFormText, false);
else if (window.attachEvent)
	window.attachEvent("onload", hideFormText);
	
/*---------------------sitemap.js----------------------*/
jQuery(document).ready(function(){


	jQuery(".expander").unbind("click");
	jQuery(".expander").bind("click", function() {
		if (jQuery(this).find("~ ul").is(":hidden")) jQuery(this).text("-");
		else jQuery(this).text("+");
		jQuery(this).find("~ ul").slideToggle(200); 
		return false;
		});

	var obj = jQuery("#html_site_map>ul>li")[2];
	jQuery(obj).children(".expander").click(); 
});

/*-------------------------resize.js ---------------------------*/

function initPage(){
	var _hold = document.getElementById('list');
  if(_hold == null) return;
	var _list = _hold.getElementsByTagName('li');
	if(_list.length==0) return;
	var _width = _hold.offsetWidth;
	var _wl = _list[0].offsetWidth;
	var _vis = Math.floor(_width/_wl);
	var _marg = Math.floor((_width - _vis*_wl-2)/(_vis*2));
	if (_marg < 2){
		_vis = _vis-1;
		_marg = Math.floor((_width - _vis*_wl-2)/(_vis*2));
	}
	for (var i = 0; i < _list.length; i++) {
		_list[i].style.marginLeft = _marg + 'px';
		_list[i].style.marginRight = _marg + 'px';
	}
}
if (window.addEventListener) window.addEventListener("load", initPage, false);
else if (window.attachEvent && !window.opera) window.attachEvent("onload", initPage);
if (window.addEventListener) window.addEventListener("resize", initPage, false);
else if (window.attachEvent && !window.opera) window.attachEvent("onresize", initPage);

/*-------------------------script.js--------------------------*/ 


var flt_timer;
var catalog_page = 1;
var keyCtrl = false;
var timer;

var cart_deleted = {};
cart_deleted.html = {};
cart_deleted.ids = [];


function CookieHandler(){
	this.setCookie = function (name, value, seconds){
		if (typeof(seconds) != 'undefined'){
			var date = new Date();
			date.setTime(date.getTime() + (seconds*1000));
			var expires = "; expires=" + date.toGMTString();
		}else{
			var expires = "";
		}
		document.cookie = name+"="+value+expires+"; path=/";
	}
	this.getCookie = function(name){
		name = name + "=";
		var carray = document.cookie.split(';');
		for(var i=0;i < carray.length;i++){
			var c = carray[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
		}
		return null;
	}
	this.deleteCookie = function (name){
		this.setCookie(name, "", -1);
	}
}
var Cookies = new CookieHandler();


function deletedInsert(){
    var rows = $('#shopCart form div.row').not('.titlerow');
    for(var i in cart_deleted.html){
        rows.last().after(cart_deleted.html[i][1]);
    }
}

$(document).bind('ready',function(){
    var parent = $('#shopCart form');
    var rows = $('div.row',parent).not('.titlerow');
    rows.each(function(i){
        var p_id = $('input.shk-id',$(this)).val();
        cart_deleted.ids.push(p_id);
    });
});

function sortCartRows(){
    var parent = $('#shopCart form');
    var rows = $('div.row',parent).not('.titlerow');
    var first_row = $('div.row:first',parent);
    for(var i=cart_deleted.ids.length;i>=0;i--){
        var c_row_input = $("input.shk-id[value="+cart_deleted.ids[i]+"]",rows);
        var c_row = c_row_input.parent().parent();
        //console.log(cart_deleted.ids.length+' - '+i);
        first_row.after(c_row);
    }
}

function setCartActionsCallback(){
    
    if($('#shopCart form').size()==0){
        $('#cartButtons').hide();
    }
    
    deletedInsert();
    var rows = $('#shopCart form div.row').not('.titlerow');
    
    rows
    .removeClass('dark')
    .not('.deleted')
    .each(function(i){
        var thisRow = $(this);
        var p_count = $('input.shk-count',thisRow).val();
        var p_id = $('input.shk-id',thisRow).val();
        $('input.shk-count',thisRow).removeAttr('disabled');
        $('input:checkbox',thisRow)
        .removeAttr('checked')
        .unbind('click')
        .bind('click',function(){
            var self = $(this);
            //clearTimeout(timer);
            //timer = setTimeout(function(){
              //if(self.is(':checked')){
                $(this).unbind('click').bind('click',function(){return false;});
                $('input:checkbox',rows).unbind('click').bind('click',function(){return false;});
                thisRow.addClass('deleted').children('div').not(':last').css('opacity',0.35);
                $('input:text',thisRow).attr('disabled','disabled');
                cart_deleted.html[p_id] = [i,thisRow];
                jQuery.deleteItem(i,null);
                if(p_id==65){
                    Cookies.setCookie('delivery', '0', 60*60);
                }
              //}
            //},200);
            //return false;
        });
    });
    
    rows
    .filter('.deleted')
    .each(function(){
        var thisRow = $(this);
        var p_count = $('input.shk-count',thisRow).val();
        var p_id = $('input.shk-id',thisRow).val();
        $('input:checkbox',thisRow)
        .attr('checked','checked')
        .unbind('click')
        .bind('click',function(){
            var self = $(this);
            //clearTimeout(timer);
            //timer = setTimeout(function(){
              //if(!self.is(':checked')){
                $(this).unbind('click').bind('click',function(){return false;});
                $('input:checkbox',rows).unbind('click').bind('click',function(){return false;});
                thisRow.removeClass('deleted').children('div').css('opacity',1);
                $('input:text',thisRow).removeAttr('disabled');
                delete cart_deleted.html[p_id];
                jQuery.fillCart(p_id,p_count);
              //}
            //},200);
            //return false;
        });
    });
    
    sortCartRows();
    
    var rows = $('#shopCart form div.row').not('.titlerow');
    rows.filter(':odd').addClass('dark');
    rows.filter(':even').removeClass('dark');
    
}




///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

function is_array(input){
  return typeof(input)=='object'&&(input instanceof Array);
}

function clone(obj){
  if(obj == null || typeof(obj) != 'object') return obj;
  var temp = new obj.constructor(); 
  for(var key in obj) temp[key] = clone(obj[key]);
  return temp;
}

function array_max(obj) {
  var max = obj[0];
  var len = obj.length;
  for (var i = 1; i < len; i++) if (obj[i] > max) max = obj[i];
  return max;
}

function array_min(obj) {
  var min = obj[0];
  var len = obj.length;
  for (var i = 1; i < len; i++) if (obj[i] < min) min = obj[i];
  return min;
}

function array_intersect(){
    var arr1 = arguments[0], retArr = [];
    var k1 = '', arr = {}, i = 0, k = '';
    arr1keys: for (k1 in arr1) {
        arrs: for (i = 1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1]) {
                    if (i === arguments.length - 1) {
                        //retArr[k1] = arr1[k1];
                        retArr.push(arr1[k1]);
                    }
                    continue arrs;
                }
            }
            continue arr1keys;
        }
    }
    return retArr;
}


function closestTo(number, set) {
    var closest = set[0];
    var prev = Math.abs(set[0] - number);
    for (var i = 1; i < set.length; i++) {
        var diff = Math.abs(set[i] - number);
        if (diff < prev) {
            prev = diff;
            closest = set[i];
        }
    }
    return closest;
}


function updateArray(id,id_array){
    var r_index = $.inArray(id,id_array);
    if(r_index!=-1) id_array.splice(r_index,1);
    return id_array;
}

function filterItems(value,array,action){
    if(typeof(action)=='undefined') var action = 1;
    var output = false;
    //console.log(value,array,action);
    if(is_array(value)){
      var check = 0;
      for(var i in value){
          if(!filterItems(value[i],array,action)){
            check++;
            break;
          }
      }
      return check==0;
    }
    switch(action){
      case 1:
        //console.log(value,array,$.inArray(value,array));
        if($.inArray(value,array)==-1) output = true;
      break;
      case 2:
        if($.inArray(value,array)>-1) output = true;
      break;
      case 3:
        //console.log(value,array);
        if(value < array[0] || value > array[1]) output = true;
      break;
    }
    return output;
}

function markUnactive(index,action,count_text){
  var parent = $('div.filter_item','#filters').eq(index);
  var input = $('input',parent);
  if(action>0){
    //console.log(index,action,count_text);
    parent.removeClass('unactive');
    parent.removeClass('onlyactive');
    if(count_text==0) parent.addClass('onlyactive');
    input.removeAttr('disabled');
  }else{
    if(input.is(':checked')){
      parent.addClass('unactive');
    }else{
      parent.addClass('unactive');
      input.attr('disabled','disabled');
    }
  }
}

function parseFilter(flt,elem){
    var flt_name = elem.attr('name').split('_');
    var flt_ind = elem.val().split('_');
    var flt_index = flt_index[1];
    if(typeof(flt[flt_name[0]])=='undefined'){
      flt[flt_name[0]] = {};
      flt[flt_name[0]].flt = [];
    }
    flt[flt_name[0]].flt.push(parseInt(flt_name[1]));
    flt[flt_name[0]].action = 1;
    return flt;
}

function readFilters(){
    var flt = new Object;
    //читаем фильтры
    $('input[type=checkbox]','#filters').each(function(i){
        var flt_name = $(this).attr('name').split('_');
        var flt_ind = $(this).val().split('_');
        var flt_index = flt_ind[1];
        var flt_checked = $(this).is(':checked');
        if(typeof(flt[flt_name[0]])=='undefined'){
          flt[flt_name[0]] = {};
          flt[flt_name[0]].flt = [];
          flt[flt_name[0]].ind = [];
          flt[flt_name[0]].action = 1;
        }
        //if(flt_checked) flt[flt_name[0]].flt.push(parseInt(flt_name[1]));
        //if(flt_checked) flt[flt_name[0]].flt.push((isNaN(flt_ind[0]) ? flt_ind[0]+'&'+flt_name[1] : parseInt(flt_ind[0])+'&'+flt_name[1]));
        if(flt_checked){
          flt[flt_name[0]].ind.push(flt_name[1]);
          flt[flt_name[0]].flt.push(isNaN(flt_ind[0]) ? flt_ind[0] : parseInt(flt_ind[0]));
        }
    });
    
    //фильтр цены
    if($('#price_1').size()>0){
      flt.price = {};
      flt.price.flt = [parseInt($('#price_1').val()),parseInt($('#price_2').val())];
      //flt.price.ind = [0,1];
      flt.price.action = 3;
    }
    
    //console.log(flt);
    
    return flt;
}

function getIdsPrices(){
    var output = {'ids':[],'prices':[]};
    for(var i in data.cvety){
      output.ids.push(data.cvety[i].id);
      output.prices.push(data.cvety[i].price);
    }
    //console.log(output);
    return output;
}

function addLocationHash(filters,move,return_hash){
    //console.log(filters);
    if(typeof(move)=='undefined') var move = true;
    if(typeof(return_hash)=='undefined') var return_hash = false;
    var f_hash = '';
    for(var i in filters){
      //if(filters[i].flt.length>0) f_hash += i+'='+(filters[i].flt.join('_'))+'/';
      if(filters[i].flt.length>0){
        f_hash += i+'=';
        for(var ii in filters[i].flt){
            //console.log(i);
            //console.log(filters[i].ind[ii]);
            var str = typeof(filters[i].ind)!='undefined' ? filters[i].flt[ii]+'&'+filters[i].ind[ii] : filters[i].flt[ii];
            //var str = typeof() filters[i].flt[ii]+'&'+filters[i].ind[ii];
            f_hash += ii>0 ? '_'+str : str;
        }
        f_hash += '/';
      }
    }
    f_hash += 'page='+catalog_page;
    if(move) $('#pageAnchor').attr('name',f_hash);
    if(!return_hash) window.location.hash = f_hash;
    else return f_hash;
    //if(typeof(console)=='object') console.log(f_hash);
}



function priceFilter(field){
    if(typeof(field)=='undefined') return;
    var field_name = $(field).attr('name');
    var field_value = field_name ? parseInt($(field).val()) : 0;
    var filters = readFilters();
    
    //проверяем чтобы введенное значение было в нужных пределах
    if(field_name=='price_1' && field_value < $('#slider-range').slider("option",'min')){
      $('#price_1').val($('#slider-range').slider("option",'min'));
      $("#slider-range").slider("values",0,$('#slider-range').slider("option",'min'));
    }
    if(field_name=='price_2' && field_value > $('#slider-range').slider("option",'max')){
      $('#price_2').val($('#slider-range').slider("option",'max'));
      $("#slider-range").slider("values",1,$('#slider-range').slider("option",'max'));
    }
    
    //передвигаем слайдер в положение соответствующее введенному значению
    if(field_name=='price_1') $("#slider-range").slider("values",0,field_value);
    if(field_name=='price_2') $("#slider-range").slider("values",1,field_value);
    
    prodIds = searchProducts(filters);
    //console.log(field_name,prodIds.length);
    
    //если товаров не найдено, исменяем значение на ближайшее
    if(prodIds.length==0){
      if(field_name=='price_1') filters.price.flt[0] = array_min(idsPrices.prices);
      if(field_name=='price_2') filters.price.flt[1] = array_max(idsPrices.prices);
      prodIds = searchProducts(filters);
      var new_price = [];
      for(i in idsPrices.ids){
        if($.inArray(idsPrices.ids[i],prodIds)>-1) new_price.push(idsPrices.prices[i]);
      }
      if(field_name=='price_1'){
        $('#price_1').val(array_max(new_price));
        $("#slider-range").slider("values",0,array_max(new_price));
      }else{
        $('#price_2').val(array_min(new_price));
        $("#slider-range").slider("values",1,array_min(new_price));
      }
      //console.log(new_price);
    }
    startFiltering(true,false);
    //console.log(prodIds);
}


function getHashFilters(){
    var l_hash = window.location.hash;
    if(!l_hash) return;
    var hash_filters = l_hash.substr(1,l_hash.length).split('/');
    for(var i in hash_filters){
      if(!hash_filters[i]) continue;
      var hf_flt = hash_filters[i].split('=');
      var hf_vals = hf_flt[1].split('_');
      if(hf_flt[0]=='price'){
        if(hf_vals.length==2){
          var price1 = hf_vals[0];//hf_vals[0].split('&'); price1 = price1[0];
          var price2 = hf_vals[1];//hf_vals[1].split('&'); price2 = price2[0];
          $('#price_1').val(price1);
          $("#slider-range").slider("values",0,price1);
          $('#price_2').val(price2);
          $("#slider-range").slider("values",1,price2);
        }
      }else if(hf_flt[0]=='page'){
          catalog_page = hf_flt.length>1 ? hf_flt[1] : 1;
      }else{
        for(var ii in hf_vals){
          var hf_name = hf_vals[ii].split('&');
          var f_input = hf_name.length>1 ? hf_flt[0]+'_'+hf_name[1] : hf_flt[0]+'_0';
          $('input[name='+f_input+']:checkbox','#filters').attr('checked','checked');
          $('input[name='+f_input+']:checkbox','#filters').next('a').addClass('active');
        }
      }
    }
    //startFiltering();
}


function searchProducts(filters,default_elem,type){
    if(typeof(type)=='undefined') var type = 1; 
    var prodIds = typeof(idsPrices) != 'undefined' ? idsPrices.ids.concat() : [];
    var s_filters = clone(filters);
    
    //проверка
    if(typeof(default_elem)!='undefined'){
      
      var def_flt_name = $(default_elem).attr('name').split('_');
      var def_flt_ind = $(default_elem).val().split('_');
      var def_flt_index = def_flt_ind[1];
      var def_flt_value = isNaN(def_flt_ind[0]) ? def_flt_ind[0] : parseInt(def_flt_ind[0]);
      var def_key = $.inArray(def_flt_value,s_filters[def_flt_name[0]].flt);
      
      if(def_key==-1){
        if(type == 1) s_filters[def_flt_name[0]].flt = [def_flt_value];
        else s_filters[def_flt_name[0]].flt.push(def_flt_value);
        //else s_filters[def_flt_name[0]].flt.push(parseInt(def_flt_name[1]));
      }else{
        //console.log(def_flt_name[0],def_flt_name[1],s_filters[def_flt_name[0]].flt);
        if(type == 1) s_filters[def_flt_name[0]].flt.splice(def_key, 1);
        else s_filters[def_flt_name[0]].flt = [def_flt_value];//s_filters[def_flt_name[0]].flt = [];
      }
      
    }
    
    //фильтруем
    if(typeof(data)!='undefined'){
      for(var i in s_filters){
        for(var ii in data.cvety){
          //console.log(i,data.cvety[ii][i],data.cvety[ii][i].length);
          if(/*((is_array(data.cvety[ii][i]) && data.cvety[ii][i].length>0)) && */s_filters[i].flt.length>0 && $.inArray(data.cvety[ii].id,prodIds)>-1){
            //console.log(data.cvety[ii].id,data.cvety[ii][i],s_filters[i].flt,filterItems(data.cvety[ii].id,data.cvety[ii][i],s_filters[i].flt,s_filters[i].action));
            if(filterItems(data.cvety[ii][i],s_filters[i].flt,s_filters[i].action)){
              prodIds = updateArray(data.cvety[ii].id,prodIds);
            }
          }
        }
      }
    }
    //if(typeof(console)=='object') console.log(filters);
    
    return prodIds;
}

var loader_timer;
$.fn.ajaxPreload = function(action){
  var target = $(this);
  if(action==true){
    clearTimeout(loader_timer);
    if($('#ajax_loader').size()==0) target.prepend('<div id="ajax_loader"></div>');
    $('#ajax_loader')
    .css({
      'position': 'absolute',
      'z-index': '200',
      'padding': '10px',
      'margin': '-10px 0 0 -10px',
      'width': target.width()+'px',
      'height': target.height()+'px',
      'background': 'url(images/ajax-loader.gif) center center no-repeat #fff',
      'opacity': 0.7
    });
    //target.css({'height':target.height()+'px','overflow':'hidden'});
  }else{
    //loader_timer = setTimeout(function(){
      $('#ajax_loader').remove();
      //target.css({'height':'auto','overflow':'auto'});
    //},500);
  }
}


function startFiltering(load_results,move){
    if(typeof(load_results)=='undefined') var load_results = true;
    if(typeof(move)=='undefined') var move = true;
    var filters = readFilters();
    var prodIds = searchProducts(filters);
    
    if(load_results) $('#products').ajaxPreload(true);
    
    $('input[type=checkbox]','#filters').each(function(i){
        var f_link = $(this).next('a');
        
        if(f_link.next('sup').size()==0) f_link.after('<sup></sup>');
        
        var f_count = f_link.next('sup');
        var def_flt_name = $(this).attr('name').split('_');
        var if_filter = searchProducts(filters,$(this),1);
        var if_filter_count = searchProducts(filters,$(this),2).length;
        var if_filter_count_text = if_filter.length>0 ? if_filter_count : 0;
        
        //f_count.text(if_filter_count+'-'+if_filter.length+'->'+if_filter_count_text);
        //f_count.text($(this).is(':checked') ? if_filter.length : if_filter_count_text);
        f_count.html($(this).is(':checked') ? '&nbsp;' : if_filter_count_text);
        markUnactive(i,$(this).is(':checked') ? if_filter_count : if_filter.length,if_filter_count_text);
        
    });
    
    if(load_results){
      //var sort_dir = $('#ctl_sorting').val();
	  //mod
		var sortdir = $('#ctl_sorting').val();
		var sortby = 'price';
		var sortby_type = 'integer';
		if  (sortdir=='menuindex'){
			sortby='menuindex';
			sortdir='asc';
		}
		if  (sortdir=='pagetitle'){
			sortby='pagetitle';
			sortdir='asc';
			sortby_type = 'string';	
		}	   
	  //end mod
      //ajaxRequest(prodIds,'ctl_sortdir='+sort_dir);
	  ajaxRequest(prodIds,'ctl_sorttype='+sortby_type+'&ctl_sortby='+sortby+'&ctl_sortdir='+sortdir);
      addLocationHash(filters,move);
    }
    
    //if(typeof(console)=='object') console.log(prodIds,'--------------------');
    //else alert(prodIds);

    //$('#result_count').text(prodIds.length);
    
}


$.fn.searchFilter = function(option){
    $(this).each(function(i){
    
      $(this).bind('click',function(e){
          
          var flt = $(this).is('a') ? $(this).prev('input') : $(this);
          var parent = $(this).parent('div');
          clearTimeout(flt_timer);
          
          if($(this).is('a')){
              if(flt.is(':checked')){
                  //alert(parent.is('.onlyactive'));
                  if(!flt.is(':disabled') && !parent.is('.onlyactive')){
                    flt.removeAttr('checked');
                    $(this).removeClass('active');
                  }
              }else{
                  if(!flt.is(':disabled') && !parent.is('.onlyactive')){
                    flt.attr('checked','checked');
                    $(this).addClass('active');
                  }
              }
          }else{
            if(parent.is('.onlyactive')) flt.attr('checked','checked');
          }
          
          if(!flt.is(':disabled') && !parent.is('.onlyactive')){
            
            //flt_timer = setTimeout(startFiltering,1000);
            catalog_page = 1;
            startFiltering(true,false);
          
          }
          if($(this).is('a')) return false;
          
      });
      
    });
}


function ajaxRequest(prodIds,params){
  var data_conteiner = $('ul:first','#products');
  var pages_conteinet = $('#paginator');
  var total_items = $('#total_items');
  if(typeof(params)=='undefined') var params = '';
  //var r_params = 'docs='+prodIds.join(',')+'&'+params;
  if(!params) params = 'ajax=1';
  
  if(params.indexOf('docs')==-1 && prodIds.length > 0)
      params += '&docs='+prodIds.join(',');
  else if(typeof(docId)!='undefined')
      params += '&parent='+docId;
      
  if(params.indexOf('ctl_display')==-1) params += '&ctl_display='+$('select','#show').val();
  if(params.indexOf('ctl_page')==-1) params += '&ctl_page='+catalog_page;
  //console.log(catalog_page);
  $.ajax({
    url: '/assets/snippets/autoFilters/catalogView_ajax.php',
    type: "GET",
    cache: false,
    data: params,
    //data: {'docs': prodIds.join(','), 'display': 16, 'page': page},
    dataType: 'json',
    success: function(response) {
      //console.log(response);
      var prod_list = response.prod_list;
      if(prod_list) data_conteiner.html(prod_list);
      if(response.pages) pages_conteinet.html(response.pages);
	  if(response.total_items) total_items.html(response.total_items);
      $('#products').ajaxPreload(false);
      if(typeof(initPage)=='function') initPage();
    },
    error: function(jqXHR,textStatus,errorThrown){
      if(typeof(console)!='undefined') console.log(jqXHR,textStatus,errorThrown);
    }
  });
}



function resetFilters(){
    $('input:checkbox','#filters').removeAttr('checked');
    $('a.label','#filters').removeClass('active');
    $('#price_1').val($('#slider-range').slider("option",'min'));
    $("#slider-range").slider("values",0,$('#slider-range').slider("option",'min'));
    $('#price_2').val($('#slider-range').slider("option",'max'));
    $("#slider-range").slider("values",1,$('#slider-range').slider("option",'max'));
    startFiltering(true,false);
}


$.fn.ajaxPages = function(){
  var parent = $(this);
  $('a',parent).live('click',function(){
      
      var href = $(this).attr('href');
      var page = href.charAt(href.length-1);
      catalog_page = page;
      startFiltering(true,true);
      
      $.history.load(page);
      
      return false;
  });
}


function displaySortSwitch(){
    /*
	var filters = readFilters();
    catalog_page = 1;
    var flt_hash = addLocationHash(filters,false,true);
	var sortdir = $('#ctl_sorting').val();
	var sortby = 'price';
	var sortby_type = 'integer';
	if  (sortdir=='menuindex'){
		sortby='menuindex';
		sortdir='asc';
	}
	if  (sortdir=='pagetitle'){
		sortby='pagetitle';
		sortdir='asc';
		sortby_type = 'string';	
	}
        
	window.location.href = window.location.pathname+'?ctl_display='+$('#ctl_display').val()+'&ctl_sorttype='+sortby_type+'&ctl_sortby='+sortby+'&ctl_sortdir='+sortdir+'#'+flt_hash;
	*/
	startFiltering(true,false);
}


/////////////////////////////////////////
// переход по страницам при нажатии на клавиши "Ctrl + ->", "Ctrl + <-"
function ajaxPagesInit(){
    
    $(document)
    .keydown(function(event){
      if(event.which==17) keyCtrl = true;
    })
    .keyup(function(event){
      if(event.which==17) keyCtrl = false;
      if($('#ajax_loader').size()>0) return; 
      if(keyCtrl && event.which==37){
        var next_link = $('b.current','#paginator').prev('a');
        var next_page = next_link.size()>0 ? next_link.text() : 0;
      }
      if(keyCtrl && event.which==39){
        var next_link = $('b.current','#paginator').next('a');
        var next_page = next_link.size()>0 ? next_link.text() : 0;
      }
      if(next_page){
          catalog_page = next_page;
          startFiltering(true);
      }
    });
    
    $('#paginator').ajaxPages();
    
    //история браузера
    $.history.init(function(hash){
        var h_page = hash.substr(hash.length-1,1);
        if(h_page && catalog_page != h_page){
          catalog_page = h_page;
          startFiltering(true);
        }
    });
}
/////////////////////////////////////////


///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

/*------------------------jquery-ui-1.8.9.custom.min.js-----------------------*/ 

/*!
 * jQuery UI 1.8.9
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function(c,j){function k(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.9",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,
NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,
"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");
if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"),10);if(!isNaN(b)&&b!==0)return b}a=a.parent()}}return 0},disableSelection:function(){return this.bind((c.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});c.each(["Width","Height"],function(a,b){function d(f,g,l,m){c.each(e,function(){g-=parseFloat(c.curCSS(f,"padding"+this,true))||0;if(l)g-=parseFloat(c.curCSS(f,
"border"+this+"Width",true))||0;if(m)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c(this).css(h,d(this,f)+"px")})};c.fn["outer"+b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c(this).css(h,
d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");if("area"===b){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&k(a)}return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==b?a.href||!isNaN(d):!isNaN(d))&&k(a)},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}});
c(function(){var a=document.body,b=a.appendChild(b=document.createElement("div"));c.extend(b.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});c.support.minHeight=b.offsetHeight===100;c.support.selectstart="onselectstart"in b;a.removeChild(b).style.display="none"});c.extend(c.ui,{plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&
b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)}})}})(jQuery);
;/*!
 * jQuery UI Widget 1.8.9
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function(b,j){if(b.cleanData){var k=b.cleanData;b.cleanData=function(a){for(var c=0,d;(d=a[c])!=null;c++)b(d).triggerHandler("remove");k(a)}}else{var l=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return l.call(b(this),a,c)})}}b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,
a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.charAt(0)==="_")return h;
e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):this.each(function(){var g=b.data(this,a);g?g.option(d||{})._init():b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options,
this._getCreateOptions(),a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},
widget:function(){return this.element},option:function(a,c){var d=a;if(arguments.length===0)return b.extend({},this.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}this._setOptions(d);return this},_setOptions:function(a){var c=this;b.each(a,function(d,e){c._setOption(d,e)});return this},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},
enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
;/*!
 * jQuery UI Mouse 1.8.9
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */
(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(true===c.data(b.target,a.widgetName+".preventClickEvent")){c.removeData(b.target,a.widgetName+".preventClickEvent");b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=
a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=
this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!(document.documentMode>=9)&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);
return a.preventDefault()}if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;a.target==this._mouseDownEvent.target&&c.data(a.target,this.widgetName+".preventClickEvent",
true);this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
;/*
 * jQuery UI Slider 1.8.9
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var b=this,a=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");a.disabled&&this.element.addClass("ui-slider-disabled ui-disabled");
this.range=d([]);if(a.range){if(a.range===true){this.range=d("<div></div>");if(!a.values)a.values=[this._valueMin(),this._valueMin()];if(a.values.length&&a.values.length!==2)a.values=[a.values[0],a.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(a.range==="min"||a.range==="max")this.range.addClass("ui-slider-range-"+a.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");
if(a.values&&a.values.length)for(;d(".ui-slider-handle",this.element).length<a.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){a.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(a.disabled)d(this).blur();
else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),h,g,i;if(!b.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e=
false;if(!b._keySliding){b._keySliding=true;d(this).addClass("ui-state-active");h=b._start(c,f);if(h===false)return}break}i=b.options.step;h=b.options.values&&b.options.values.length?(g=b.values(f)):(g=b.value());switch(c.keyCode){case d.ui.keyCode.HOME:g=b._valueMin();break;case d.ui.keyCode.END:g=b._valueMax();break;case d.ui.keyCode.PAGE_UP:g=b._trimAlignValue(h+(b._valueMax()-b._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:g=b._trimAlignValue(h-(b._valueMax()-b._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(h===
b._valueMax())return;g=b._trimAlignValue(h+i);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(h===b._valueMin())return;g=b._trimAlignValue(h-i);break}b._slide(c,f,g);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(b._keySliding){b._keySliding=false;b._stop(c,e);b._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");
this._mouseDestroy();return this},_mouseCapture:function(b){var a=this.options,c,e,f,h,g;if(a.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c=this._normValueFromMouse({x:b.pageX,y:b.pageY});e=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(i){var j=Math.abs(c-h.values(i));if(e>j){e=j;f=d(this);g=i}});if(a.range===true&&this.values(1)===a.min){g+=1;f=d(this.handles[g])}if(this._start(b,
g)===false)return false;this._mouseSliding=true;h._handleIndex=g;f.addClass("ui-state-active").focus();a=f.offset();this._clickOffset=!d(b.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:b.pageX-a.left-f.width()/2,top:b.pageY-a.top-f.height()/2-(parseInt(f.css("borderTopWidth"),10)||0)-(parseInt(f.css("borderBottomWidth"),10)||0)+(parseInt(f.css("marginTop"),10)||0)};this.handles.hasClass("ui-state-hover")||this._slide(b,g,c);return this._animateOff=true},_mouseStart:function(){return true},
_mouseDrag:function(b){var a=this._normValueFromMouse({x:b.pageX,y:b.pageY});this._slide(b,this._handleIndex,a);return false},_mouseStop:function(b){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(b,this._handleIndex);this._change(b,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(b){var a;
if(this.orientation==="horizontal"){a=this.elementSize.width;b=b.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{a=this.elementSize.height;b=b.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}a=b/a;if(a>1)a=1;if(a<0)a=0;if(this.orientation==="vertical")a=1-a;b=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+a*b)},_start:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=
this.values(a);c.values=this.values()}return this._trigger("start",b,c)},_slide:function(b,a,c){var e;if(this.options.values&&this.options.values.length){e=this.values(a?0:1);if(this.options.values.length===2&&this.options.range===true&&(a===0&&c>e||a===1&&c<e))c=e;if(c!==this.values(a)){e=this.values();e[a]=c;b=this._trigger("slide",b,{handle:this.handles[a],value:c,values:e});this.values(a?0:1);b!==false&&this.values(a,c,true)}}else if(c!==this.value()){b=this._trigger("slide",b,{handle:this.handles[a],
value:c});b!==false&&this.value(c)}},_stop:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("stop",b,c)},_change:function(b,a){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("change",b,c)}},value:function(b){if(arguments.length){this.options.value=
this._trimAlignValue(b);this._refreshValue();this._change(null,0)}return this._value()},values:function(b,a){var c,e,f;if(arguments.length>1){this.options.values[b]=this._trimAlignValue(a);this._refreshValue();this._change(null,b)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(b):this.value();
else return this._values()},_setOption:function(b,a){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(b){case "disabled":if(a){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation();
this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var b=this.options.value;return b=this._trimAlignValue(b)},_values:function(b){var a,c;if(arguments.length){a=this.options.values[b];
return a=this._trimAlignValue(a)}else{a=this.options.values.slice();for(c=0;c<a.length;c+=1)a[c]=this._trimAlignValue(a[c]);return a}},_trimAlignValue:function(b){if(b<=this._valueMin())return this._valueMin();if(b>=this._valueMax())return this._valueMax();var a=this.options.step>0?this.options.step:1,c=(b-this._valueMin())%a;alignValue=b-c;if(Math.abs(c)*2>=a)alignValue+=c>0?a:-a;return parseFloat(alignValue.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},
_refreshValue:function(){var b=this.options.range,a=this.options,c=this,e=!this._animateOff?a.animate:false,f,h={},g,i,j,l;if(this.options.values&&this.options.values.length)this.handles.each(function(k){f=(c.values(k)-c._valueMin())/(c._valueMax()-c._valueMin())*100;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](h,a.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(k===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},a.animate);
if(k===1)c.range[e?"animate":"css"]({width:f-g+"%"},{queue:false,duration:a.animate})}else{if(k===0)c.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},a.animate);if(k===1)c.range[e?"animate":"css"]({height:f-g+"%"},{queue:false,duration:a.animate})}g=f});else{i=this.value();j=this._valueMin();l=this._valueMax();f=l!==j?(i-j)/(l-j)*100:0;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](h,a.animate);if(b==="min"&&this.orientation==="horizontal")this.range.stop(1,
1)[e?"animate":"css"]({width:f+"%"},a.animate);if(b==="max"&&this.orientation==="horizontal")this.range[e?"animate":"css"]({width:100-f+"%"},{queue:false,duration:a.animate});if(b==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},a.animate);if(b==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:a.animate})}}});d.extend(d.ui.slider,{version:"1.8.9"})})(jQuery);
;

/*------------------------------jquery.history.js--------------------------------*/ 
/*
 * jQuery history plugin
 * 
 * The MIT License
 * 
 * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
 * Copyright (c) 2010 Takayuki Miwa
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

(function($) {
    var locationWrapper = {
        put: function(hash, win) {
            //(win || window).location.hash = this.encoder(hash);
        },
        get: function(win) {
            var hash = ((win || window).location.hash).replace(/^#/, '');
            try {
                return $.browser.mozilla ? hash : decodeURIComponent(hash);
            }
            catch (error) {
                return hash;
            }
        },
        encoder: encodeURIComponent
    };

    var iframeWrapper = {
        id: "__jQuery_history",
        init: function() {
            var html = '<iframe id="'+ this.id +'" style="display:none" src="javascript:false;" />';
            $("body").prepend(html);
            return this;
        },
        _document: function() {
            return $("#"+ this.id)[0].contentWindow.document;
        },
        put: function(hash) {
            var doc = this._document();
            doc.open();
            doc.close();
            locationWrapper.put(hash, doc);
        },
        get: function() {
            return locationWrapper.get(this._document());
        }
    };

    function initObjects(options) {
        options = $.extend({
                unescape: false
            }, options || {});

        locationWrapper.encoder = encoder(options.unescape);

        function encoder(unescape_) {
            if(unescape_ === true) {
                return function(hash){ return hash; };
            }
            if(typeof unescape_ == "string" &&
               (unescape_ = partialDecoder(unescape_.split("")))
               || typeof unescape_ == "function") {
                return function(hash) { return unescape_(encodeURIComponent(hash)); };
            }
            return encodeURIComponent;
        }

        function partialDecoder(chars) {
            var re = new RegExp($.map(chars, encodeURIComponent).join("|"), "ig");
            return function(enc) { return enc.replace(re, decodeURIComponent); };
        }
    }

    var implementations = {};

    implementations.base = {
        callback: undefined,
        type: undefined,

        check: function() {},
        load:  function(hash) {},
        init:  function(callback, options) {
            initObjects(options);
            self.callback = callback;
            self._options = options;
            self._init();
        },

        _init: function() {},
        _options: {}
    };

    implementations.timer = {
        _appState: undefined,
        _init: function() {
            var current_hash = locationWrapper.get();
            self._appState = current_hash;
            self.callback(current_hash);
            setInterval(self.check, 100);
        },
        check: function() {
            var current_hash = locationWrapper.get();
            if(current_hash != self._appState) {
                self._appState = current_hash;
                self.callback(current_hash);
            }
        },
        load: function(hash) {
            if(hash != self._appState) {
                locationWrapper.put(hash);
                self._appState = hash;
                self.callback(hash);
            }
        }
    };

    implementations.iframeTimer = {
        _appState: undefined,
        _init: function() {
            var current_hash = locationWrapper.get();
            self._appState = current_hash;
            iframeWrapper.init().put(current_hash);
            self.callback(current_hash);
            setInterval(self.check, 100);
        },
        check: function() {
            var iframe_hash = iframeWrapper.get(),
                location_hash = locationWrapper.get();

            if (location_hash != iframe_hash) {
                if (location_hash == self._appState) {    // user used Back or Forward button
                    self._appState = iframe_hash;
                    locationWrapper.put(iframe_hash);
                    self.callback(iframe_hash); 
                } else {                              // user loaded new bookmark
                    self._appState = location_hash;  
                    iframeWrapper.put(location_hash);
                    self.callback(location_hash);
                }
            }
        },
        load: function(hash) {
            if(hash != self._appState) {
                locationWrapper.put(hash);
                iframeWrapper.put(hash);
                self._appState = hash;
                self.callback(hash);
            }
        }
    };

    implementations.hashchangeEvent = {
        _init: function() {
            self.callback(locationWrapper.get());
            $(window).bind('hashchange', self.check);
        },
        check: function() {
            self.callback(locationWrapper.get());
        },
        load: function(hash) {
            locationWrapper.put(hash);
        }
    };

    var self = $.extend({}, implementations.base);

    if($.browser.msie && ($.browser.version < 8 || document.documentMode < 8)) {
        self.type = 'iframeTimer';
    } else if("onhashchange" in window) {
        self.type = 'hashchangeEvent';
    } else {
        self.type = 'timer';
    }

    $.extend(self, implementations[self.type]);
    $.history = self;
})(jQuery);




/*--------------------countdown.js------------------------*/ 

/*
 * Metadata - jQuery countdown plugin
 * http://alexmuz.ru/jquery-countdown/
 *
 * Copyright (c) 2009 Alexander Muzychenko
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

/*(function($) {

jQuery.fn.countdown = function (date, options) {
		options = jQuery.extend({
			lang: {
				years:   ['г.', 'г.', 'л.'],
				months:  ['м.', 'м.', 'м.'],
				days:    ['д.', 'д.', 'д.'],
				hours:   ['ч.', 'ч.', 'ч.'],
				minutes: ['м.', 'м.', 'м.'],
				//seconds: ['с.', 'с.', 'с.'],
				plurar:  function(n) {
					return (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
				}
			}, 
			prefix: "Осталось: ", 
			finish: "Всё"			
		}, options);
 
		var timeDifference = function(begin, end) {
		    if (end < begin) {
			    return false;
		    }
		    var diff = {
		    	//seconds: [end.getSeconds() - begin.getSeconds(), 60],
		    	minutes: [end.getMinutes() - begin.getMinutes(), 60],
		    	hours: [end.getHours() - begin.getHours(), 24],
		    	days: [end.getDate()  - begin.getDate(), new Date(begin.getYear(), begin.getMonth() + 1, 0).getDate() - 1],
		    	months: [end.getMonth() - begin.getMonth()-1, 12],
		    	years: [end.getYear()  - begin.getYear(), 0]
		    };
		    var result = new Array();
		    var flag = false;
		    for (i in diff) {
		    	if (flag) {
		    		diff[i][0]--;
		    		flag = false;
		    	}    	
		    	if (diff[i][0] < 0) {
		    		flag = true;
		    		diff[i][0] += diff[i][1];
		    	}
		    	if (!diff[i][0]) continue;
			    result.push(diff[i][0] + ' ' + options.lang[i][options.lang.plurar(diff[i][0])]);
		    }
		    return result.reverse().join(' ');
		};
		var elem = $(this);
		var timeUpdate = function () {
		    var s = timeDifference(new Date(), date);
		    if (s.length) {
		    	elem.html(options.prefix + s);
		    } else {
		        clearInterval(timer);
		        elem.html(options.finish);
		    }		
		};
		timeUpdate();
		var timer = setInterval(timeUpdate, 1000);		
	};
})(jQuery);*/

/*------------------zakaz-zvonka.js---------------------*/ 

$(document).ready(function(){
	
	$('#feedbackPhone #telefon').blur(function(){
		   if($("#feedbackPhone #telefon").val()==''){
			   $("#feedbackPhone #telefon").addClass('error');
		   }
		   else{
			   $("#feedbackPhone #telefon").removeClass('error');
		   }
	});

   $("#feedbackPhone .btn").live('click',function(){
       if($("#feedbackPhone #telefon").val()==''){
           $("#feedbackPhone #telefon").addClass('error');
           return false;
       }
       else{
			var form = $('#feedbackPhone');
           $("#feedbackPhone #telefon").removeClass('error');
           jQuery.ajax({
				url: '/system/zakaz-zvonka', //куда послать запрос
				type: 'POST', //тип  HTTP запроса
				data: form.serialize(),
				success: function(data) //обработчик успешного завершения запроса
				{
					//form.remove();
					//$('#zakaz_zvonka img#loader_zakaz_zvonka').css('display','none');
					//$('#zakaz_zvonka .corner-text').html(data);
					$("#feedbackPhone").fadeOut(700);
					$("#text-zvonok").html('<p>Спасибо, ваш запрос отправлен,<br /> наш менеджер свяжется с вами в течение 10 минут.<br /><br />Этот оверлей закроется через 5 секунд</p>');
					setTimeout(function() { $('#popup1').hide();$('#lightbox-overlay').fadeOut(700);$("#text-zvonok").html('<p>Спасибо, ваш запрос отправлен,<br /> наш менеджер свяжется с вами в течение 10 минут.<br /></p>'); }, 5000);
				}
			});
       }
   });

});



