//var $J = jQuery.noConflict();
jQuery(document).ready(function(){
	//	Для показа и скрытия доп инф.используется много где
	$('.click_to_show').live('click',function() {
		var auth = false;
		var id = $(this).attr('id');
		$('div[id^=show_]').not('div#show_'+id).hide('fast');
		$('div#show_'+id).toggle('normal');
	});
    
    //  save cookie
    $('.saveMyLogIn').click(function() {
        var cooc = $('#saveMyCookie');
        if ( $(this).attr('id') == 'nothing' ) {
            $(this).attr('id','saveMyCookieSelected');
            cooc.val('save');
        } else {
            $(this).attr('id','nothing');
            cooc.val('no');
        };
    }).focus(function(){
		$(this).blur();
	});
    
	
	//catalog tree
	$("#tree ul ul ul:not(.opened)").hide();
	$("#tree a.group").click(function(){
		$(this).blur().next("ul").slideToggle(100);
		return false;
	});
	
	//any corners
	$(".popular_img").cornerz({radius: 3, background: "#dcdddc"});
	$(".popular2, .tree_first").cornerz({corners: "tl tr", radius: 13}).cornerz({corners: "bl br", radius: 13, background: "#e1e1e1"});
	$(".popular, #tree").cornerz({radius: 16});
	
	//photo review
	$(".photo_pic a").click(function(){
		$(".photo_view").hide();
		$(this).parent().next(".photo_view").show();
	});
	/*$(".photo_view").each(function(){
		$(this).width($("img", this).width());
	});*/
	$(".photo_view").prepend('<b class="b1t"></b><b class="b2t"></b><b class="b3t"></b><b class="b4t"></b>').append('<b class="b4t"></b><b class="b3t"></b><b class="b2t"></b><b class="b1t"></b>');
	$(".photo_view a").click(function(){
		$(this).parent().parent().hide();
	});
});

$(window).resize(function()
{
});

/**
* корзина медиаконтента (фотосток, видеосток,...)
*/
Basket = {
    'user': {}
};

/***************************
*** добавление в корзину ***
***************************/
Basket.add = function ( type, id ) {
    
    $.ajax({
        type: 'post',
        url: '/templates/blocks/basket_ajax.php',
        data: 'ajaxAction=add&type=' + type + '&id=' + id,
        success: function( _data ){
            try {
                eval( 'data = ' + _data );
            } catch (e) {
                data = {'code':'error', 'message':'Ошибка на сервере.'};
            }
            if ( data['code'] == 'ok' ) {
                alert( 'Успешно добавлено ' + data['message'] );
            } else if ( data['code'] == 'error' ){
                alert( 'Ошибка : ' + data['message'] );
            }
        },
        error: function(){
            alert( 'Неизвестная ошибка' );
        }
    });
}

Basket.rem = function( type, id ) {
    if ( confirm('Вы действительно желаете удалить товар из крзины?') ) {
        $.ajax({
            type: 'post',
            url: '/ru/salemediacontent/basket/sendvalues/ajax/rem/',
            data: 'type=' + type + '&id=' + id,
            success: function( _data ){
                try {
                    eval( 'data = ' + _data );
                } catch (e) {
                    data = {'code':'error', 'message':'Ошибка на сервере.'};
                }
                if ( data['code'] == 'ok' ) {
                    //alert( 'Успешно удалено ' + data['message'] );
                    $('#item_' + type + '_' + id).remove();
                    Basket.recalc();
                } else if ( data['code'] == 'error' ){
                    alert( 'Ошибка : ' + data['message'] );
                }
            },
            error: function(){
                alert( 'Неизвестная ошибка' );
            }
        });
    }
}

/*** пересчет суммы покупки*/
Basket.recalc = function() {
    var total_price = 0;
    $('#basket_table input[name^="price"]:checked').each(function(){
        total_price += parseFloat($(this).val());
    });
    $('#basket_table #price_total').html(total_price);
    if ( Basket.user['money'] >= total_price ) {
        $('.basket_message').hide();
        $('#basket_mesage_ok').show();
        $('#basket_buy').removeAttr('disabled');
    } else {
        $('.basket_message').hide();
        $('#basket_mesage_money').show();
        $('#basket_buy').attr('disabled','disabled');
    }
}

/*** запуск пересчетчика корзины**/
Basket.start_recalcer = function() {
    $('#basket_table input[name^="price"]').attr("DD","dd");
    $('#basket_table input[name^="price"]').change( Basket.recalc );
}

/**
* Корзина интернет магазина
**/
ShopBasket = {};


ShopBasket.counts = '';

/**
* добавление в корзину
**/
ShopBasket.add = function ( id ) {
    $.ajax({
        type: 'post',
        url: '/ru/shop/shop_basket/sendvalues/ajax/add/',
        data: 'id=' + id,
        success: function( _data ){
            try {
                eval( 'data = ' + _data );
            } catch (e) {
                data = {'code':'error', 'message':'Ошибка на сервере.'};
            }
            if ( data['code'] == 'ok' ) {
                alert( 'Успешно добавлено ' + data['message'] );
            } else if ( data['code'] == 'error' ){
                alert( 'Ошибка : ' + data['message'] );
            }
        },
        error: function(){
            alert( 'Неизвестная ошибка' );
        }
    });
}

/**
* пересчет кол-ва
**/
ShopBasket.recalc = function( counts ) {
	
	$.post(
		'/ru/shop/shop_basket/sendvalues/ajax/recalc/',
		{counts:counts},
		function (data) {
		
			if ( data['code'] == 'ok' ) {
				var total_price = 0;
				for ( var item_id in data['data'] ) {
                    $('#full_price_' + item_id).html( data['data'][item_id] );
                    total_price += data['data'][item_id] * 1;
                }
                $('#price_total').html(total_price);
			} else {
				alert( 'Ошибка : ' + data['message'] );
			}
			
		}, "json"
	);
	
	//alert('dd');
	/*
    $.ajax({
        type: 'post',
        url: '/ru/shop/shop_basket/sendvalues/ajax/recalc/',
        data: counts,
        
        success: function( data ){

            try {
                eval( 'data = ' + _data );
            } catch (e) {
                data = {'code':'error', 'message':'Ошибка на сервере.'};
            }

            alert(data);
            if ( data['code'] == 'ok' ) {
                var total_price = 0;
                for ( var item_id in data['data'] ) {
                    $('#full_price_' + item_id).html( data['data'][item_id] );
                    total_price += parseInt( data['data'][item_id] );
                }
                $('#price_total').html(total_price);
            } else if ( data['code'] == 'error' ) {
                alert( 'Ошибка : ' + data['message'] );
            }
        },
        error: function(){
            alert( 'Неизвестная ошибка' );
        }
    });
    */
}

ShopBasket.rem = function( id ) {
    if ( confirm('Вы действительно желаете удалить товар из крзины?') ) {
        $.ajax({
            type: 'post',
            url: '/ru/shop/shop_basket/sendvalues/ajax/rem/',
            data: '&id=' + id,
            success: function( _data ){
                try {
                    eval( 'data = ' + _data );
                } catch (e) {
                    data = {'code':'error', 'message':'Ошибка на сервере.'};
                }
                if ( data['code'] == 'ok' ) {
                    //alert( 'Успешно удалено ' + data['message'] );
                    $('#item_' + id).remove();
                    ShopBasket.recalc( ShopBasket.counts );
                } else if ( data['code'] == 'error' ){
                    alert( 'Ошибка : ' + data['message'] );
                }
            },
            error: function(){
                alert( 'Неизвестная ошибка' );
            }
        });
    }
}


/**
* Vote
*/

enable_vote = function() {
    /**
    * Vote start
    */
    $('#photostock_stars span.star').css('cursor', 'pointer');
    $('#photostock_stars')
        .live( 'mouseover', 
            function(){
                $('#photostock_stars span.star').css('cursor', 'pointer');
                $(this).addClass('active');
            })
        .live( 'mouseout',
            function(){
                $(this).removeClass('active');
                $('.star', $(this)).removeClass('star_chosen')
            }
        );
    $('#photostock_stars .star')
        .live('mouseover', 
            function() {
                $(this).addClass('star_chosen');
                var _prev = $(this);
                var _points = 1;
                do {
                    _prev = _prev.prev();
                    if ( _prev.hasClass('star') ) {
                        _prev.addClass('star_chosen');
                        _points++;
                    } else {
                        _prev = false;
                    }
                } while ( _prev );
                $('.star_points').text(_points + '.0');
            })
        .live('mouseout', 
            function() {
                if ( !$(this).next().hasClass('star_chosen')) {
                    $(this).removeClass('star_chosen');
                }
                $('.star_points').empty();
            }
        );
}

voteIt = function( type, id, value ) {
    $.ajax({
        type: 'post',
        url: '/ru/vote/',
        data: 'type=' + type + '&id=' + id + '&value=' + value,
        success: function( _result ){
            try {
                eval('result = ' + _result );
                $('#photostock_votecount').html( result['votes'] );
                $('#photostock_voteavg').html( result['rating'] );
                $('#photostock_stars').html( result['stars'] );
                $('#photostock_voteok').fadeIn( 200, function(){ $('#photostock_voteok').fadeOut( 1000 ); });
            } catch (e) {}
        }
    });
}


/**
* php js functions
* 
* http://phpjs.org/
**/

function intval (mixed_var, base) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: stensi
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Matteo
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
    // *     example 4: intval('09');
    // *     returns 4: 9
    // *     example 5: intval('1e', 16);
    // *     returns 5: 30

    var tmp;

    var type = typeof( mixed_var );

    if (type === 'boolean') {
        return (mixed_var) ? 1 : 0;
    } else if (type === 'string') {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if (type === 'number' && isFinite(mixed_var) ) {
        return Math.floor(mixed_var);
    } else {
        return 0;
    }
}
function trim(sInString){
    //sInString = sInString.replace(/ /g,'');
    if ( sInString == '' ) return false;
    	else return sInString.replace(/(^\s+)|(\s+$)/g, '');
}

function objCount(obj) {
	var count = 0;
	for ( var i in obj ) {
		count++
	}
	return count;
}

function dump(obj,step) {
    var out = '';
    if ( getType(obj) == 'object' ) {
		for (var i in obj) {
			if ( step == 2 ) tab='\t';
				else tab='';
			if ( getType(obj[i]) == 'object' ) out += i + dump(obj[i],2)
				else out += tab + i + ": " + obj[i] + "\n";
		}
		if ( step == 2 ) return out;
			else alert(out);
	} else alert(obj);
}

function getType (obj) {
	return typeof obj;
}


/***
 * Работа с медиа статистика
 **/
function goStatItem(item) {
    var id =  $(item).attr('id');
    window.location='/ru/salemediacontent/statistics/sendvalues/show_more/'+id+'/';
}
//~Округление
function roundVal(val){
	var dec = 2;
	var result = Math.round(val*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

