function ChangeBudget1(id,prefix){
    $('#budget_limit'+prefix).attr('disabled', 'disabled');
    $('#budget_range'+prefix).attr('disabled', 'disabled');
    $('#'+id+prefix).removeAttr('disabled');
}

function t_subcat(sid){
	if('cat' == document.getElementById(sid).className){
		document.getElementById(sid).className = 'cat op';
		document.getElementById(sid + 'b').style.display = 'block';
	} else {
		document.getElementById(sid).className = 'cat';
		document.getElementById(sid + 'b').style.display = 'none';
	}
}

function maxlength(text_el, count_el, maxvalue) {
	var el = document.getElementById(text_el);
  	var count = parseInt(el.value.length);
	if(count > maxvalue) {
		el.value = el.value.substr(0, maxvalue);
	}
	document.getElementById(count_el).innerHTML = el.value.length;
}

function changeKidsCount(select){
    var count = jQuery(select).val();
    if(count == 0){
        $('table#kids').hide();
    }else{
        $('table#kids').show();
        for(var i = 1; i<=15;i++){
            if(i<=count){
                $('tr#kid'+i).show();
            }else{
                $('tr#kid'+i).hide();
            }
        }
    }
}
function changeCatalogNumber(){
    var catNum = product_id+'_'+size_id+'_'+color_id;
    $('#catalog_number').html(catNum);
}
function SetSelectedColor(id){
    $('div.colors').children('div.selected').removeClass('selected');
    $('#color'+id).addClass('selected');
    color_id = id;
    if(size_id == 0){size_id = '000';}
    changeCatalogNumber();
}
function SetSelectedSize(select){
    size_id = jQuery(select).val();
    var obj = window['colors_'+size_id];
    var temp = obj.color;
    var first_div = $('div.colors div:first-child');
    first_div.unbind('click');
    first_div.siblings('div.color').remove();
    var first_image = first_div.children(':first');
    var cur_div = first_div;
    var cur_image = first_image;
    for ( var i in temp ){
        cur_image.attr('alt',temp[i].name);
        cur_image.attr('src',temp[i].image);
        cur_div.attr('id','color'+temp[i].value);
        if(i != temp.length -1){
        cur_div.after(first_div.clone());
        cur_div = cur_div.next();
        cur_div.removeClass('selected');
        cur_image = cur_div.children(':first');
        }
    }
    $('div.color').click(function(){
        var id = $(this).attr('id');
        id = id.substr(5);
        SetSelectedColor(id);
    })
    first_div.addClass('selected');
    first_div.click();
    if(color_id==''){color_id='000';}
    changeCatalogNumber();
}

function changeImage(src,indx){
    big_image_index = indx-1;
    $('#image-large').attr('src',src);
}

function manageCount(order,delta){
    var input = $('#product_quantity_'+order);
    var current = input.val();
    $.get('ajax.php',{action:'manageCount',order:order,current:current,delta:delta},
        function(data){
            input.val(data);
            productSum(order,data);
            sumProductsValues();
        });
}
function productSum(order){
    var count = $('#product_quantity_'+order).val();
    var additional = parseFloat($('#additional_charge_'+order+'>span').text());
    if(!additional){additional = 0;}
    $('#sum_'+order).html(roundM(parseFloat(count) *
        (parseFloat($('#price_'+order).html()) +additional)
        )
    );
}
function removeProductFromCart(order){
    $.get('ajax.php',{action:'removeProductFromCart',order:order},
        function(data){
            $(".tr_"+order).remove();
            sumProductsValues();
        });
}
function changeDeliveryType(noresum){
    var type = $('#delivery_type3').val();
    var price = parseFloat($('#products_sum').text());
    $.ajax({url:'ajax.php'
        ,data:{action:'chnageDeliveryType',type:type,price:price}
        ,async:false
        ,success:function(data){
            js_delivery_price = parseFloat(data);
            var delivery_price = $('.special_delivery_price').maxValue();
            if(delivery_price==0){
                $('#delivery_type1').hide();
                $('#delivery_type1').attr('disabled','disabled');
                if(free_shipping == 0){
                    delivery_price += parseFloat(js_delivery_price);
                    $('#delivery_type2').hide();
                    $('#delivery_type2').attr('disabled','disabled');
                    $('#delivery_type3').show();
                    $('#delivery_type3').attr('disabled','');
                }else{
                    $('#delivery_type3').hide();
                    $('#delivery_type3').attr('disabled','disabled');
                    $('#delivery_type2').show();
                    $('#delivery_type2').attr('disabled','');
                }
            }else{
                $('#delivery_type1').show();
                $('#delivery_type1').attr('disabled','');
            }
            $("#delivery_price").text(roundM(delivery_price));
        }
    });
}
function deliveryPrice(){
    changeDeliveryType();
}
function sumProductsValues(){
    $('#products_sum').text(roundM($('.product_sum').sumValues()));
    deliveryPrice();
    makeDiscount();
    var sum = roundM($('.totals').sumValues());
    if(sum>=0){
        $('#total_sum').text(sum);
    }else{
        $('#total_sum').text(0);
    }

}

function makeDiscount(){
    var discount = 0;
    if(const_discount < 0){
        discount += parseFloat(const_discount);
    }
    if(percent_discount>0){
        var sum = parseFloat($('#products_sum').text());
        discount += -sum * percent_discount / 100;
    }
    $('#discount_price').text(roundM(discount));

    if(free_shipping==1){
        js_delivery_price = 0;
        deliveryPrice();
    }
}

function addDiscount(input){
    var code = input.val();
    $.getJSON('ajax.php',{action:'addDiscount',code:code},
        function(data){
            if(data.error){
                $('#code_discount_error').text(data.error);
            }else{
                switch(data.type){
                    case 3:
                        var disc = parseFloat($('#discount_price').text());
                        $('#discount_price').text(disc - parseFloat(data.value));
                        const_discount -=data.value;
                        break;
                    case 2:
                        percent_discount += data.value;
                        break;
                    case 1:
                        if(roundM($('.special_delivery_price').sumValues())>0){
                            alert(data.alert);
                        }
                        free_shipping = 1;
                        break;
                }
                $('#shopping_bonus').html(data.out);
                sumProductsValues();
            }
        });
}
function roundM(number){
    return Math.round(number*100)/100;
}

$.fn.sumValues = function() {
	var sum = 0;
    var val = '';
	this.each(function() {
		if ( $(this).is(':input') ) {
			val = $(this).val();
		} else {
			val = $(this).text();
		}
		sum += parseFloat( (val).replace(/[^0-9-\.]/g, ''), 10 );
	});
	return sum;
};

$.fn.maxValue = function() {
	var max = 0;
    var val = '';
	this.each(function() {
		if ( $(this).is(':input') ) {
			val = $(this).val();
		} else {
			val = $(this).text();
		}
        val = parseFloat( (val).replace(/[^0-9-\.]/g, ''), 10 );
        if(val > max){
            max = val
        }
	});
	return max;
};

function getSubcategories(){
    var category_id  = $('#category').val();
    $.get('ajax.php', {action:'getSubcategories', category_id: category_id},
        function(data){
            $('#subcategories').html(data);
        }
    );
}

function changeSize(order){
    $("#form_size_"+order).change(function(){
        $("#form_color_"+order).removeOption(/./);
        $("#form_color_"+order).addOption(window["colors_"+order+'_'+$(this).val()], false);
        var cat_num = $('#catalog_number_'+order).text();
        var cat = cat_num.split('_');
        cat[1] = $(this).val();
        cat[2] = '000';
        $('#catalog_number_'+order).text(cat.join('_'));
        $.get('ajax.php',{action:'changeCartSize',order:order,size:$(this).val()},
        function(){
           changeAdditionCharge(cat[1],cat[2],order);
        });
    });
}
function changeColor(order){
    $("#form_color_"+order).change(function(){
        var cat_num = $('#catalog_number_'+order).text();
        var cat = cat_num.split('_');
        cat[2] = $(this).val();
        $('#catalog_number_'+order).text(cat.join('_'));
        $.get('ajax.php',{action:'changeCartColor',order:order
            ,color:$(this).val()},
        function(data){
           changeAdditionCharge(cat[1],cat[2],order);
        });
    });
}
function changeAdditionCharge(size,color,order){
    var val = window['add_charge_'+parseInt(size)+'_'+parseInt(color)];
     if(val >0){
                $('#additional_charge_'+order).show();
                $('#additional_charge_'+order+'>span').text(val);
            }else{
                $('#additional_charge_'+order).hide();
                $('#additional_charge_'+order+'>span').text('0');
            }
    productSum(order);
    sumProductsValues();
}

function saveCustContentEvent(order,cust_id){
    $('#form_'+order+'_'+cust_id).blur(function(){
       saveCustContent(order,cust_id,$(this).val());
    });
}
function saveCustContent(order,cust_id,value){
    $.get('ajax.php',{action:'saveCustContent',order:order
           ,cust_id:cust_id,value:value});
}
function giftCardSpecialPrice(order,cust_id,value,min,max){
   $(document).ready(function(){
    $('#form_'+order+'_'+cust_id).spinner({min: min
        , max: max
        , className: "price-gift-card"
        , increment: 'fast'});
    $('#form_'+order+'_'+cust_id).spinner("value", value);

    $('#form_'+order+'_'+cust_id).change(function(){
        var value = $(this).spinner('value');
        if(isNaN(value)){
            value = min;
        }else if(value > max){
            value = max;
        }
        $('#form_'+order+'_'+cust_id).val(value);
        $('#price_'+order).text(parseFloat(value));
        productSum(order);
        sumProductsValues();
        $(this).val(value);
    });
});
}
function giftCardShippingType(order,cust_id,type){
    var current = $('input[name="gift_card_shipping_type_'+order+'"]');
    var email_title = current.parent().next().next();
    var email_field = current.parent().next().next().next();
    var address_title = email_field.next().next();
    var address_field = email_field.next().next().next();
    if(type==1){
        email_title.hide();
        email_field.hide();
    }else{
        address_title.hide();
        address_field.hide();
    }
    current.click(function(){
       if($(this).attr('id')=='form_gift_card_shipping_type_'+order+'0'){
           address_title.hide();
           address_field.hide();
           email_title.show();
           email_field.show();
       }else{
           address_title.show();
           address_field.show();
           email_title.hide();
           email_field.hide();
       }
       $.get('ajax.php',{action:'saveCustContent',order:order,cust_id:cust_id,value:$(this).val()});
    });
}
function saveCardText(){
    $('#form_card_text').blur(function(){
       $.get('ajax.php',{action:'saveCardText',value:$(this).val()});
    });
    $('#form_gift_packaging').click(function(){
       $.get('ajax.php',{action:'saveGiftPackaging',value:$(this).is(':checked')});
    });
}
function showAddressForm(){
    $('.address-verify').hide();
    $('#address-change').hide();
    $('#payment-address').show(600);
}
function closeAddressForm(){
    $('#payment-address').hide();
    $('#address-change').show(600);
    $('#payment-address form').get(0).reset();
    $.get('ajax.php',{action:'removeAddressForm'});
}
function submitAddressForm(submitPage){
    var tmp = true;
    var tmp1 = true;
    if(!submitPage){
       tmp =  EmptyTextValidator();
    }else{
        if($('#form-payment-address').find('#form_name').val()==''){
            tmp1 = false;
        }else{
            tmp = EmptyTextValidator();
        }
    }
    if(tmp && tmp1){
    $.ajax({
        type: "POST",
        url: "ajax.php?action=submitAddressForm",
        data: $('#form-payment-address').serialize(),
        dataType: "json",
        success: function(msg){
            if(msg.message){
                $('.address-verify > div :first').html(msg.message);
                $('.address-verify').show();
                $('#payment-address').hide();
                $('#errors').hide();
                if(msg.popup){
                    $.colorbox({html:'<p>'+msg.popup+'</p>'});
                }
//                js_unusual_additional_price = parseFloat(msg.unusual_additional_price);
                deliveryPrice();
            }else if(msg.errors){
                $('#errors').show();
                $('#errors').html(msg.errors);
            }
       }
     }
    );
    }
    return tmp;
}

function selectPaymentType(select){
    if(select.val() == 1){
        $('.payment-by-phone').hide();
        $('.payment-by-card').show();
    }else if(select.val() == 2){
        $('.payment-by-card').hide();
        $('.payment-by-phone').show();

    }
}
function showSecondLvlMenu(start){
    if(start.next().is(':hidden')){
        start.next().show();
    }else{
        start.next().hide();
    }
}

function showHideBrandDescription(div,show){
    var container = $('#global_description');
    if(show == 1){
        var text = div.siblings('.localdescription').text();
        var title = div.siblings('.supplier-title').text();
        if(text != ''){
            container.find('h4').text(title);
            container.find('span.content').text(text);
            container.show();
            var offset = div.offset();
            var width = div.width();
            var height = div.height();
            offset.left +=roundM(width/2 - 70)
            offset.top += roundM(height*(2/3) + 20);
            container.css('left', offset.left);
            container.css('top', offset.top);

        }else{
            return false;
        }
    }else{
        container.hide();
    }
    return true;
}
function send_cooperation(){
    if(EmptyTextValidatorcoop()==true){
    $.ajax({
        type: "POST",
        url: "ajax.php?action=Coop",
        data: $("#coop_form").serialize(),
        dataType: "json",
        success: function(msg){
            if(msg.success!=""){
                $('#coop_message').show();
                $('#coop_message').html(msg.success);
                $('#coop_errors').hide();
                $('#div_form').hide();
            }else{
                $('#coop_errors').show();
                $('#coop_errors').html(msg.errors);
                $('#coop_message').hide();
            }
        }
     }
    );
    }
}
function removeProductFromWishlist(wishlist,id){
    $('#prtr_'+id).remove();
    $.get('ajax.php',{action:'removeProductFromWishlist',wishlist:wishlist,id:id});
}
function removeWishlist(wishlist){
    $('#wltr_'+wishlist).next().remove();
    $('#wltr_'+wishlist).remove();
    $.get('ajax.php',{action:'removeWishlist',wishlist:wishlist});
}
function addToWishList(){
    var catalogNumber = $.trim($('#catalog_number').text());
    var link = $('a.addtowishlist');
    var href = link.attr('href');
    href = href.split('?',1);
    link.attr('href', href+'?cat_num='+catalogNumber);
    link.colorbox();
}
function addToCart(product_id){
   var cat_num = $.trim($('#catalog_number').text());
   var link = "add_to_cart.php?add="+product_id+"&cat_num="+cat_num;
   window.location= link;
}
function saveForWishlist(checkbox){
    alert(checkbox.is(':checked'));
    if(checkbox.is(':checked')){
        $.get('ajax.php',{action:'saveForWishlist',order:checkbox.val(),value:1});
    }else{
        $.get('ajax.php',{action:'saveForWishlist',order:checkbox.val(),value:0});
    }
}
function successPopup(backUrl){
   $(window).load(function() {
        $.colorbox({inline:true
            ,height: 200
            ,innerWidth: 300
            ,href:'#success'
            ,onClosed: function(){
                if(backUrl != ''){
                    window.location =  backUrl;
                }
            }
        });
    });
}
function disabledAdressForm(){
    if($('#form_name').val() == ''){
        $('#form-payment-address input:not(#form_name)').attr('disabled','disabled');
        $('#form-payment-address input:submit').switchClass("address-submit", "address-submit-disabled", 1);
    }else{
        $('#form-payment-address input:disabled').attr('disabled','');
        $('#form-payment-address input:submit').switchClass("address-submit-disabled", "address-submit", 1);
    }
}
