
var shk_timer;

$.fn.setCounterToField = function(opt){
    var imgpath = 'img/';
    function checkKey(e){
        var key_code = e.which ? e.which : e.keyCode;
        return (key_code>47&&key_code<58)||key_code==8 ? true : false;
    }
    function changeCount(field,action){
        var count = parseInt($(field).attr('value'));
        var num = action==1 ? count+1 : count-1;
        if(num>=1)
            $(field).val(num);
    }
    var countButs = '<img class="field-arr-up" src="'+imgpath+'arr_up.gif" width="17" height="9" alt="" />'
    + '<img class="field-arr-down" src="'+imgpath+'arr_down.gif" width="17" height="9" alt="" />'+"\n";
    $(this).each(function(){
        var field = $(this);
        $(this)
        .after(countButs)
        .keypress(function(e){return checkKey(e);});
        $(this).next('img').click(function(){
            changeCount(field,1);
        })
        .next('img').click(function(){
            changeCount(field,2);
        });
    });
}


$.fn.tabs = function(){
    var parent = $(this);
    var tabNav = $('ul:first',this);
    var tabContent = $('div.tab-content',this);
    $('a',tabNav).each(function(i){
        $(this).click(function(){
            $('li',tabNav).removeClass('active');
            $('li',tabNav).eq(i).addClass('active');
            tabContent.hide();
            tabContent.eq(i).show();
            return false;
        });
    });
}

$.fn.activate = function(option){
    var opt = $.extend({'elem':'a'},option);
    var parent = $(this);
    $(opt.elem, parent).each(function(i){
        $(this).click(function(){
            $(opt.elem,parent).removeClass('active');
            $(this).addClass('active');
            return false;
        });
    });
}

$.fn.overlayFit = function(opt){
    var overlay = $(this);
    overlay.css({'width': $(window).width()+'px', 'height': $(document).height()+'px'});
    $(opt.wrapper).css({'height':$(window).height()+'px'});
    $(window).bind('resize',function(){
        overlay.css({'width': $(window).width()+'px', 'height': $(document).height()+'px'});
        $(opt.wrapper).css({'height':$(window).height()+'px'});
    });
}
$.fn.alignCenter=function(){
    var marginLeft=Math.max(40,parseInt($(window).width()/2-$(this).width()/2))+'px';
    var marginTop=Math.max(40,parseInt($(window).height()/2-$(this).height()/2)) + $(window).scrollTop() +'px';
    return $(this).css({
        'margin-left':marginLeft,
        'margin-top':marginTop
    });
};
var gallery1, gallery2;

function noGoodBrowser(){
    if($.browser.msie){
        return $.browser.version=='7.0' || $.browser.version=='6.0';
    }else{
        return false;
    }
}

$.fn.zoomIcn = function(opt){
    
    //var options = $.extend({},opt);
    $('div.close a','#gallery-win').click(function(){
        $('#gallery-win-wrapper').hide();
        $('#overlay').remove();
        
        if(!noGoodBrowser())
            $(document.body).css({'overflow':'auto'});
        else
            $('html').css({'overflow':'auto'});
        
        var selectedIndex = $('#thumbs_big li.selected').prevAll().size();
        gallery1.gotoIndex(selectedIndex);
        return false;
    });
    
    $(this).each(function(){
        
        $('img',this).live('mouseover',function(){
            var img = $(this);
            var pos = $(this).offset();//position();
            var i_width = img.width();
            var i_height = img.height();
            var window_height = $(window).height();
            $(document.body).append('<a href="#" id="zoomIcn"></a>');
            $('#zoomIcn').css({
                'left':pos.left+'px',
                'top':pos.top+'px',
                'width': i_width+'px',
                'height': i_height+'px'
            })
            .fadeIn(300);
            $('#zoomIcn')
            .click(function(){
                $(document.body).append('<div id="overlay"></div>');
                var selectedIndex = $('#thumbs li.selected').prevAll().size();
                var win_height = 700;//$('#gallery-win').height();
                var doc_height = $(document).height();
                var yScroll = $.browser.msie ? document.documentElement.scrollTop : self.pageYOffset;
                //var top_pos = win_height<window_height ? (window_height - win_height)/2 : ((window_height - win_height)/2) + yScroll + (win_height - window_height)/2;
                var top_pos = ((window_height - win_height)/2) + yScroll + (win_height - window_height)/2;
                var top_pos2 = win_height<window_height ? (window_height - win_height)/2 : 0;
                var pos_style = !noGoodBrowser() ? 'fixed' : 'absolute';//win_height<window_height /*&& (!$.browser.msie || ($.browser.msie && $.browser.version=='9.0'))*/ ? 'fixed' : 'absolute';
                var win_overflow = window_height < doc_height ? 'scroll' : 'hidden';
                if(top_pos<0 || pos_style == 'fixed') top_pos = 0;
                //if(!$.browser.msie){
                //$(document.body).css({/*'height':'100%',*/'overflow-y':(window_height < $(document).height() ? 'scroll' : 'hidden')});//'overflow':(window_height < win_height ? 'visible' : 'hidden')
                if(!noGoodBrowser()) $(document.body).css({'height':'100%','overflow':'hidden'});
                else $('html').css({'overflow':'hidden'});
                //}
                gallery2.gotoIndex(selectedIndex);
                $('#overlay').overlayFit({'wrapper':'#gallery-win-wrapper'});
                $('#gallery-win-wrapper')
                .css({'position':pos_style,'top': top_pos+'px','overflow-y':win_overflow})
                .show();
                $('#gallery-win').css({'top':top_pos2+'px'}).fadeIn(500);
                $('#overlay').show();//fadeIn();
                return false;
            })
            .mouseout(function(){
                $(this).stop().fadeOut(300,function(){
                    $(this).remove();
                });
            });
        });
        
    });
}


function winSizeAlign(){
    if($(window).width()<1100) $('div.catalog-products li').css('width','24%');
    else $('div.catalog-products li').css('width','19%');
}



$(document).bind('ready',function(){
  
    if($('#tabs').size()>0) $('#tabs').tabs();
  
    // if($('#scrollBrands').size()>0){
    //   $('#scrollBrands').smoothDivScroll({
    //     autoScroll: "onstart",//always
    //     autoScrollDirection: "backandforth",
    //     autoScrollStep: 0,
    //     autoScrollInterval: 15,
    //     mouseDownSpeedBooster: 1,
    //     visibleHotSpots: "always",
    //     scrollableArea: "div.scrollablearea",
    //     scrollWrapper: "div.scrollwrapper"
    //   });
    // }
  
  
  
  
 
//проверка электронной почты перед допуском в оформление заказа
  
  $("#mailInform")
  .unbind('submit')
  .live('submit',function(){
   var tmp = document.getElementById("usrnm");
   var loc = document.getElementById("locurl");
   var inc = document.getElementById("mincor");
   var loco = document.getElementById("locurlto");
   var loct = document.getElementById("locurltt");
   var uname = "url="+site_url+"&name="+tmp.value;
 
   $.ajax({
 		 url: site_url+'tsn', 
		 type: "post",
		 data: uname, 
		 dataType: 'html',
		 success: function(response){
           if(response == '<p>in</p>'){
 		    	$(".infrmans").text(loco.value);
		    	return false;             
           }else if(response == '<p>notin</p>'){
		    	//window.location.href = '/'+loc.value;
				document.forms["mailInform"].submit();
           } else if(response == '<p>incorrect</p>'){
				$(".infrmans").text(inc.value);
		   } else {alert(response);}
         },
		 beforeSend: function(){
            $(".infrmans").text(loct.value);
 		 },
		 error: function() {
			$(".infrmans").text(loco.value);
			return false;
		 }
	});
	
    return false;
  });    
  
  
    //авторизация и напоминание пароля
    $("#loginfrm, #loginreminder")
    .unbind('submit')
    .live('submit',function(){
        var as_params = $(this).serialize()+"&ajax_submit=#weblogin_alert";
        var thisForm = $(this);
		var loc = document.getElementById("locurl");
        $.ajax({
            url: window.location.href,
            type: "post",
            data: as_params,
            dataType: 'html',
            success: function(response){
                if(response=='success'){
				    if (window.location.href == site_url+'basket/products'){
						window.location.href = '/'+loc.value;
					} else {
						window.location.reload();
					}
                }else if(response.length > 0){
                    if($('#weblogin_alert').size()>0)
                        $('#weblogin_alert').html(response);
                    else
                        thisForm.parent().parent().prepend('<p id="weblogin_alert">'+response+'</p>');
                }
            },
            error: function(jqXHR,textStatus,errorThrown){
            //alert(textStatus+' '+errorThrown);
            }
        });
        return false;
    });
  
    //проверяем доступность оператора в чате
    $.ajax({
        url: site_url+'chat/_available.php',
        type: "post",
        data: {},
        dataType: 'html',
        success: function(response){
            var available = response==1;
            var available_txt = available ? 'В сети' : 'Не в сети';
            $('#chat_available').html(available_txt);
            if(!available) $('#chat_available').prev().prev().removeClass('green-js-link').addClass('gray-js-link');
        }
    });

    $('select[name="time_from"]').change(function() {
        $("option",this).each(function(i) {
            if($(this).is(':selected')) {
                var flag = false;
                $('select[name="time_to"] option').each(function(j) {
                    if($(this).is(':selected')) {
                        if(i > j){
                            flag = true;                            
                        }
                    }
                    if(i == j && flag == true) {
                        $(this).attr("selected","selected");
                    }
                });
            }
        });
    });

    $('select[name="time_to"]').change(function() {
        var time_to = $('option:selected', this).val();
        var time_from = $('select[name="time_from"] option:selected').val();
        var time_to_int = parseInt(time_to.substr(0,2));
        var time_from_int = parseInt(time_from.substr(0,2));

        if((time_to_int - time_from_int) < 3) {
            $('select[name="time_from"] option[value="'+(time_to_int - 3)+':00"]').attr("selected","selected");
        }
    });

    /*$('select[name="time_from"]').change(function() {
        $("option",this).each(function(i) {
            if($(this).is(':selected')) {

                $('select[name="time_to"] option').each(function(j,from) {

                        if(i == j){
                            $(from).attr("selected","selected");                            
                        }

                });
            }
        });
    });

    $('select[name="time_to"]').change(function() {
        $("option",this).each(function(i) {
            if($(this).is(':selected')) {

                $('select[name="time_from"] option').each(function(j,from) {

                        if(i == j){
                            $(from).attr("selected","selected");                            
                        }

                });
            }
        });
    });*/


    /*$('#menuSubmit a').click(function() {
        if($(this).parent().hasClass('last')) {
            if($(this).parent().hasClass('active')) {
                return false;
            } else {
                $('#orderForm form').submit();
                return true;
            }
        } else {
            if($(this).parent().hasClass('active')) {
                return false;
            } else {
                window.location.href = $(this).attr('href');
                $('#orderForm form').submit();
                return true;
            }
        }
    });*/

//$(document).bind('ready',winSizeAlign);
//$(window).bind('resize',winSizeAlign);

    bind_event();
  
});

function bind_event(){
    $('.shk-count_').each(function(index, el){
    /*$(el).bind('change',function(){
        var value = $(el).val();
        var re = /^[0-9]*$/;
        if (value < 0 || !re.test(value)){
            $(el).val('1');
        }
    })*/
    // когда пользователь отпускает клавишу клавиатуры
    jQuery(el).bind('keyup', function(event){checkNumberFields(this, event, index);})
    // когда пользователь нажимает клавишу клавиатуры и удерживает её в нажатом состоянии
    .bind('keypress',function(event){checkNumberFields(this, event, index);})
    // когда поля теряет фокус
    .bind('focusout',function(event){checkNumberFields(this, event, index);})
    //.bind('change',function(event){checkNumberFields(this, event, index);})
    /*.bind('click',function(){this.select();})*/;
});
}

function checkNumberFields(e, k, idx){
	
	var str = jQuery(e).val();
	var new_str = s = "";
	
	for(var i=0; i < str.length; i++){
		
		s = str.substr(i,1);
		
		if(s!=" " && isNaN(s) == false){// если цифра
			new_str += s;
		}
	}
	if(eval(new_str) <= 0){new_str = "1";}
	if(k.type == "focusout" && new_str == ""){new_str = "1";}
        if((k.type == "change" && new_str != "") || ((k.type == "keypress" && new_str != "") && k.keyCode == 13 || (k.keyCode >= 48 && k.keyCode <= 57) || (k.keyCode >= 96 && k.keyCode <= 105))){
            recountItem_new(idx,parseInt(new_str));
        }
	jQuery(e).val(new_str);
	
}

function recountItem_new(num,count){
        //var thisAction = function(){
            $.showLoading_new(true);
            var getParams = '&action=recount&index='+num+'&count='+count+$.getSettings_qs();
            ajaxRequest_new(getParams,num);
            if(shkOpt.debug){
                log.debug('recountItem_new(): num:'+num+', count:'+count);
            }
        //}
        
}

function ajaxRequest_new(params,index,refresh){
        shkOpt = $.getshkOpt();
        var idx_delivery = -1;
        var idx_payment = -1;
        $('input[name="delivery"]').each(function(idx,el){
            if($(el).attr('checked') == 'checked')
                idx_delivery = idx;
        });
        $('input[name="payment"]').each(function(idx,el){
            if($(el).attr('checked') == 'checked')
                idx_payment = idx;
        });
        
        if(typeof(refresh)=='undefined') var refresh = true;
        if(shkOpt.debug){
            log.debug('ajaxRequest_new(), params='+params);
        }
        $.ajax({
            type: "POST",
            cache: false,
            url: site_url+'assets/snippets/shopkeeper/ajax-action.php',
            data: params+'&lang='+shkOpt.lang+'&idx_d='+idx_delivery+'&idx_p='+idx_payment,
            /*dataType: "json",*/
            success: function(data){
                $.showLoading_new(false);
                if(refresh){
                    if(window.location.href.indexOf('/'+shkOpt.orderFormPage)>-1){
                        $('#butOrder').hide();
                    }
                    var cartHeight = $('#shopCart').height();
                    $('#shopCart').replaceWith(data);
                    cart_doc_ready();
                    var req_error = $('#req_error').val();
                    var req_success = $('#req_success').val();
                    var req_inventory = $('#req_inventory').val();
                    var req_idx_d = $('#req_idx_d').val();
                    var req_idx_p = $('#req_idx_p').val();
                    if(req_error.length > 0)
                    {    
                        $('.error_inventory').each(function(idx, el){
                            if(idx == index){
                                $(el).children('.msg_block').children('#inv_msg').html(req_error);
                                $(el).children('.msg_block').children('#inv_count').html('');
                                $(el).fadeIn(300);
                                $(el).children('a').bind('click', function(){
                                    $(el).fadeOut(300);
                                });
                            }
                        });
                        
                    }    
                    else if(req_success.length > 0 && req_inventory.length > 0){
                        $('.shk-count_').each(function(idx, el){
                            if(idx == index)
                                $(el).val(req_inventory)
                        });
                        $('.error_inventory').each(function(idx, el){
                            if(idx == index){
                                $(el).children('.msg_block').children('#inv_msg').html(req_success);
                                $(el).children('.msg_block').children('#inv_count').html(req_inventory);
                                $(el).fadeIn(300);
                                $(el).children('a').bind('click', function(){
                                    $(el).fadeOut(300);
                                });
                                return false;
                            }
                        });
                        $('input[name="delivery"]').each(function(idx,el){
                            if(idx == parseInt(req_idx_d))
                                $(el).trigger('click');
                        });
                        $('input[name="payment"]').each(function(idx,el){
                            if(idx == parseInt(req_idx_p))
                                $(el).trigger('click');
                        });
                    }
                    $.setCartActions_new();
                    var cartheightNew = $('#shopCart').height();
                    bind_event();
                //animCartHeight(cartHeight,cartheightNew);
                }
            }
            ,
            error: function(jqXHR, textStatus, errorThrown){
                alert(textStatus+' '+errorThrown);
            }
        });
}

function ajaxRequest_new_all(refresh){
        shkOpt = $.getshkOpt();
        var idx_delivery = -1;
        var idx_payment = -1;
        $('input[name="delivery"]').each(function(idx,el){
            if($(el).attr('checked') == 'checked')
                idx_delivery = idx;
        });
        $('input[name="payment"]').each(function(idx,el){
            if($(el).attr('checked') == 'checked')
                idx_payment = idx;
        });
        var params = '&action=recount_all'+$.getSettings_qs();
        if(typeof(refresh)=='undefined') var refresh = true;
        if(shkOpt.debug){
            log.debug('ajaxRequest_new_all(), params='+params);
        }
        $.ajax({
            type: "POST",
            cache: false,
            url: site_url+'assets/snippets/shopkeeper/ajax-action.php',
            data: params+'&lang='+shkOpt.lang+'&idx_d='+idx_delivery+'&idx_p='+idx_payment,
            success: function(data){
                $.showLoading_new(false);
                if(refresh){
                    if(window.location.href.indexOf('/'+shkOpt.orderFormPage)>-1){
                        $('#butOrder').hide();
                    }
                    var cartHeight = $('#shopCart').height();
                    $('#shopCart').replaceWith(data);
                    cart_doc_ready();
                    var req_error = $.parseJSON($('#req_error_json').html());
                    var req_success = $.parseJSON($('#req_success_json').html());
                    var req_inventory = $.parseJSON($('#req_inventory_json').html());
                    var req_idx_d = $('#req_idx_d').val();
                    var req_idx_p = $('#req_idx_p').val();
                    if(typeof(req_error) == "object")
                    {    
                        $('.error_inventory').each(function(idx, el){
                            if(typeof(req_error[idx]) != 'undefined'){
                                $(el).children('.msg_block').children('#inv_msg').html(req_error[idx]);
                                $(el).children('.msg_block').children('#inv_count').html('');
                                $(el).fadeIn(300);
                                $(el).children('a').bind('click', function(){
                                    $(el).fadeOut(300);
                                });
                            }
                        });
                        window.scroll(0,0);
                    }    
                    else if(typeof(req_success) == "object" && typeof(req_inventory) == "object"){
                        $('.shk-count_').each(function(idx, el){
                            if(typeof(req_inventory[idx]) != 'undefined')
                            {    
                                $(el).val(req_inventory[idx]);
                            }   
                        });
                        $('.error_inventory').each(function(idx, el){
                            if(typeof(req_success[idx]) != 'undefined'){
                                $(el).children('.msg_block').children('#inv_msg').html(req_success[idx]);
                                $(el).children('.msg_block').children('#inv_count').html(req_inventory[idx]);
                                $(el).fadeIn(300);
                                $(el).children('a').bind('click', function(){
                                    $(el).fadeOut(300);
                                });
                            }
                        });
                        window.scroll(0,0);
                    }
                    else
                    {
                        $.setCartActions_new();
                        var cartheightNew = $('#shopCart').height();
                        cart_doc_ready();
                        bind_event();
                        $('input[name="delivery"]').each(function(idx,el){
                            if(idx == parseInt(req_idx_d))
                                $(el).trigger('click');
                        });
                        $('input[name="payment"]').each(function(idx,el){
                            if(idx == parseInt(req_idx_p))
                                $(el).trigger('click');
                        });
                        var check = $('#login_bigwin').attr('id');
                        if (check == 'login_bigwin') 
                        {
                            $('#login_bigwin').show();
                            return false;
                        }
                        else
                        {
                            $('#ordForm').submit();
                            return false;
                        }
                    }    
                    $.setCartActions_new();
                    var cartheightNew = $('#shopCart').height();
                    cart_doc_ready();
                    bind_event();
                    $('input[name="delivery"]').each(function(idx,el){
                        if(idx == parseInt(req_idx_d))
                            $(el).trigger('click');
                    });
                    $('input[name="payment"]').each(function(idx,el){
                        if(idx == parseInt(req_idx_p))
                            $(el).trigger('click');
                    });
                    
                //animCartHeight(cartHeight,cartheightNew);
                }
            }
            ,
            error: function(jqXHR, textStatus, errorThrown){
                alert(textStatus+' '+errorThrown);
                //return false;
            }
        });
}

function changeDelivery(mode) {
    $('#orderForm a.dost, #orderForm a.samo, #orderForm a.dostUSA').removeClass('active');
    
    if(mode == '1') {
        $('#orderForm a.dost').addClass('active');
        $('#orderForm .samo-hidden').addClass('hidden');
        $('#orderForm .dostUSA-hidden').addClass('hidden');
        $('#orderForm .dost-hidden').removeClass('hidden');
        $('input#delivery').val('1');

    } else if(mode == '2') {
        $('#orderForm a.samo').addClass('active');
        $('#orderForm .samo-hidden').removeClass('hidden');
        $('#orderForm .dost-hidden').addClass('hidden');
        $('#orderForm .dostUSA-hidden').addClass('hidden');
        $('input#delivery').val('0');
    } else if(mode == '3') {
        $('#orderForm a.dostUSA').addClass('active');
        $('#orderForm .dostUSA-hidden').removeClass('hidden');
        $('#orderForm .dost-hidden').addClass('hidden');
        $('#orderForm .samo-hidden').addClass('hidden');
        $('input#delivery').val('0');
    }

    return false;
}

function copyData() {
    $('input[name="city"]').val($('input[name="cityMoskov"]').val());
    $('input[name="address"]').val($('input[name="addressMoskov"]').val());
}

