$(document).ready(function(){
    /**
     *  Center menu list
     */

    var widthList = 0;

    $('ul#products li').each(function(){
        widthList += parseInt($(this).width());
    });

    $('ul#products').css('margin-left', ((parseInt($('#products').parent().width()) - widthList ) / 2));


    




    /**
     *  Selects
     */

    var selects = $('.optionsProduct');
    var price = 0;
    var title = '';
    prices = Array();
    
    selects.parent().children('#preloader').hide();
    selects.children('.productDetail').children('div').children('input').click(function(){
        $(this).setDelivery();
    });


    selects.find('select.dropdown').each(function(){
        
        $(this).change(function(){
            var parent = $(this).parent().parent();

            parent.children('.imageProduct').children().hide('fast');
            parent.children('#preloader').show();

            var elements = $(this).attr('id').split('_');
            var productDetails = $(this).next();

            var thisObj = $(this);
            title = $(this.options[this.options.selectedIndex]).text();


            $.ajax({
                type: 'POST',
                url: '/ajax/signup.html',
                dataType: 'json',
                data: {
                    product: elements[1],
                    select: elements[2],
                    value: thisObj.val()
                },

                success : function(data){
                    parent.children('#preloader').hide();

                    parent.children('.imageProduct').children().attr('src', data.returnValue['icon_url'])
                    parent.children('.imageProduct').children().show('slow');

                    price = data.returnValue['item_gross_price'];

                    productDetails.children('strong').text(price);
                    productDetails.children('span').text(data.returnValue['price_currency']);
                    productDetails.children('.fQuantity').attr('id', 'qty_' + data.returnValue['item_code'] + '_' + activeBox).val('1');
                    productDetails.children('.fQuantity').prev('label').attr('for', 'qty_' + data.returnValue['item_code']);

                    parent.children('.description').children('div').html(data.returnValue['short_description']);
                    parent.children('.description').children('p').html(data.returnValue['description']);

                    if(data.returnValue['available_as_autoship'] == 1)
                    {
                        productDetails.children('div').show();
                        
                        var checkbox = productDetails.children('div').children('input:checkbox');
                        checkbox.attr('id', 'autoship_'+ data.returnValue['item_code'] +'_' + elements[1]);
                        checkbox.attr('for', 'autoship_'+ data.returnValue['item_code'] +'_' + elements[1]);

                        if(data.returnValue['is_delivery_checked']){
                            $(checkbox).attr('checked', true);
                        }
                        else{
                            $(checkbox).attr('checked', false);
                        }
                    }
                    else
                        productDetails.children('div').hide();

                    productDetails.next('.button').attr('id', 'cart_' + data.returnValue['item_code'] + '_' + activeBox);
                }
            });
        });
    });

    /**
     *  Signup menu - products
     */

    var products = $('ul#products li');
    var activeBox = 'vemma';

    var hash = window.location.hash.split('?')[0];
    var hashTab = hash.substr(1, hash.length - 1);

    products.each(function(index){
        /**
         *   Tabs hash
         */
    	
        if(hashTab != ''){
            $(this).removeClass('on');
            $('#'+ $(this).attr('id').substr(0, $(this).attr('id').length - 13)).css('display', 'none');

            if($(this).attr('id') == hashTab + '_products_tab'){
                $(this).addClass('on');
                $('#' + hashTab).css('display', 'block');
            }
        }

        $(this).click(function(){
            for(var i=0, c=products.length; i<c; i++){
                if(i != index){
                    $(products[i]).removeClass('on');
                    $('#'+ $(products[i]).attr('id').substr(0, $(products[i]).attr('id').length - 13)).css('display', 'none');
                }
                else{
                    $(this).addClass('on');

                    activeBox = $(products[i]).attr('id').substr(0, $(products[i]).attr('id').length - 13);
                    $('#' + activeBox).css('display', 'block');  
                    setKeyUpToQty(activeBox, price);
                }
            }
        });
    });

    /**
     *  Buttons
     */

    var buttons = $('.button');
    var cartPreloader = $('#cartPreloader');

    cartPreloader.hide();

    buttons.each(function(){
        if($(this).children().attr('class') == 'orangeBtn'){
            $(this).click(function(){
                if($(this).parent().children('select.dropdown').length > 0)
                {
                    $('#cartList').hide();
                    cartPreloader.show();

                    var id = $(this).attr('id').split('_')[1];

                    if(title == ''){
                        var selectedOption = $(this).parent().children('select.dropdown')[0].options;
                        title = $(selectedOption[selectedOption.selectedIndex]).text();
                    }

                    if($('#cartList table tr').length < 2){
                        $('#spanbtns').show();
                        $('#cartList').prev().prev().show();
                    }

                    var price = parseFloat($(this).parent().children('.productDetail').children('strong').text());
                    var currency = $(this).parent().children('.productDetail').children('span').text();
                    var amount = parseInt($(this).parent().children('.productDetail').children('.fQuantity').val());
                    var country_code = $('input[name="country"]').val();		
                    
                    $.ajax({
                        type: 'POST',
                        url: '/ajax/signup.html',
                        dataType: 'json',
                        data : {
                            isAdd : true,
                            cart_id : id,
                            cart_price : price,
                            cart_amount : amount,
                            cart_currency : currency,
                            cart_description : title,
                            user_country : country_code
                        },

                        success : function(data){
                            title = '';

                            cartPreloader.hide();
                            $('#cartList').show();

                            $('#itemcount').text('Items ' + data.cart['items']);
                            $('#cartList').html(data.cart['html']);
                            $('#gtotal').html(data.cart['price'] + '&nbsp;' + currency);
                            
                            if('UA' == country_code)
                            	$('#autoship_'+id+'_'+activeBox).attr('checked', true);	
                            	
                        }
                    });
                }
            });

            $(this).hover(function(){
                $(this).find('.left').css('background-position', '0 -594px').next().css('background-position', '0 -636px').next().css('background-position', '0 -678px');
            },
            function(){
                $(this).find('.left').css('background-position', '0 -468px').next().css('background-position', '0 -510px').next().css('background-position', '0 -552px');
            });
        }
        else if($(this).children().attr('class') == 'greenBtn')
        {
            $(this).hover(function(){
                $(this).find('.left').css('background-position', '0 -1438px').next().css('background-position', '0 -1480px').next().css('background-position', '0 -1522px');
            },
            function(){
                $(this).find('.left').css('background-position', '0 -1312px').next().css('background-position', '0 -1354px').next().css('background-position', '0 -1396px');
            });
        }
    });


    /**
     *  Box height
     */
    setKeyUpToQty(activeBox, price);	

    if($('.allredyInVemma').attr('tagName') != 'undefined')
    {
        if($('.allredyInVemma #error1').attr('class') == 'notification')
        {
            $('.allredyInVemma .notification').slideFadeToggle('slow').click(function(){
                $(this).slideFadeToggle('slow');
            });
        }
    }


    $('#spanbtns .btn-font a').click(function(){
        $.ajax({
            type: 'POST',
            url: '/ajax/signup.html',
            dataType: 'json',
            data: {checkout : true},

            success : function(data){
                if(data.checkout['valid'] == true){
                    $('#step2').submit();
                }
                else{
                    $('#error' + data.checkout['error'][0]).slideFadeToggle('slow').click(function(){
                        $(this).slideFadeToggle('slow');
                    });
                }
            }
        });
    });
});


jQuery.fn.setDelivery = function(){
    var id = $(this).attr('id').split('_')[1];
    var isDelivery = 1;

    if($(this).is(':checked'))
        isDelivery = 2;
    else
        isDelivery = 1;

    $.ajax({
        type: 'GET',
        url: '/ajax/signup.html',
        dataType: 'json',
        data: {active : isDelivery, id : id},

        success : function(data){
            var rows = $('#cartList table tr');
            var rowsLength = rows.length;
            
            $('#cartAutoshipTable > tbody').html('');
            $('#cartASLabel').hide();            
            if (data.autoship)
            {
            	var autoship = data.autoship;
            	var bgDark = true;
            	for (key in autoship)
            	{
            		if (true == bgDark)
            		{
            			bgDark = false;
            			bgColor = 'eee';
            		}
            		else
            		{
            			bgDark = true;
            			bgColor = 'fff';
            		}
            		$('#cartAutoshipTable > tbody:last').append('<tr id="as_info_' + key + '" style="background:#' + bgColor +'"><td class="row" style="vertical-align:middle"><img onclick="dropFromAutoship(\'' + key + '\')" style="cursor:pointer" src="/images/main/delete.png" alt="Remove" /></td><td class="row" style="text-align: left; color:#FF6600; padding-left:3px; padding-right:3px; vertical-align:middle;">' + autoship[key] + '</td></tr>');
            		$('#cartASLabel').show();
            	}
            }

            if(rowsLength > 1){
                var rowId = 0;

                for(var i=1; i<rowsLength; i++){
                    rowId = $(rows[i]).attr('id').split('_')[1];

                    /*
                    if(rowId == id){
                        if(data.returnValue[id]['is_delivery_checked'] == true)
                            $(rows[i]).children('td:first').children('img:last-child').show();
                        else
                            $(rows[i]).children('td:first').children('img:last-child').hide();
                    }*/
                }
            }
        }
    });
};

function dropFromCart(itemCode){
    var currency = $(this).parent().children('.productDetail').children('span').text();

    if($('#cartList table tr').length == 2)
    {
        $('#spanbtns').hide('fast');
        $('#cartList').prev().prev().hide('fast');
    }

    $.ajax({
        type: 'POST',
        url: '/ajax/signup.html',
        dataType: 'json',
        data : {
            isDrop : true,
            item_code : itemCode
        },

        success : function(data){
            $('#itemcount').text('Items ' + data.cart['items']);
            $('#cartList').html(data.cart['html']);
            $('#gtotal').html(data.cart['price'] + '&nbsp;' + currency);
            
            if('UA' ==  $('input[name="country"]').val()){
            	$.each($('input[type=checkbox]'), function(){ 
            		var _regex = new RegExp( "^autoship_" + itemCode+"_([a-z]+)$", "i");	
            		if( $(this).attr('id').match(_regex))	{
            			$(this).attr('checked', false);
            		}
            	});
            }
    	}
    });
}


function dropFromAutoship(itemCode){
	
	$('[id^=autoship_' + itemCode + ']').attr('checked', false);
 
    $.ajax({
        type: 'POST',
        url: '/ajax/signup.html',
        dataType: 'json',
        data : {
            isDropAutoship : true,
            item_code : itemCode
        },        

        success : function(data){
            var rows = $('#cartList table tr');
            var rowsLength = rows.length;

            $('#cartAutoshipTable > tbody').html('');
            $('#cartASLabel').hide();
            if (data.autoship)
            {
            	var autoship = data.autoship;
            	var bgDark = true;
            	for (key in autoship)
            	{
            		if (true == bgDark)
            		{
            			bgDark = false;
            			bgColor = 'eee';
            		}
            		else
            		{
            			bgDark = true;
            			bgColor = 'fff';
            		}
            		$('#cartAutoshipTable > tbody:last').append('<tr id="as_info_' + key + '" style="background:#' + bgColor +'"><td class="row" style="vertical-align:middle"><img onclick="dropFromAutoship(\'' + key + '\')" style="cursor:pointer" src="/images/main/delete.png" alt="Remove" /></td><td class="row" style="text-align: left; color:#FF6600; padding-left:3px; padding-right:3px; vertical-align:middle;">' + autoship[key] + '</td></tr>');
            		$('#cartASLabel').show();
            	}
            }

            if(rowsLength > 1){
                var rowId = 0;

                for(var i=1; i<rowsLength; i++){
                    rowId = $(rows[i]).attr('id').split('_')[1];
                }
            }
        }
    });
}


function setKeyUpToQty(activeBox, price)
{
	var boxes = $('#contentProducts #' + activeBox + ' .box');
	var height = 0;
	
	
	
	for(var i=0, c=boxes.length; i<c; i++){
	    // Quantity counter
	    $(boxes[i]).find('.fQuantity').keyup(function(e){
	    		
	    	var id = $(this).parent().children('input').attr('id');
	    	if(prices[id])
	    		price = prices[id];
	    	else
	    		prices[id] = price = $(this).parent().children('strong').text();	
	
	        // short validate
	        if(e.which == 48 || e.which == 49 || e.which == 50 || e.which == 51 || e.which == 52 || e.which == 53 || e.which == 54 || e.which == 55 || e.which == 56 || e.which == 57)
	            newValue = parseInt($(this).val());
	        else{
	            var newValue = 0;
	
	            if($(this).val()){
	                if(parseInt($(this).val()) > 0)
	                    newValue = parseInt($(this).val());
	                else
	                    newValue = 0;
	            }
	        }
	
	        $(this).val(newValue);
	        $(this).parent().children('strong').text(parseFloat(newValue * price).toFixed(2));
	    });
	
	    if(i % 2 == 0 && $(boxes[i+1]).attr('class') == 'box')
	    {
	        if(parseInt($(boxes[i]).height()) < parseInt($(boxes[i+1]).height()))
	            height = parseInt($(boxes[i+1]).height());
	        else
	            height = parseInt($(boxes[i]).height());
	
	        $(boxes[i+1]).css('height', height + 'px');
	        $(boxes[i]).css('height', $(boxes[i+1]).height()+ 'px');
	    }
	}
}

function showAutoshipSelector(id)
{
	$('#'+id).slideFadeToggle('slow'); 
}

function changeCustomerType(pObj)
{
	if(pObj.checked)				
		$('#customer_type').val('preferred');
	else
		$('#customer_type').val('normal');	
}