$(document).ready(function(){
	searchField();

	$("#comment").maxlength();
	$("#cf_field_4").maxlength();
	
	
	$('.accordion .content').hide();
	/*
	
	$('.accordion li').hover(function(){
		$(this).addClass('active');
		setTimeout(function() { rollAccordion() }, 1000);
		
    },
    	function () {
    		// $('.accordion .content').slideUp();
    		$(this).removeClass('active');
    	}
    );

	function rollAccordion (a) {
		$('.accordion .current .content').slideUp();
		$('.accordion .active').addClass('current');
		$('.accordion .active .content').slideDown();
		$('.accordion .active').removeCLass('active');
		return false;
	}

*/

	function highlightAlt () {
		$('table.zebra').each(function () {
			var i = 0;

			$(this).find('tr').each(function () {
				i++;

				if (i%2) {
					$(this).addClass('alt');				
				}		
    		});    	
    	});
	}
	highlightAlt ();

	
	$('.glossary .term').click(function(){
		
		if ($(this).hasClass('expanded')) {
			$(this).next().slideUp();
			$(this).removeClass('expanded')
		}
		else {
			$(this).addClass('expanded');
			$(this).next().slideDown();
		}

		return false;
		
    },
    	function () {
    		
    	}
    );

	$('#expand-all').click(function () {
		
		if ($(this).find('span').html()!='Свернуть все') {
	
			$('.glossary .term').addClass('expanded');
			$('.glossary dd').slideDown();
		
			$(this).find('span').html('Свернуть все');
		
		}
		else {
		
			$('.glossary .term').removeClass('expanded');
			$('.glossary dd').slideUp();
		
			$(this).find('span').html('Развернуть все');
		}
		
		return false;
	
	});



	// cforms widget
	if ($('#cformsform')) {
	$('body').append('<div id="fader" class="hidden">&nbsp;</div>' );
	$('body').append($('.widgetcform form'));
	$('#cformsform').append($('.widgetcform .cf_info'));
	$('#cformsform').append('<span class="btn-close" title="Закрыть это окно">Закрыть</span>');

	$('#cformsform .btn-close').click( function () {
		$('#cformsform').toggle();
		$('#fader').toggle();
	});
	
	
	$('.widgetcform h3').click(function () {
      $('#cformsform').toggle();
      $('#fader').toggle();
      $('#fader').css("height",$(document).height()); 
    });
    
    } // cforms widget




	/* products list view switcher */
	$('.products-list-menu h3').each(function () {
		if ($.cookie($(this).attr('id'))=='expanded') {
			$(this).parent().find('.container').show();
			$(this).addClass('expanded');
		}
	
	});
	$('.products-list-menu h3').click(function () {
		if (!$(this).hasClass('expanded')) {
			//$('.products-list-menu .container').hide('fast');
			//$('.products-list-menu h3').removeClass('expanded');
		
			$(this).parent().find('.container').show('fast');
			$(this).addClass('expanded');
			$.cookie($(this).attr('id'), 'expanded');	
		}
		else {
			//$('.products-list-menu .container').hide('fast');
			$(this).removeClass('expanded');
			$(this).parent().find('.container').hide('fast');
			$.cookie($(this).attr('id'), 'collapsed');
		}
	});


	var i=0;
	$('#products-block .product').each(function () {
		$(this).css({zIndex: 10-i});
		
		//$(this).css({left: (-i*100 + 200) + 'px'});
		//$(this).width($(this).width() - (3-i)*100);
		//$(this).attr('position', -i*100 + 200);
		
		var contWidth = $('#products-block .wrap').width();
		
		var increment = Math.floor((2-i)*10*contWidth/100);
		
		$(this).css({left: increment + 'px'});
		$(this).width(contWidth - increment + 'px');
		$(this).attr('position', increment);
		$(this).attr('i', i);
		
		if (i==0){
			$(this).find('.descr').show();
		}
		else {	
			$(this).click(function () {
				rollOutProductInfo($(this));
			});
		}
		i++;
	});
	
	function rollOutProductInfo(product) {
		hideInfo (product.prev());
		hideInfo (product.prev().prev());

		rollRight (product.prev());
		rollRight (product.prev().prev());
		
		showInfo (product);


		product.unbind('click');
		
		product.prev().unbind('click'); 
		product.prev().click(function () {rollInProductInfo($(this));});
		
		product.prev().prev().unbind('click'); 
		product.prev().prev().click(function () {rollInProductInfo($(this));});
	}

	function rollInProductInfo(product) {
	
		hideInfo (product.next());
		hideInfo (product.next().next());
		
		rollLeft(product);
		rollLeft(product.next());
		
		showInfo (product);

		product.unbind('click');
		
		product.next().unbind('click'); 
		product.next().click(function () {rollOutProductInfo($(this));});
		
		product.next().next().unbind('click');
		product.next().next().click(function () {rollOutProductInfo($(this));});

	}
	
	function hideInfo (product) {
		product.find('.descr').animate({opacity: 0},200).delay(200).hide(200);
		//product.find('.descr').delay(400).animate({display:'none'},200);
	}

	function rollRight(product) {
		var rightEdge = $('#products-block').width()- 200 - product.attr('i')*110;
		//var pos = product.offset();
		
		//product.css({left: pos.left });
		//product.animate({left: rightEdge + 'px',width:'160px'},400);
		
		product.animate({left: rightEdge + 'px'},400);
		
		//product.delay(200).animate({left: rightEdge + 'px',width:'160px'},400);
	}
	function rollLeft (product) {
	//	var rightEdge = $('#products-block').width()-200;
	//	product.animate({left: product.attr('position') + 'px', width: rightEdge - (300 - product.attr('position'))+'px'},400);
		
		var contWidth = $('#products-block .wrap').width();

		product.animate({left: product.attr('position') + 'px', width: contWidth - product.attr('position') + 'px'},400);
		
	}
	
	function showInfo (product) {
		product.find('.descr').delay(200).css({display:'block',opacity:0}).show().animate({opacity: 1},200);
	}
	


	$('.promo .letters i').each (function () {
		var r = Math.floor(Math.random()*9)-9;
		$(this).css('top',r);	
	});
	
	$('.promo a').hover (function () {
	
		$('.promo .letters i').each (function () {
			var r = Math.floor(Math.random()*9)-9;
			$(this).animate({top: r},250);
		});
	
	
	});
	



	if (document.getElementById("YMapsID")) {// Яндекс карта 
	var map = new YMaps.Map(document.getElementById("YMapsID")); 	
	map.setCenter(new YMaps.GeoPoint(35.03409845129883,48.460946699380855), 17);

	var ml = new YMaps.YMapsML('http://artmedia-c.com.ua/address.xml');
    map.addOverlay(ml);
	
	map.addControl(new YMaps.Zoom()); 
	map.addControl(new YMaps.ScaleLine()); 

	YMaps.Events.observe(ml, ml.Events.Fault, function (error) {alert('Произошла ошибка: ' + error);});
	}// Яндекс карта 



});




// table of contents 
	function tableOfContents() {
		var tbl='<div class="sidebar contents"><ol>';
		var n=0;
		$('.entry-content').find('h3').each ( function () {
			n++;
			$(this).attr('id','section'+n);

			tbl += '<li><a href="#section' + n + '" class="pseudo-link">' + $(this).html() + '</a></li>' ;
		});
		tbl +='<ol></div>';
		$('.entry-content').prepend(tbl);
	}






// maxlength для текстовых полей
jQuery.fn.maxlength = function(options) {

  var settings = jQuery.extend({
    maxChars: 2048,
    leftChars: "осталось символов:"
  }, options);

  // выполняем плагин для каждого объекта
  return this.each(function() {
    // определяем объект
    var me = $(this);
    // определяем динамическую переменную колличества оставшихся для ввода символов
    var l = settings.maxChars;
    // определяем события на которые нужно реагировать
    me.bind('keydown keypress keyup',function(e) {
      // если строка больше maxChars урезаем её
      if(me.val().length>settings.maxChars) me.val(me.val().substr(0,settings.maxChars));
      // определяем колличество оставшихся для ввода сиволов
      l = settings.maxChars - me.val().length;
      // отображаем значение в информере
      
      if(l<100) {
      	me.next('br').next('small').attr("class", "maxlen");
      }
      else {
		me.next('br').next('small').attr("class", "hidden");
      }
      me.next('br').next('small').html(settings.leftChars + ' ' + l);
		 
    });
    // вставка информера после объекта
    me.after('<br /><small class="maxlen">' + settings.leftChars + ' ' + settings.maxChars + '</small>');
    me.next('br').next('small').attr("class", "hidden");
  });
};



function searchField () {// крутое поле поиска
	var s=document.getElementById('s');
	if (s) {
	var DEF_VAL = "поиск";
	var AUTOSAVE_URL = "belbiy.com";
	var NUM_RESULTS = 5;
	var isSafari = ((parseInt(navigator.productSub)>=20020000)&&(navigator.vendor.indexOf("Apple Computer")!=-1));
	if (isSafari) {
		s.setAttribute('type', 'search');
		s.setAttribute('placeholder', DEF_VAL);
		s.setAttribute('autosave', AUTOSAVE_URL);
		s.setAttribute('results', NUM_RESULTS);
	} 
	else {
		s.onfocus = function() { 
			if (this.value==DEF_VAL) {
				this.value = '';
				this.className="";
			}
		};
		s.onblur  = function() { 
			if (this.value=='') {
				this.value = DEF_VAL;
				this.className="empty";
			}
		};
		if (s.value=='') {
			s.value = DEF_VAL;
			s.className="empty";
		}
	}
	}
}



/* Anchor Slider */
$(document).ready(function(){
  $('a[href*=#]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname) {
      var $target = $(this.hash);
      $target = $target.length && $target
      || $('[name=' + this.hash.slice(1) +']');
      if ($target.length) {
        var targetOffset = $target.offset().top;
        $('html,body')
        .animate({scrollTop: targetOffset}, 500);
       return false;
      }
    }
  });
});


/*  « ctrl » navigation */
document.onkeydown = NavigateThrough;
var isCtrl = false; 

$(document).keyup(function (e) { if(e.which == 17) isCtrl=false; }).keydown(function (e) { if(e.which == 17) isCtrl=true;}); 

function NavigateThrough (event) {
	var link;
	if (event.ctrlKey) {isCtrl=1;}
	if (isCtrl) {
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
			case 0x25:
				link = $('.nav-previous a').attr("href");
				break;
			case 0x27:
				link = $('.nav-next a').attr("href");
				break;
	}
	if (link) document.location = link;
	}
}










/* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options);
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { 
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



/* pause function */
$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};
