

$(document).ready(function() {
	count=$('#countimgs').val();
	val=$('#i').val();
	hidelinks(count,val);
	
	$("#trmenu").treeview({animated: "fast",  collapsed: true,persist: "location"});
	
	//Set Default State of each portfolio piece
	$(".paging").show();
	$(".paging .link_paging:first").addClass("active");
		
	//Get size of images, how many there are, then determin the size of the image reel.
	var imageWidth = $(".window").width();
	var imageSum = $(".image_reel img").size();
	var imageReelWidth = imageWidth * imageSum;
	
	//Adjust the image reel to its new size
	$(".image_reel").css({'width' : imageReelWidth});
	
	//Paging + Slider Function
	rotate = function(){	
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".paging .link_paging").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
		
		//Slider Animation
		$(".image_reel").animate({ 
			left: -image_reelPosition
		}, 500 );
		
	}; 
	
	//Rotation + Timing Event
	rotateSwitch = function(){		
		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
			$active = $('.paging .link_paging.active').next();
			if ( $active.length === 0) { //If paging reaches the end...
				$active = $('.paging .link_paging:first'); //go back to first
			}
			rotate(); //Trigger the paging and slider function
		}, 7000); //Timer speed in milliseconds (3 seconds)
	};
	
	rotateSwitch(); //Run function on launch
	
	//On Hover
	$(".image_reel a").hover(function() {
		clearInterval(play); //Stop the rotation
	}, function() {
		rotateSwitch(); //Resume rotation
	});	
	
	//On Click
	$(".paging .link_paging").click(function() {	
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});	
	
});

function InputHelperIn ( obj, text )
	{
	    //если при фокусе значение поля равно значению подсказки, то чистим его и вешаем стили
		if ( obj.value == text )
		{
		    $( obj )
		        .css ( { color: '#000', fontStyle: 'normal', font: 'Arial' } )
		        .val ( '' );
		}
	}
	
	function InputHelperOut ( obj, text )
	{
	    //если при потере фокуса значение поля равно пустоте или значению по умолчанию,
            //то пихаем в него текст подсказки и вешаем стили подсказки
		if ( obj.value == '' || obj.value == text )
		{
		    $( obj )
		        .css ( { color: '#aaa', fontStyle: 'normal' } )
		        .val ( text );
		}
	}
	
	function InputHelperCreate ( obj, text )
	{
	    //вешаем на поле эвенты. На фокус и потерю фокуса.
		$( obj )
			.bind ( 'focus', function () {
				InputHelperIn ( this, text );
			} )
			.bind ( 'blur', function () {
				InputHelperOut ( this, text );
			} );
			
		//первоначальный инит
		InputHelperOut ( obj, text );
	}

	$( document ).ready ( function () {
	    //пробегаемся по всем текстовым полям и колдуем над ними
	    InputHelperCreate ( $( 'input.search_input' ).get( 0 ), 'Поиск товаров...' );
	} );
	
function moveleft(){
	margin=$('#hcont').css('margin-left');
	margin=parseInt(margin,10);
	newmargin=margin+74;
	count=$('#countimgs').val();
	val=$('#i').val();
	
	$('#hcont').animate({marginLeft: newmargin},300);
	$('#i').attr('value',+val-1);
	//alert(val-1);
	hidelinks(count,val-1);
}

function moveright(){
	margin=$('#hcont').css('margin-left');
	margin=parseInt(margin,10);
	newmargin=margin-74;
	count=$('#countimgs').val();
	val=$('#i').val();
	
	$('#hcont').animate({marginLeft: newmargin},300);
	$('#i').attr('value',+val+1);
	//alert(val-1);
	hidelinks(count,val+1);
}

function hidelinks(count,val){
	
	if (+val>=0){
		$('.mini-img-right-cur').css('display', 'inline');
		$('.mini-img-left-cur').css('display', 'none');
	}
	
	if(+val>=+count-3){
		$('.mini-img-right-cur').css('display', 'none');
		$('.mini-img-left-cur').css('display', 'inline');
	}
	
	if (+val>0 && +val<+count-3){
		$('.mini-img-right-cur').css('display', 'inline');
		$('.mini-img-left-cur').css('display', 'inline');
	}
	if (count<=3){
		$('.mini-img-right-cur').css('display', 'none');
		$('.mini-img-left-cur').css('display', 'none');
	}
	
}

function showbigimg(img){
	$("#bimg").load("/catalog/getbimg", { 'pic': img});
}

function sortbypriceasc(){
		cururl=$('#cururl').val();
		
		$.post("/catalog/productssortby", { subject: 'pasc'});
		//window.location.replace(baseurl+"admin/products/");
		window.location.replace(cururl);
	
}

function sortbypricedesc(){
	cururl=$('#cururl').val();
	
	$.post("/catalog/productssortby", { subject: 'pdesc'});
	//window.location.replace(baseurl+"admin/products/");
	window.location.replace(cururl);

}

function sortbynothing(){
	cururl=$('#cururl').val();
	
	$.post("/catalog/productssortby", { subject: 'title'});
	//window.location.replace(baseurl+"admin/products/");
	window.location.replace(cururl);

}

function sortbysklad(){
    cururl=$('#cururl').val();

    $.post("/catalog/productssortby", { subject: 'col_on_skl'});
    //window.location.replace(baseurl+"admin/products/");
    window.location.replace(cururl);
}

function CheckByButton(){
	CurSpDost=$('#spdost').val();
	
	
	dostcity=$('#dostcity').val();
	spdost2=$('#spdost2').val();
	region=$('#region').val();
	
	if(CurSpDost!='0' && CurSpDost!=''){
		
		
		if(CurSpDost=='3'){
			
			err=0;
			if (dostcity==''){
				alert('Необходимо указать город для доставки');
				err=1;
			}
			if (spdost2=='' || spdost2=='0'){
				alert('Необходимо указать способ доставки доставки');
				err=2;
			}
			
			if(err!=0){
				return;
			}
		}
		//action
		
		$.post("/shop/buy/"+CurSpDost+"/", { spdost1:CurSpDost, city: dostcity, spdost2: spdost2, region: region},function(data){
			if(data=='not_authorize'){
				window.location.replace("/auth/cart_login/");
			}else if(data=='err_min_sum'){
				alert('Сумма заказа меньше минимально установленой.');
			}else if(data=='success'){
				window.location.replace("/profile/orders/");
			}else{
				alert('Ошибка'+data);
				
				//window.location.replace("/profile/orders/");
			}
		});
		//window.location.replace("/profile/orders/");
		
	}else{
		alert('Сначала необходимо выбрать тип доставки.');
	}
	
}


function CheckOtherCity(){
	CurSpDost=$('#spdost').val();
	if (CurSpDost=='3'){
		//$('.dosthidden').css('display', 'inline');
		$('.dosthidden').slideDown(300);
		$('#stdostspan').text('Стоимость доставки расчитывается отдельно');
	}else{
		//alert('asd');
		$('.dosthidden').slideUp(300);
		$.post("/shop/getdostprice/", { 'dosttype': CurSpDost}, function(data){
			//alert(data);
			$('#stdostspan').replaceWith("<span id='stdostspan'>"+data+"</span>");
			//$('#stdostspan').html(data);
		});
		//$('#stdostspan').load("/shop/getdostprice/", { 'dosttype': CurSpDost } );
	}
	
	
}

function printContent(divtoprint){
	var DocumentContainer = document.getElementById(divtoprint);
	var WindowObject = window.open("", "PrintWindow","width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
	WindowObject.document.writeln("<html><head><link href='/css/style.css' type='text/css' rel='stylesheet'></head><body style='background: #fff;'>");
	WindowObject.document.writeln(DocumentContainer.innerHTML);
	WindowObject.document.writeln("</body></html>");
	WindowObject.document.close();
	WindowObject.focus();
	WindowObject.print();
	WindowObject.close();
}
