/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( fx.state == 0 ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
            }

            fx.elem.style[attr] = "rgb(" + [
                Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255]
    function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
            return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Look for rgba(0, 0, 0, 0) == transparent in Safari 3
        if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
            return colors['transparent'];

        // Otherwise, we're most likely dealing with a named color
        return colors[jQuery.trim(color).toLowerCase()];
    }

    function getColor(elem, attr) {
        var color;

        do {
            color = jQuery.curCSS(elem, attr);

            // Keep going until we find an element that has color, or we hit the body
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break;

            attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
    };

    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0],
        transparent: [255,255,255]
    };

})(jQuery);
$(document).ready(function(){
    
    $.fn.animateHighlight = function (highlightColor, duration) {
        var highlightBg = highlightColor || "#FF0000";
        var animateMs = duration || 1000;
        var originalBg = this.css("background-color");

        if (!originalBg || originalBg == highlightBg)
            originalBg = "#FFFFFF"; // default to white

        jQuery(this)
            .css("backgroundColor", highlightBg)
            .animate({backgroundColor: originalBg}, animateMs, null, function () {
                jQuery(this).css("backgroundColor", originalBg); 
            });
    };
    
    // ПНГ фикс
    //$('#head, #window, #menu_top, #slider, .cat_index, .wholesale, .middle-table, .window .close').supersleight();

    // Placeholder
    $('input:text,textarea').placeholder();

    $('.cat_slider, .catalog_list li, .basket .items li, #cat_pos_carousel_container, .favorites').hover(
        function(){
            $(this).addClass('hover');
            $('#toolbar .in_basket.openbox .inner');
        },
        function(){
            $(this).removeClass('hover');
            $('#toolbar .in_basket.openbox .inner');
        }
        );

    // Меню ховер
    $('#menu_top .mt-el').not('.sel').hover(
        function(){            
           
            //$(this).html('<table class="select"><tr><td class="sel-left">&nbsp;</td><td class="sel-inn">'+inner+'</td><td class="sel-right">&nbsp;</td></tr></table>');
            $(this).addClass('hover');
        },
        function(){
            $(this).removeClass('hover');
        //$(this).html($('.sel-inn',inner).html());
        }
        );

    // $('.white_box .inner').css('height', $('.middle-content').outerHeight());

    // Зебра
    $(".catalog_list .sizes tr:nth-child(odd)").addClass("odd");


    $('.win_reg .reg_choice input:radio').change(function(){
        $('.win_reg .reg_choice .check').removeClass('check');
        $(this).parents('.item').addClass('check');
    });

    $('.win_reg .reg_choice input:checked').parents('.item').addClass('check');


    // Окна
    $('.catalog_item .image a').click(function(){
        win_show('#window_image',true);
        return false;
    });
    
    $('.button_faq a').click(function(){
        win_show('#window_feedback',true);
        return false;
    });
    
    $('#toolbar .city a').click(function(){
        win_show('#window_cities',true);
        return false;
    });
    
    $('#toolbar .control a').not('.disabled').click(function(){
        win_show('#window_login',true);
        return false;
    });
    
    $('#window_login .button_registred').click(function(){
        $('#window_login').fadeOut();
        win_show('#window_registred',false);
        return false;
    });
    
    $('.window .back_link').click(function(){
        $('.window').fadeOut();
        win_show('#window_login',false);
        return false;
    });
    
    $('#window_registred .button_next').click(function(){
        $('.window').fadeOut();
        $.post(site_home + 'registration?opt=' + $('.isopttype:checked').val(), {
            ajax:1
        }, function(data) {
            $('#regformajax').html(data);
            win_show('#window_registred_form',false);
        });
      
        return false;
    });
    
       //IE auth
    if ($.browser.msie && $.browser.version == 9){
        $('#window_login .button_login').click(function(){
        window_close();
        return false;
    });
    }
    if ($.browser.msie && $.browser.version == 8){
        $('#window_login .button_login').click(function(){
        window_close();
        return false;
    });
    }

    

    $(".change_city").click(function(){
        set_current_city($(this).text());
        window_close();
        return false;
    });

    $("#city_manual").submit(function(){
        if(!$("#city_manual_name").val() || $("#city_manual_name").val()==$("#city_manual_name").attr("placeholder")){}
        else{
            set_current_city($("#city_manual_name").val());
        }
        window_close();
        return false;
    });

    // Закрыть окно
    $('.window .close').click(function(){
        $(this).parents('.window').fadeOut(function(){
            $('#overlay').hide();
            $('#manager_form_reset').submit(); 
        });
        $('#successMessage').hide();
        $('#window .win_form .hidemeonsuccess').show();

        if ($.browser.msie && $.browser.version == 6) {
            $('select').css('visibility','');
        }        
        return false;
    });



   
    
    $('.cat_slider ul').jcarousel({
        scroll: 4
    });   


    $('.client_service .items').hover(function() {
        $('.client_service .items').removeClass('active');
        $(this).addClass('active');
    }, function() {});
    $("object embed").attr('wmode', 'transparent' ).attr('allowfullscreen', 'true');
    $("object").wrap('<div class="object"/>').prepend(' <param name="wmode" value="transparent"> ').prepend(' <param name="allowfullscreen" value="true"> ');
    $("object").each(function(){
       var clone = $(this).clone();
       var parent = $(this).parent();
       $(this).remove();
       parent.append(clone);
    })
   
});


// 
function set_current_city(city_name){
    $.ajax({
        type: "POST",
        url: site_home+'plugins/ajax/cities',
        data:{
            mode:"set_name",
            city_name:city_name
        },
        success: function(data){
            
            history.go(0);
            
        }
    });
    $("#current_city").text(city_name);
    return false;
}

function window_close(){
    $('.window').fadeOut(function(){
        $('#overlay').hide();
    });
    if ($.browser.msie && $.browser.version == 6) {
        $('select').css('visibility','');
    }
    if ($.browser.msie && $.browser.version == 9) {
    setTimeout('window.location.reload()', 2000);
    }
    if ($.browser.msie && $.browser.version == 8) {
    setTimeout('window.location.reload()', 2000);
    }
    return false;
}

function wirePageEvents(){

    $('div.pages a, div.pages_items a ').not('.select').each(function(){
        $(this).click(function(){
            $('#middletd').load($(this).attr('href') + ' #justForAjax', null, wirePageEvents);
            return false;
        }
        );
    })

}
// Показать окно
function win_show(el,overlay) {
        
    $(el).appendTo('body');
        
    res_top = ($(window).height() - $(el).height()) / 2;
    res_left = ($(window).width() - $(el).width()) / 2;

    if (res_top<0) res_top = 30;
    if (res_left<0) res_left = 30;

    $(el)
    .css({
        top: res_top + $(window).scrollTop(),
        right: res_left 
    })
    .fadeIn(function(){
        $(this).find("form input:first").focus()
        });
            
    if ($.browser.msie && $.browser.version == 6) {
        $('select').css('visibility','hidden');
    }
        
    if (overlay==true) $('#overlay').height($(document).height()).show();
        
        
}


///<summary>
/// Функция препятствует введению в инпут чего либо
/// кроме int или real в зависимости от type берет и проверяет является ли число int или real
///<summary>
function __OnDataChangeValidation(field, type, evt, max) {
    
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (evt) keycode = evt.which;
    if (keycode != 9) {
        var check = true;
        var value = field.value; //Берем значение
        var dotesCount = 0;
        var Newstring = "";
        for (var i = 0; i < field.value.length; ++i) {
            var new_key = value.charAt(i); //cycle through characters
            if (((new_key < "0") || (new_key > "9")) &&
                !(new_key == "")) {
                if (type == "real" && (new_key == "." || new_key == ",") && dotesCount == 0) {
                    dotesCount++;
                    Newstring += ",";
                }
                else {
                    check = false;
                }
            }
            else {
                Newstring += new_key;
            }
        }
        //Цвета
        if (!check) {
            field.style.background = "red";
            setTimeout('document.getElementById("' + field.id + '").style.background="white"', 100)
        }
        
        if((max || max === 0) && Newstring > max){
            Newstring = max;
            alert('К сожалению, на складе осталось только ' + max + ' шт данного товара ');
        }

        field.value = Newstring;
    }
}


//skm market
function buy_item(id,count, element, clothId, cancel_checkings)
{   

    if(!cancel_checkings){
        if( !(count+'').replace(/,/g,'').replace(/0/g,'')){
            
            
            $('.price_input_' + clothId).animate( {backgroundColor: 'red'}, 200)
    .animate( {backgroundColor: 'white'}, 200);
            return;
        }
    }
    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/cart?ajax=true&action=add&qty=' + count + '&item=' + id,
        data:{
            ajax: true
        },
        success:function(){
            if(element){
                $(element).replaceWith('<a href="plugins/basket/basket" class="buy">Корзина</a>');
            }
            reloadMiniCart();

            $('#price_input_' + id).replaceWith('<span>' + count + '</span>');
            $('.price_input_many_' + id).replaceWith('<span>' + count + '</span>');
            $('.price_input_' + clothId).each(function(){
                $(this).replaceWith('<span>' + $(this).val() + '</span>')
            });
        }
    });
}

//skm market
function no_buy_item(id)
{
    
    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/cart?ajax=true&action=delete&item=' + id,
        data:{
            ajax: true
        },
        success:function(){           
            reloadMiniCart();
        }
    });
}



function fav_item(id, element)
{

    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/compare?ajax=true&action=add&item=' + id,
        data:{
            ajax: true
        },
        success:function(){
            $(element).replaceWith(' <a href="#" class="star_s" onclick="no_fav_item(' + id +',this); return false;"><img src="templates/default/images/1.png" class="altForStar" title="убрать из избранного" /></a>');
            
            reloadMiniFav();
        }
    });
//$('#forajax').load(
// site_home + 'plugins/catalog/cart?ajax=true&action=add&qty=' + count + '&item=' + id ,
// function(){reloadMiniCart()});
//window.location = 'http://localhost/skm/plugins/catalog/cart?action=add&qty=' + count + '&id=' + id;
}

function no_fav_item(id, element)
{

    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/compare?ajax=true&action=delete&item=' + id,
        data:{
            ajax: true
        },
        success:function(){
            $(element).replaceWith(' <a href="#" class="star" onclick="fav_item(' + id +',this); return false;"><img src="templates/default/images/1.png" class="altForStar" title="добавить в избранное" /></a>');
            reloadMiniFav();
        }
    });
//$('#forajax').load(
// site_home + 'plugins/catalog/cart?ajax=true&action=add&qty=' + count + '&item=' + id ,
// function(){reloadMiniCart()});
//window.location = 'http://localhost/skm/plugins/catalog/cart?action=add&qty=' + count + '&id=' + id;
}

function no_buy_item_from_cart(id,element)
{
    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/cart?ajax=true&action=delete&item=' + id,
        data:{
            ajax: true
        },
        success:function(){
            history.go(0);
        //reloadMiniCart();
            
        }
    });
 
}

function no_fav_item_from_cart(id,element)
{
    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/compare?ajax=true&action=delete&item=' + id,
        data:{
            ajax: true
        },
        success:function(){
            history.go(0);
        //reloadMiniCart();

        }
    });

}

function no_buy_all_item_from_cart(element)
{
    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/cart?ajax=true&action=deleteall',
        data:{
            ajax: true
        },
        success:function(){
            history.go(0);
        }
    });

}

function no_fav_all_item_from_cart(element)
{
    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/compare?ajax=true&action=deleteall',
        data:{
            ajax: true
        },
        success:function(){
            history.go(0);
        }
    });

}
function no_fav_item_from_cart(id, element)
{
    $.ajax({
        type: "POST",
        url: site_home + 'plugins/catalog/compare?ajax=true&action=delete&item='+id,
        data:{
            ajax: true
        },
        success:function(){
            history.go(0);
        }
    });

}
var BasketOpened = false;
function reloadMiniCart(keepHover){

    $.ajax({
        type: "POST",
        url:  site_home + "plugins/catalog/ajaxhandler?ajax=true&action=cart",
        context: document.body,
        data: {
            ajax : true
        },
        success: function(data){
            $('#toolbar .in_basket').replaceWith(data);
//            $('.reload_on_basket_reload').each(function(){
//                $(this).html($('#minibasket_grand_total').html() + '.&ndash;');
//            });
            $('.reload_on_basket_reload_count').each(function(){
                $(this).html('(' + $('#minibasket_grand_count').html() + ')');
            });
            $('.counts').each(function(){
                var price = discount = 0;
                items = $(this).find('.item');
                for(i = 0; i < items.length; i++) {
                    add = parseFloat($('#mb_result_' + items[i].id.substr(5)).text().replace(/\s/, ''));
                    if(!isNaN(add)) {
                        price += add;
                    }
                }
                $(this).find('.reload_on_basket_reload_result').html(price + '.&ndash;');
                $(this).find('.reload_on_basket_reload_discount').html((parseFloat($(this).find('.e05').text().replace(/\s/, '')) - price) + '.&ndash;');
            });
//            $('.reload_on_basket_reload_result').each(function(){
//                $(this).html($('#mb_' + $(this).attr('id')).html());
//            });
            $('#total_discount, #total_result, #total_price').each(function(){
                $(this).html($('#mb_' + $(this).attr('id')).html() + '.&ndash;');
            });
            
            if(data.indexOf('пока ничего нет') == -1){
                $('#toolbar .in_basket').hover(
                    function(){
                        $(this).stop(true, true).addClass('hover')
                        $('#toolbar .in_basket.openbox .inner').stop(true, true);
                    },
                    function(){
                        $(this).removeClass('hover');
                       // $('#toolbar .in_basket.openbox .inner');
                    }
                    );
            }
            else if(keepHover){
                $('#toolbar .in_basket').addClass('hover');
            }
            
            
            $('#toolbar .openbox .inner').hide();
            $('#toolbar .in_basket').addClass('hover');
            $('#toolbar .in_basket.openbox .inner').slideDown(300).delay(1000).slideUp(600, function()
                    {                       
                        $('#toolbar .in_basket').removeClass('hover');
                        $('#toolbar .in_basket.openbox .inner').css('display', '');
                        
                    });
             
            
        }
    });
}

function reloadMiniFav(keepHover){
    $.ajax({
        type: "POST",
        url:  site_home + "plugins/catalog/ajaxhandler?ajax=true&action=compare",
        context: document.body,
        data: {
            ajax : true
        },
        success: function(data){
            $('#toolbar .in_favorites').replaceWith(data);
        
            $('.reload_on_fav_reload_count').each(function(){
                $(this).html('(' + $('#fav_grand_count').html() + ')');
            });
        
            if(data.indexOf('пока ничего нет') == -1){
                $('#toolbar .in_favorites').hover(
                    function(){
                        $(this).addClass('hover')
                    },
                    function(){
                        $(this).removeClass('hover')
                    }
                    );
            }
            else if(keepHover){
                $('#toolbar .in_basket').addClass('hover');
            }
        }
    });
}

function DeleteChecked(){
    var ids = '';
    
    var anyToDelete = false;
    var liToDelete = new Array();
   
    $('.basket .idOfItem').each(function(){
        if($(this).parents('li:first').find('.checkbox').is(':checked')){
            ids+= ',' + $(this).val();
            anyToDelete = true;
          
            liToDelete.push($(this).parents('li:first'));
        }
    });
    if(anyToDelete){
        $.ajax({
            type: "POST",
            url: site_home + 'plugins/catalog/cart?ajax=true&action=delete&item=' + ids,
            data:{
                ajax: true
            },
            success:function(){            
           
                if($('.basket .items li ').length <= liToDelete.length){
                    history.go(0);
                }else{
                    for(var i=0; i<liToDelete.length; i++ ){
                        $(liToDelete[i]).remove();
                    }
                    reloadMiniCart();
                }
            }
        });
    }
}

function DeleteCheckedFav(){
    var ids = '';
    
    var anyToDelete = false;
    var liToDelete = new Array();
   
    $('.basket .idOfItem').each(function(){
        if($(this).parents('li:first').find('.checkbox').is(':checked')){
            ids+= ',' + $(this).val();
            anyToDelete = true;
          
            liToDelete.push($(this).parents('li:first'));
        }
    });
    if(anyToDelete){
        $.ajax({
            type: "POST",
            url: site_home + 'plugins/catalog/compare?ajax=true&action=delete&item=' + ids,
            data:{
                ajax: true
            },
            success:function(){            
           
                if($('.basket .items li ').length <= liToDelete.length){
                    history.go(0);
                }else{
                    for(var i=0; i<liToDelete.length; i++ ){
                        $(liToDelete[i]).remove();
                    }
                    reloadMiniFav();
                }
            }
        });
    }
}

function DeleteCheckedVis(){
    var ids = '';
    
    var anyToDelete = false;
    var liToDelete = new Array();
   
    $('.basket .idOfItem').each(function(){
        if($(this).parents('li:first').find('.checkbox').is(':checked')){
            ids+= ',' + $(this).val();
            anyToDelete = true;
          
            liToDelete.push($(this).parents('li:first'));
        }
    });
    if(anyToDelete){
        $.ajax({
            type: "POST",
            url: site_home + 'plugins/catalog/compare?ajax=true&action=deleteVis&item=' + ids,
            data:{
                ajax: true
            },
            success:function(){            
                history.go(0);
                if($('.basket .items li ').length <= liToDelete.length){
                    history.go(0);
                }else{
                    for(var i=0; i<liToDelete.length; i++ ){
                        $(liToDelete[i]).remove();
                    }
                    
                }
            }
        });
    }
}



function AddToFavoriteChecked(){
    var ids = '';
    
    var anyToDelete = false;
    var liToDelete = new Array();
   
    $('.basket .idOfItem').each(function(){
        if($(this).parents('li:first').find('.checkbox').is(':checked')){
            ids+= ',' + $(this).val();
            anyToDelete = true;
          
            liToDelete.push($(this).parents('li:first'));
        }
    });
    if(anyToDelete){
        $.ajax({
            type: "POST",
            url: site_home + 'plugins/catalog/compare?ajax=true&action=add&item=' + ids,
            data:{
                ajax: true
            },
            success:function(){
            
                reloadMiniFav();
            }
        });
    }
}

function AddCheckedToCart(){
    var ids = '';
    var count = '';
    var anyToDelete = false;
    var liToDelete = new Array();
   
    $('.basket .idOfItem').each(function(){
        if($(this).parents('li:first').find('.checkbox').is(':checked') && $(this).parents('li:first').find('input:text').length ){
            ids+= ',' + $(this).val();
            if($(this).attr('itemcount')){
                count+=','+$(this).attr('itemcount');
            }else{
                count+=',1';
            }
            anyToDelete = true;
          
            liToDelete.push($(this).parents('li:first'));
        }
    });
    if(anyToDelete){
        $.ajax({
            type: "POST",
            url: site_home + 'plugins/catalog/cart?ajax=true&action=add&item=' + ids + '&qty=' + count,
            data:{
                ajax: true
            },
            success:function(){
            
                history.go(0);
            }
        });
    }
}

$(document).ready(function(){
    if ($('[rel=lightbox]').length != 0) {
        $('[rel=lightbox]').click(function(){
            
            $($('<img>').attr('src', $(this).attr('href'))).lightbox_me();
            return false;
        });
    }
});

