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

	$("#comment").maxlength();
	$("#cf_field_4").maxlength();
	
	
	

	$('#li-3-5 span span').tooltip({
	track: true,
	delay: 0,
	showURL: false,
	showBody: " - ",
	fade: 250,
	top: -135, 
    left: -85
	});

	$('#cf3_field_1').change(function () {
		var vv = ($(this).find('option:selected').val());
		var sel2 = $('#cf3_field_2');
		if (vv=='Банан 30×40'||vv=='Банан 40×50') {
			sel2.find('option:not(:first)').removeAttr('disabled');
		}else {
			sel2.find('option:first').attr('selected','selected');
			sel2.find('option:not(:first)').attr('disabled','disabled');
		}
	}).trigger('change');


	// landing tabs 
	var $tab_menu = $('.prices-landing .tabs-menu');
	if ($tab_menu.length) {

		var lis =  $tab_menu.find('li'),
			linum = 0;
			
		var types = $('.prices-landing .type'),
			tnum = 0;
			
		
		types.each(function () {
			tnum++;
			$(this).addClass('tab-item');
			$(this).attr('id','tab-item-'+tnum);
		})
			
		lis.each(function () {
			linum++;
			var t = $(this).html();
			$(this).html('<a href="#tab-item-'+ linum +'" class="pseudo">' + t + '</a>');
			$(this).find('a').click(function (e) {
				e.preventDefault();
				lis.removeClass('current');
				$(this).parent().addClass('current');
				types.hide();
				types.filter(this.hash).show()
			//	alert(this.hash);
				
			});
		});

		$tab_menu.find('li:first a').click();

	}
	



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

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



	// поле поиска с примерами
	$('#searchform .example').find('a').click(function() { 
		$("#searchform #s").attr("value", $(this).html()); 
		$("#searchform #s").attr("class", "");
		$("#searchform #s").focus();
		
		return false;  
	});





	/* 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');
		}
	});



	

	if (document.getElementById("YMapsID")) {// Яндекс карта 
	var map = new YMaps.Map(document.getElementById("YMapsID")); 	
	map.setCenter(new YMaps.GeoPoint(35.013482,48.45928), 17);
 
	var ml = new YMaps.YMapsML('http://suvenirka.dp.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);});
	}// Яндекс карта 





	$flag = Array();
	if ($.cookie('main-cat')) {
		$className = $.cookie('main-cat');
	}
	else {
		$className = 'souvenirs';
	}
	showCat($className);
	
	
	
	function showCat ($cat) {
		var filterVal = $cat;
		$('#content.main').find('.category').each(function () {
			if(!$(this).hasClass(filterVal)){ $(this).fadeOut('normal').addClass('hidden'); }
			else { $(this).fadeIn('normal').removeClass('hidden'); }
		});
		
		$('.categories li .image').each(function () {
			if($(this).parent().parent().hasClass(filterVal)){ $(this).animate({top:"-12px"},250);$(this).parent().parent().addClass('current')}			
		});
		
	}


	$('ul.categories a').mouseover(function() {

		$flag[$(this).parent().attr('class')]=1;

		if (!$(this).parent().hasClass('current')) {
		
		$className = ($(this).parent().attr('class'));

		$(this).fadeTo(120, 100, function() { 
		
		if ($className!=$(this).parent().attr('class')) { return false;}
	 
		if ($flag[$(this).parent().attr('class')]) {
			$flag[$(this).parent().attr('class')] = 0;
			$('ul.categories .current .image').animate({top:"0"},250);
			$('ul.categories .current').removeClass('current'); 

			$(this).parent().addClass('current');

			var filterVal = $className;
			if ($(this).parent().hasClass($className)) {
         
        		 $('#content.main').find('.category').each(function () {
         			if(!$(this).hasClass(filterVal)){
         				$(this).fadeOut('fast').addClass('hidden');
         			}
         			else {
         				$(this).fadeIn('slow').removeClass('hidden');
         			}

  				  })
			}
			
			$(this).parent().find('.image').animate({top:"-12px"},250, function () {
				var filterVal = $className;
				$.cookie('main-cat', $className);
			});

			return false; 
		} 
     }); 
	}
});


$('ul.categories a').mouseout(function() {	$flag[$(this).parent().attr('class')] = 0; });


});




// 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;
	}
}




/* products gallery */

$(document).ready(function(){
        tooltip();//active les tooltip simple
        imagePreview();//active les tooltip image preview
        screenshotPreview();//active les tooltip lien avec preview
});

this.screenshotPreview = function(){
        /* CONFIG */

                xOffset = 96;
                yOffset = 30;

                // these 2 variable determine popup's distance from the cursor
                // you might want to adjust to get the right result

        /* END CONFIG */
        //$("a.screenshot").click(function () {return false;});
        
        $("a.screenshot").hover(function(e){
                this.t = this.title;
                this.title = "";
                //var c = (this.t != "") ? "" + this.t : "";
               var c=this.t;
                $("body").append("<p id='screenshot'><img src='"+ this.rel +"' alt='url preview' />"+ c +"</p>");
                $("#screenshot")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px")
                        .fadeIn("fast");
    },
        function(){
                this.title = this.t;
                $("#screenshot").remove();
    });
        $("a.screenshot").mousemove(function(e){
                $("#screenshot")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px");
        });
};
this.imagePreview = function(){
        /* CONFIG */

                xOffset = -10;
                yOffset = 0;

                // these 2 variable determine popup's distance from the cursor
                // you might want to adjust to get the right result

        /* END CONFIG */
       
        $("a.preview").hover(function(e){
                this.t = this.title;
                this.title = "";
                var alt=$(this).find('img').attr('alt');
                //var c = (this.t != "") ? "" + this.t : "";
                var c = this.t;
                $("body").append("<p id='preview'><img src='"+ this.href +"' alt='" + alt + "' /><span>"+ c +"</span></p>");
                imgw = $("#preview").width();
                pagew =  $("body").width();
                if (pagew > imgw + e.pageX) {
                	  $("#preview")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px")
                        .fadeIn("fast");
                }
                else {
                	$("#preview")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX - yOffset*2 - imgw) + "px")
                        .fadeIn("fast");
                }
              
    },
        function(){
                this.title = this.t;
                $("#preview").remove();
    });
        $("a.preview").mousemove(function(e){
        imgw = $("#preview").width();
                pagew =  $("body").width();
                if (pagew > imgw + e.pageX) {
                	  $("#preview")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px")
                        .fadeIn("fast");
                }
                else {
                	$("#preview")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX - yOffset*2 - imgw) + "px")
                        .fadeIn("fast");
                }

        
              /*  $("#preview")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px");*/
        });
         $("a.preview").click(function () {return false;});
};
this.tooltip = function(){
        /* CONFIG */
                xOffset = 0;
                yOffset = 0;
                // these 2 variable determine popup's distance from the cursor
                // you might want to adjust to get the right result
        /* END CONFIG */
        $("a.tooltip").hover(function(e){
                this.t = this.title;
                this.title = "";
                $("body").append("<p id='tooltip'>"+ this.t +"</p>");
                $("#tooltip")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px")
                        .fadeIn("fast");
    },
        function(){
                this.title = this.t;
                $("#tooltip").remove();
    });
        $("a.tooltip").mousemove(function(e){
                $("#tooltip")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px");
        });
};








/* @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;
    }
};





/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);
