passstr = 'Парола';

$(document).ready(function() {
	
	$('.submitHolder,.submBt').hover(function(){$(this).addClass('submHover')},function(){$(this).removeClass('submHover')});
	$('.loginForm .input,.searchHolder .input').each(function(){
		if($(this).attr('type')=='password'){
			if($(this).val()==''){$(this).watermark(passstr)}
		}
		else{$(this).watermark($(this).val())}
	});
	$("input.paswordMark").change(function(){
		if($(this).val()==''){$(this).watermark(passstr)}
	})
	
	$('.teaserMain').cycle({
		fx:     'fade',
		speed:  'slow',
	    timeout: 8000,
		pause: 1,
		before:  onBefore
	});
	
	$('#carouselList').jcarousel();
	//$('.pageContent 3sd3x').each(function(){$(this).width($('img',this).width()+12)})
	$('.accentContent').each(function(){
		$('.accentDescription',$(this)).height(211-($('.partRight',$(this)).height()+50))	;
	});
	
	$('select.selectCustomStyle').styledSelect();
	
	$('.profileTable .odd').each(function(){
		var maxHeight = 0;
		$('td div',$(this)).each(function(){
			if($(this).height()>maxHeight){maxHeight = $(this).height()}
		})
		
		$('td div',$(this)).each(function(){
			var paddB = (maxHeight - $(this).height())/2 + 4;
			$(this).css('padding-bottom',paddB) 
		})
	})
	
	
	$('.decreaseCount').click(function(e){changeAmount(-1,$(this));e.preventDefault()})
	$('.increaseCount').click(function(e){changeAmount(1,$(this));e.preventDefault()})
	$('.removeProduct').click(function(){ 
	    deleteCartProduct($(this));
	});
	setAmControl();
	
	$("#deliveryPrice").change(function(){	
			var thisval = $(this).val()
			var valstr = $(this).val();
			var valarr = valstr.split("||");
			var name = valarr[0]
			var price = valarr[1]
			$('#deliveryData').slideUp('normal',function(){
				if(thisval!='noSelected'){
					$('.name div',$(this)).text(name);
					$('.price div',$(this)).text(price);
					$('.deliveryPrice .value').text(price);
					$(this).slideDown('normal');
					setTotal();
				}	
			})
	});
    
		$("#firm_r").change(function(){
		if($(this).attr("checked") == true){
			$(".hideInputs").show("normal");
			$("label[for='IN_number']").html("ИН:<span class=\"required\">*</span>");
			$("#IN_number").attr("name","IN_number");
		}
	});
	$("#private_r").change(function(){
		if($(this).attr("checked") == true){
			$(".hideInputs").hide("normal");
			$("label[for='IN_number']").html("ЕГН:<span class=\"required\">*</span>");
			$("#IN_number").attr("name","EGN")
			
		}
	});
	$('.video').click(function(){
		$('#embedContent').modal({
			opacity:70,
			overlayCss: {backgroundColor:"#000"},
			overlayClose:true,
			closeHTML: "<a class='modalCloseImg' href='#'></a>"

		});
	})
	
	$("#sendToFriendButton").click(function(){
	    $("#sednToFriendForm").submit();
	});
	
	$('.share').click(function(){
		$('#emailFriendWrapper').modal({
			opacity:70,
			overlayCss: {backgroundColor:"#000"},
			overlayClose:true,
			closeHTML: "<a class='modalCloseImg' href='#'></a>"

		});
	})
	
	$('.viewMoreProducts').click(function(e){
		$('.viewMoreProducts').toggleClass('active')
		$('#accessoaries').slideToggle('normal',function(){});
		
		e.preventDefault();
	})
	
	
	var mrgL = $('.loginLoged').width() - $('.userHalloMessage').width()
	$('.bottomLinksLoged').css('margin-left',mrgL)
	$('iframe').load(function(){$(this).height($('.contentHolder').height()-7)})
	
	
	var loginError=$("#loginErrors1").html();
	if (loginError != '' && loginError != null){
	   return create({modal: true}, loginError, 'Грешка при вход');
	}
	
	var success_message=$("#success_message").html();
	if (success_message != '' && success_message != null){
	   return create({modal: true}, success_message, 'Благодаря Ви');
	}
	var error_message=$("#error_message").html();
	if (error_message != '' && error_message != null){
	   return create({modal: true}, error_message, 'Грешка');
	}

     $('.pageContent .imageHolder').each(function(){
     	if($('img',$(this)).width()>145){
     	   
     	      $(this).width($('img',$(this)).width()+12)
     	}
     	else{
     	     if($('img',$(this)).width()>0){
     	    $(this).width(157);
     	     }else{$(this).width($('iframe',$(this)).width()+12)}
     	}
     })	
     
     $("#adressProfile").change(function(){
         var selectVal=$(this).val();
         $("#userAdressesMainDiv").slideUp('normal');
         $(".userAdressDiv").slideUp('normal');
         $("#userAddress_"+selectVal).slideDown('normal');
         $(".deliveryPriceDiv").slideUp('normal');
         $("#deliveryPrice_"+selectVal).slideDown('normal');
         $("#userAdressesMainDiv").slideDown('normal');
         
         var courierId=$("#deliveryPriceSelect_"+selectVal).val();
         var location=$("#currentLocation_"+selectVal).text();
         var weight=$("#order_weight").val();
         changeDeliveryPrice(courierId, location, weight);
         
     });
     
     $(".deliveryPriceSelect").change(function(){
         var courierId=$(this).val();
         var element_id=$(this).parent().attr('id');
         var addressId=element_id.split('_')[1];
         var location=$("#currentLocation_"+addressId).text();
         var weight=$("#order_weight").val();
         changeDeliveryPrice(courierId, location, weight);
     });
     
     $("#invoiceProfile").change(function(){
         var selectVal=$(this).val();
         $("#invoiceMainDiv").slideUp('normal');
         $(".invoiceTypeDiv").slideUp('normal');
         $("#invoiceType_"+selectVal).slideDown('normal');
         $("#invoiceMainDiv").slideDown('normal');
         
     });
     
     $(".statFilter").change(function(){
         $(this).parent().parent().submit();
     });
     
     $("#deleteAllCartProducts").click(function(){
         deleteCartProduct('all');
     });
});

function changeDeliveryPrice(courierId, location, weight){
    $.post("/ajax_module", { "courier_id" : courierId, 'location' : location, "weight" : weight }, function (data, textStatus) {
		if (1 === data.status) {
		    $(".deliveryPrice .value").text(data.deliveryPrice);
		    $(".totalValue .value").text(data.total_price);
		    $("#deliveryData .price div").text(data.deliveryPrice);
		    $("#deliveryData .name div").text(data.courier_name);
		}
		else {
			alert('Sorry we can\'t do action in this moment!');
		}
	}, "json");
	return false;
}

function create(options, custom_text, custom_title) {
  options = $.extend({title: custom_title}, options || {});
  var dialog = new Boxy('<div style="min-width: 300px; min-height: 73px;"><p>'+custom_text+'</p></div>', options);
  return false;
}

function changeAmount(dir,object){
	//var curamm = parseFloat($('.number',object.parent()).text())
	//var newAmm = curamm + dir;
	//$('.number',object.parent()).text(newAmm)
	
	//setTotal();
	
	item_id_row=object.parent().parent().parent().attr('id');
	item_id=item_id_row.split('_')[1];
	
	
	if (dir == 1)
	   amountKeyword='amountPlus';
    else
       amountKeyword='amountMinus';
	$.post("/cart/"+amountKeyword+"-"+item_id, { }, function (data, textStatus) {
		if (1 === data.status) {
		    //$('.price_all',$(this).parent().parent()).text(data.product_amount_price);
		    $('#'+item_id_row+' .price_all').text(data.product_amount_price);
		    $('.number',object.parent()).text(data.product_amount);
		    $('#totalValue').text(data.total_price);
		    $('#countProducts').text(data.products_count);
		    $('.total_price').text(data.total_price);
		    setAmControl();
		}
		else {
			alert('Sorry we can\'t do action in this moment!');
		}
	}, "json");
	return false;
}

function deleteCartProduct(object){
	//var curamm = parseFloat($('.number',object.parent()).text())
	//var newAmm = curamm + dir;
	//$('.number',object.parent()).text(newAmm)
	
	//setTotal();
	
	if (object != 'all'){
    	item_id_row=object.parent().parent().attr('id');
    	item_id=item_id_row.split('_')[1];
	} else {
	    item_id='all';
	}
	
	
	$.post("/cart/del-"+item_id, { }, function (data, textStatus) {
		if (1 === data.status) {
		    $('#totalValue').text(data.total_price);
		    $('#countProducts').text(data.products_count)
		    $('.total_price').text(data.total_price) 
		    
    	    if (data.products_count == 0){
    	        $(".cart_list").fadeOut("slow", function(){
        	        $(".cart_list").slideUp("slow", function(){
        	            $(".cart_list").remove();
        	            $("#cartButtonsArea").remove();
        	            $("#cart_sec").append("<h3>Количката е празна</h3>");
        	        });
        	    });
    	    } else {
    	        object.parent().parent().fadeOut("slow", function(){
        	        object.slideUp("slow", function(){
        	            object.remove();
        	            
        	        });
        	    });
    	    }
		}
		else {
			alert('Sorry we can\'t do action in this moment!');
		}
	}, "json");
	return false;
}

function setTotal(){
	var Total = 0;
	$('.amountControl').each(function(){
		var amount = parseFloat($('.number',$(this)).text())
		var onepr = parseFloat($('.one_price',$(this).parent().parent()).text().replace(" ",""))
		var curprice = amount*onepr;
		
		$('.price_all',$(this).parent().parent()).text(curprice+" лв.");
		
		Total += parseFloat($('.price_all',$(this).parent().parent()).text());
	})
	$('.total_price').text(Total+' лв.') 
	var subTotal = parseFloat($('.deliveryPrice .value').text())+Total;
	$('.totalValue .value').text(subTotal+' лв.')
}

function setAmControl(){
	$('.amountControl').each(function(){
		var amount = parseFloat($('.number',$(this)).text())
		if(amount==1){$('.decreaseCount',$(this)).css('display','none')}
		else{$('.decreaseCount',$(this)).css('display','block')};
		var mrgL = (($(this).parent().width())-$(this).width())/2;
		$(this).css('margin-left',mrgL);
	})
}

function fixPrice(price){
    tmpPrice=price;
    price=price+'';
    if (price.indexOf('.') != -1){
        peny=price.split('.')[1];
        if (peny.length == 1){
            tmpPrice=tmpPrice+'0';
        }
    } else {
        tmpPrice=tmpPrice+'.00';
    }
    
    return tmpPrice;
}


function onBefore(){}
