

document.documentElement.className += ' has-js ';

$(function(){

	var speed = 1000,
		fast = speed/2,
		faster = speed/3,
		frontCarousel = $('.h_carousel'),
		frontSlider = frontCarousel.find('.container'),
		frontSliderMenu = frontCarousel.find('#dots a'),
		frontSliderCurrent = frontSliderFirst = frontSliderMenu.filter(':first'),
		counter = 0,
		slideInterval;
		
	$('.pr_list').masonry();
		
	/*----------------------------------------------------------------------------------- FRONT CAROUSEL */
	frontSliderMenu.each(function(){
		this.rel = ++counter;
	});
	frontSliderCurrent.addClass('active');
		
	frontSlider.jcarousel({
		scroll:1,
		animation:speed,
		easing:'easeInOutCubic',
		wrap: 'circular',
		initCallback:function(c){
			frontSliderMenu.click(function(e){
				c.scroll($.jcarousel.intval(this.rel));
				frontSliderMenu.removeClass('active');
				frontSliderCurrent = $(this);
				frontSliderCurrent.addClass('active');
				e.preventDefault();
			});
			frontCarousel.find('.left_arrow').click(function(e){
				
				frontSliderCurrent = $('#dots a.active').parent().prev().find('a');
				if (typeof frontSliderCurrent.get(0) == 'undefined'){						
					frontSliderCurrent = $('#dots a.active').parent().siblings(':last').find('a');
				}	
				frontSliderCurrent.click();
				
			});
			frontCarousel.find('.right_arrow').click(function(e){
				
				frontSliderCurrent = $('#dots a.active').parent().next().find('a');
				if (typeof frontSliderCurrent.get(0) == 'undefined'){						
					frontSliderCurrent = $('#dots a.active').parent().siblings(':first').find('a');
				}					
				frontSliderCurrent.click();
			});
		},

		buttonNextHTML:null,
		buttonPrevHTML:null
	});
	frontCarousel.hover(function(){ clearInterval(slideInterval); }, function(){ sliderAutoRotate(); });
	
	sliderAutoRotate();
	function sliderAutoRotate(){
		slideInterval = setInterval(function(){
			var next = frontSliderCurrent.parent().next().find('a');
			if(next.length==0) next = frontSliderFirst;
			next.click();
		},5000);
	}
		
	/*-------------------------------------------------------------------------------- VERTICAL CAROUSEL */
	var vCarousel = $('.category_list li .carousel'),
		vSlider = vCarousel.find('.c_container'),
		vSliderP = vCarousel.find('.up.arrow'),
		vSliderN = vCarousel.find('.down.arrow');
		
	vSlider.jcarousel({
		vertical:true,
		scroll:1,
		initCallback:function(c){
			vSliderP.click(function(e){ $(this).parent().find('.jcarousel-prev').click(); e.preventDefault(); });
			vSliderN.click(function(e){ $(this).parent().find('.jcarousel-next').click(); e.preventDefault(); });
		}
	});
		
	/*------------------------------------------------------------------------ INTERACTIVE SEARCH SLIDER */
	var iSlider = $('#interactive_search .container'),
		iSliderC = iSlider.find('.listing'),
		iSliderUL = iSliderC.find('ul'),
		iSliderI = iSliderC.find('li'),
		iSliderIW = iSliderI.width(),
		iSliderW = iSliderIW * iSliderI.length,
		iSliderW2 = iSliderW - iSliderC.width(),
		iScroll = iSlider.find('.scroll .slider'),
		iScrollW = iScroll.width(),
		iScrollA = iScroll.parent().width();
		
	iSliderC.css('width','100%');
	iSliderUL.width(iSliderW);
	
	iScroll.css('left','1px').draggable({
		axis:'x',
		containment:'parent',
		drag:function(e,ui){
			var elem = $(this),
				pos = parseInt(elem.css('left')) / (iScrollA - iScrollW);
			iSliderUL.css('margin-left','-'+(iSliderW2*pos)+'px');
		}
	});
		
	/*------------------------------------------------------------------------------ PROMOTIONS CAROUSEL */
	var promo = $('#promotions'),
		promoC = promo.find('.carousel'),
		promoP = promo.find('.arrow_left'),
		promoN = promo.find('.arrow_right');
		
	promo.jcarousel({
		scroll:1,
		wrap: 'circular',
		initCallback:function(c){
			promoP.click(function(e){ promo.find('.jcarousel-prev').click(); e.preventDefault(); });
			promoN.click(function(e){ promo.find('.jcarousel-next').click(); e.preventDefault(); });
		}
	});
			
	/*------------------------------------------------------------------------ SIMILAR PRODUCTS CAROUSEL */
	var similar = $('#product_d_c'),
		similarC = similar.find('.carousel'),
		similarP = similar.find('.left_arrow'),
		similarN = similar.find('.right_arrow');
		
	similar.jcarousel({
		scroll:1,
		initCallback:function(c){
			similarP.click(function(e){ similarC.find('.jcarousel-prev').click(); e.preventDefault(); });
			similarN.click(function(e){ similarC.find('.jcarousel-next').click(); e.preventDefault(); });
		}
	});
		
	/*-------------------------------------------------------------------------------------- FOOTER MENU */
	$('#footer .l_1').hover(
		function(){
			collapseSub($(this));
		},
		function(){
			var elem = $(this);
			elem.data('hovered',false);
			setTimeout(function(){ expandSub(elem); },1000);
		}
	).find('ul').hover(
		function(){
			collapseSub($(this).parent());
		},
		function(){
			var elem = $(this).parent();
			elem.data('hovered',false);
			setTimeout(function(){ expandSub(elem); },1000);
		}
	);
	
	function collapseSub(elem){
		elem.data('hovered',true).find('ul').slideDown(300).prev().show();
		expandSub(elem.siblings());
	}
	
	function expandSub(elem){
		if(!elem.data('hovered')) elem.find('ul').slideUp(300).prev().hide();
	}
		
	/*----------------------------------------------------------------------------------- CUSTOM SELECTS */
	$('#search select, #price_alarm select, #filter_services select').css({'opacity':0}).after('<div class="select-js"></div>').each(function(){
		var elem = $(this),label = elem.find('option:first');
		this.defaultVal = label.text();
		//label.remove();
		var div = elem.next();
		var selected = elem.find('option:selected').text();
		/*if (this.defaultVal==selected)
			div.addClass('gray');*/
		var pos = elem.position();
		div.text(selected).css({left:pos.left+'px',top:pos.top+'px'}).addClass(elem.attr('class'));
	}).change(function(){
		var div = $(this).next();
		var selected = $(this).find('option:selected').text();
		/*if (this.defaultVal==selected)
			div.addClass('gray');*/
		//else div.removeClass('gray');
		div.text(selected);
	});
		
	/*------------------------------------------------------------------------- FILTER SLOT-MACHINE-LIKE */
	var filters = $('.count ul'),
		filtersLi = filters.find('li'),
		liH = filtersLi.height();
		
	filtersLi.css({height:liH+'px',overflow:'hidden'});
	filters.each(function(){
		var elem = $(this),
			li = elem.find('li');
		
		elem.wrap('<div class="draggable-wrapper" />');
		var wrapper = elem.parent(),
			h = elem.height();
			
		wrapper.css({
			position:'absolute',
			left:0,
			top:'-'+(h-liH)+'px',
			width:'100%',
			height:(h*2)+'px'
		}).parent().css({position:'relative'});
		
		elem.css({top:(h-7)+'px'});
	}).draggable({
		grid:[liH,liH],
		axis:'y',
		scroll:false,
		containment:'parent',
		stop:function(e,ui){
			var elem = $(this),
				h = elem.height(),
				pos = parseInt(elem.css('top')),
				nth = Math.floor((h-pos)/liH)+1,
				selected;
				
			nth = nth<0 ? nth*-1 : nth;
			selected = $(this).find('li:nth-child('+nth+') input').val();
			
			// selected price callback:
			// alert(selected);
		}
	});
	
	/*------------------------------------------------------------------------ COLUMN SAME HEIGHT */
	function equalHeight(group) {
	   tallest = 0;
	   group.each(function() {
	      thisHeight = $(this).height();
	      if(thisHeight > tallest) {
	         tallest = thisHeight;
	      }
	   });
	  
	   group.height(tallest);
   
	}
	$(document).ready(function() {
		//height = $(window).	innerHeight();
		//$('.column_1').height(height);
	});
	
	$(document).ready(function() {
	   equalHeight($(".column_6"));
	});



	/*------------------------------------------------------------------------ HEADER MENU */
	
	/*$('#navigation ul .l_1 div').css('display','block');*/

	$('#navigation ul .l_1').hover(
		function(){
			totalWidth=$('body').width();
			dv=$(this).children('div');
			dv.fadeIn('fast');
			offs=(dv.width()-$(this).width())/2;
			delta1 = $(this).offset().left+$(this).width()+offs-totalWidth+15;
			delta1 = (delta1>0)?delta1:0;
			delta2 = $(this).offset().left-offs-15;
			delta2 = (delta2<0)?delta2:0;
			offs+=(delta1+delta2);
			dv.css('margin-left',-offs);
				},
		function(){
			$(this).children('div').fadeOut('fast');
				}
		);

	/*------------------------------------------------------------------------ CART UPDATE */
	
	function updatePrice(i){
		price=$('#price'+i+' .main').html().toLowerCase();
		price=price.replace('<sup>','.');
		price=price.replace('</sup>','');
		price=Math.round(price*100);
		$('#sum'+i).html(($('#qty'+i).attr('value')*price/100)+' лв');
		
		updateTotal();
	}
	
	function updateTotal(){
		totalSum=0;
		$('.cart-sum .sum').each(function(){
			totalSum+=Math.round(($(this).html().replace(' лв', ''))*100);
		});
		$('.final-sum').html(totalSum/100 + ' лв');
	}
	
	function updateQty(i,value){
			a=($('#qty'+i).attr('value')*1+value<0)?0:$('#qty'+i).attr('value')*1+value;
			$('#qty'+i).attr('value',a);
			updatePrice(i);
	}
		
	$('.cart-number .up').live('click',function(){
		updateQty($(this).parents('.row-holder').not('[rel=heading]').attr('rel'),1);
		});

	$('.cart-number .down').live('click',function(){
		updateQty($(this).parents('.row-holder').not('[rel=heading]').attr('rel'),-1);
		});
		
	$('.cart-refresh a').live('click',function(){
		updatePrice($(this).parents('.row-holder').not('[rel=heading]').attr('rel'));
	});
	
	$('.cart-number input').blur(function(){
		updatePrice($(this).parents('.row-holder').not('[rel=heading]').attr('rel'));
		});
		
	$('.cart-sum .close-btn a').live('click',function(){
		$(this).parents('.row-holder').fadeOut('slow',function(){
			$(this).remove();
			updateTotal();
		});
	});
	
	$('.cart-sum .sum').each(function(){
		updatePrice($(this).parents('.row-holder').attr('rel'));
	});
	
	updateTotal();

	/*------------------------------------------------------------------------ ORDER HISTORY */
	/*
	$('.close-btn a').live('click',function(){
		$(this).parents('.productRow').fadeOut('slow',function(){
			$(this).remove();
		});
	});
	*/
	
	//disable all text fields + textareas on load
	$('form.initDisabled input[type=text],form.initDisabled input[type=password],form.initDisabled textarea').attr('disabled','disabled').addClass('disabled');
	
	//enable all text fields on 'edit' button
	$('.formDefault .edit-btn').click(function(){
		$('.formDefault input, .formDefault textarea').removeAttr('disabled').removeClass('disabled');
		return false;
	});
	
	//disable all text fields on 'send' button
	$('.formDefault .submit').click(function(){
		$('.formDefault input, .formDefault textarea').attr('disabled','disabled').addClass('disabled');
		$(this).parents('form').submit();
	});

	
	// clear the input text on focus if the value is the default one; default value taken from attribute "default"
	$('.formDefault input[type=text]').focus(function(){
		if($(this).attr('value')==$(this).attr('default')) $(this).attr('value','');
		$(this).removeClass('default');
		});

	// revert to default value if nothing is entered; default value taken from attribute "default"
	$('.formDefault input[type=text]').blur(function(){ 
		if(jQuery.trim($(this).attr('value'))=='') {
			$(this).addClass('default');		
			$(this).attr('value',$(this).attr('default'));
		}
		});

	$('.formDefault input[type=text]').each((function(){
		if(jQuery.trim($(this).attr('value'))==$(this).attr('default')) {
			$(this).addClass('default');		
		}
		}));
		
	$('.addAddress').click(function(){
		num=$('div.address').size();
		$('div.address[rel=1]').clone().appendTo($('div.addresses')).attr('rel',(num+1));
		newName='address'+(num+1);
		$('div.address[rel='+(num+1)+'] label').attr('for',newName).removeClass('closed').next().show();
		$('div.address[rel='+(num+1)+'] label').html('Адрес '+(num+1));
		$('div.address[rel='+(num+1)+'] input').attr('id',newName);
		$('div.address[rel='+(num+1)+'] input').attr('name',newName);
		return false;
	});
	
	$('.address label').live('click',function(){
		$(this).toggleClass('closed').next().slideToggle('slow');
	})
	
	$('span.submit').click(function(){
		$(this).parents('form').submit();
		})

	/*------------------------------------------------------------------------ STORES CAROUSEL */
function mycarousel_initCallback(carousel)
	{
			// Disable autoscrolling if the user clicks the prev or next button.
			carousel.buttonNext.bind('click', function() {
				carousel.startAuto(0);
			});
		 
			carousel.buttonPrev.bind('click', function() {
				carousel.startAuto(0);
			});
		 
			// Pause autoscrolling if the user moves with the cursor over the clip.
			carousel.clip.hover(function() {
				carousel.stopAuto();
			}, function() {
				carousel.startAuto();
			});
		};		
		
	$('.thumbs').jcarousel({
		scroll:2,
		wrap:'circular',
		initCallback:mycarousel_initCallback
		});
	$('.thumbs a').click(function(){
		$(this).parents('.box-x-3').children('.mainImage').attr('href',$(this).attr('href'));
		$(this).parents('.box-x-3').children('.mainImage').children('img').attr('src',$(this).attr('href'));
		return false;
		});

	/*------------------------------------------------------------------------------ BOX CAROUSEL HORIZONTAL */

	$('.corporate .box .carousel').jcarousel({
		scroll:1,
		wrap:'circular',
		initCallback:mycarousel_initCallback
		});

	/*------------------------------------------------------------------------------ BOX CAROUSEL VERTICAL (CART) */

	$('.corporate #login .cart').jcarousel({
		scroll:1,
		wrap:'circular',
		vertical: true,
		initCallback:mycarousel_initCallback
		});

		
	/*------------------------------------------------------------------------ ACCORDIONS */
	
	$('.accordion .expandable').css('display','none');
	$('.accordion .switch').click(function(){
			$(this).parent().toggleClass('open');
			$(this).next().slideToggle('slow')
	});


	$('.logos li').hover(
		function(){
			$(this).children('div').fadeIn('fast');
		},
		function(){
			$(this).children('div').fadeOut('fast');
		}
	);


	$('#start-order #login a:first').click(function(){
		$('#start-order #new-pass').toggle();
	});

});


$(document).ready(function(){
	

	/* ------------------------------------------------------------------------- MENU REARRANGE */
	
	
	var rowHeight=20; // if no padding and other shit, should be the same as line-height value
	var maxHeight=330; // max height of the column
	var maxRows=Math.floor(maxHeight/rowHeight);

	$('#navigation').find("dl").each(function(){
		
		 //alert('w: '+$(this).width());
		var cnt=0;
		$("<div class='column'></div").insertBefore($(this));
		var div_column=$("div.column").last();

		$("dt,dd",this).each(function(){
								 
			if($(this).is("dt")){
				if(maxRows-cnt==1){
					$("<div class='column'></div").insertAfter(div_column);
					div_column=$("div.column").last();
					cnt=0;
				}
				$(this).appendTo(div_column);
				cnt++;
				//console.log(cnt+" - "+maxRows);
				if(cnt==maxRows){
					$("<div class='column'></div").insertAfter(div_column);
					div_column=$("div.column").last();
					cnt=0;
				}
				
			}
			else { // <dd> - has an <ul> with lots of <li>s
				div_column.append("<dd><ul></ul></dd>");
				var ul=$("ul:last",div_column);
				$("li",$(this)).each(function(){
					$(this).appendTo(ul);
					cnt++;
					if(cnt==maxRows){
						$("<div class='column'></div").insertAfter(div_column);
						div_column=$("div.column").last();

						div_column.append("<dd><ul></ul></dd>");
						ul=$("ul:last",div_column);
						
						cnt=0;
					}
				});
			}
		});
		
		$(this).remove();
	});
	$('#navigation ul div').show();
	$('#navigation ul div').each(function(){
		var w=0;
		var h=0;
		if($(this).find('.column').length>0){
			$(this).find('.column').each(function(){
				w+= $(this).outerWidth();
					if($(this).height()>h){
						h=$(this).height();
					}
				});
			$(this).find('.column').css('height', h+'px');																						  
			$(this).css('width', w+'px');
		}
		//$(this).find('.column').each(function(){$(this).css('width', '');});
	});
	$('#navigation ul div').hide();
	$('#navigation ul div .column').show();


});



