var TRANSLATIONS = {
    'es': { 'Preço': 'Precio',
            'Página seguinte': 'Página siguiente',
            'Olá': 'iHola',
            'tem': 'tienes',
            'Zis no seu ZI CARD!': 'Zis en tu ZI CARD!',
            'Alterar dados': 'Cambiar datos',
            'Logout': 'Salir',
            'Vale de Desconto': 'Vale descuento'}
};

function _(str) {
    
    if(TRANSLATIONS[TLD] != null && TRANSLATIONS[TLD][str] != null)
        return TRANSLATIONS[TLD][str]; 
    
    return str;
}

function evaluateTpl(tpl, obj) {
    var final_tpl = tpl;
    
    for(attr in obj)
        final_tpl = final_tpl.replace(eval('/#{'+attr+'}/g'), obj[attr]);
    
    return final_tpl;
}

var product_li_tpl = '<li style="position: absolute; width: 0px; height: 0px; left: 810px; top: 575px">'+
                     '    <a href="#{url}" title="#{designation}">'+
                     '        <img src="#{img}" alt="#{designation}" />'+
                     '        <span class="bag1 #{online_sale}" style="display: none">'+
                     '            <img src="/images/bag1.gif" alt="" />'+
                     '        </span>'+
                     '        <span class="description">'+
                     '            <span class="price">'+_('Preço')+' <br />'+
                     '                <strong>#{price}€</strong>'+
                     '            </span>'+
                     '            <span class="info">'+
                     '                #{designation}<br />'+
                     '                <strong>#{version}</strong>'+
                     '            </span>'+
                     '        </span>'+
                     '    </a>'+
                     '</li>';
                     
                    
function loadProducts(data, status) {
    
    if(data.products.length == 0) {
        $('#product_list').empty();
        $('.no-products').fadeIn(300);
        $('.pro-pagination').empty();
        return;
    }
    else {
        $('#product_list').empty();
        $('.no-products').hide();
    }
    
    var pathname = window.location.pathname.charAt(window.location.pathname.length-1) == '/' ? window.location.pathname : window.location.pathname + '/';
    
    // populate products
    $(data.products).each(function(index, elem) {
                          
                            elem.url = pathname+elem.seo; 
                          
                            elem.online_sale = elem.online_sale ? 'online-sale' : '';
                            
                            $('#product_list').append(evaluateTpl(product_li_tpl, elem));
                          });
    
    $('#product_list li').each(function(index, elem) {
                                
                                x_i = index % 5;
                                y_i = Math.floor(index/5);
                               
                                $(elem).animate({ 'left': (x_i*161)+'px', 'top': (y_i*114+3)+'px', 'width': '160px', 'height': '113px' }, 500);
                               });
    
    setTimeout(function() { $('#product_list li a .online-sale').fadeIn(500) }, 1000);
    
    collectionHoverEffect();
    
    // update pagination
    $('#current_page').val(data.current_page);
    $('#last_page').val(data.pages);
    $('.pro-pagination').empty();
    
    if($('#last_page').val() > 1) {
        
        if(parseInt($('#current_page').val()) > 1)
            $('.pro-pagination').append('<a href="'+window.location.pathname+'?page='+(parseInt($('#current_page').val())-1)+'" title="Página anterior" class="prev">'+_('Página anterior')+'</a>'+
                                    '<span>|</span>');   
        
        for(i = 1; i < parseInt($('#last_page').val())+1; i++) {
            $('.pro-pagination').append('<a href="#" title="'+_('Página')+' '+i+'"'+(i == $('#current_page').val() ? 'class="selected"' : '')+'>'+i+'</a>');
            
            if(i < parseInt($('#last_page').val()))
                $('.pro-pagination').append('<span>|</span>');
        }
            
        if(parseInt($('#current_page').val()) < parseInt($('#last_page').val()))
            $('.pro-pagination').append('<span>|</span>'+
                                    '<a href="'+window.location.pathname+'?page='+(parseInt($('#current_page').val())+1)+'" title="Página seguinte" class="next">'+_('Página seguinte')+'</a>');
     
        initProductLoadFromPagination();
    }
    
        
}

function getProducts(e) {
    
    e.preventDefault();
    
    if($('.no-products').is(':visible'))
        $('.no-products').fadeOut(1000);
    
    /* $('#product_list li').css('position', 'absolute');

    $('#product_list li').each(function(index, elem) {
                                x_i = index % 5;
                                y_i = Math.floor(index/5);
                                
                                $(elem).css('left', (x_i*161)+'px').css('top', (y_i*114+3)+'px');
                                
                                }); */
    
    $('#product_list li').animate({ width: '0px', height: '0px', left: '0px', top: '0px'}, 500);
    
    $('#product_list li .bag1').hide();
    
    setTimeout(function() {
                    $.get(window.location.pathname,
                    $('form.filters').serialize(),
                    loadProducts,
                    'json');
    }, 500);
}

function collectionHoverEffect() {
    $('.gallery-list .list .squares1').hover(function(){
        $(".description", this).stop().animate({top:'0'},{queue:false,duration:300});
    }, function() {
        $(".description", this).stop().animate({top:'115px'},{queue:false,duration:300});
    });
    
    $('.gallery-list .list .squares2').hover(function(){
        $(".description", this).stop().animate({top:'0'},{queue:false,duration:300});
    }, function() {
        $(".description", this).stop().animate({top:'228px'},{queue:false,duration:300});
    });
}

function initProductLoadFromPagination() {
    $('.pro-pagination a').each(function(index, elem) {
                            
                                elem = $(elem);
                            
                                if(elem.hasClass('prev') && parseInt($('#current_page').val()) > 1)
                                    elem.click(function(e) {
                                                $('#product_page').val(parseInt($('#current_page').val())-1);
                                                getProducts(e);
                                               });
                                    
                                else if(elem.hasClass('next') && parseInt($('#current_page').val()) < parseInt($('#last_page').val()))
                                    elem.click(function(e) {
                                                $('#product_page').val(parseInt($('#current_page').val())+1);
                                                getProducts(e);
                                               });
                                    
                                else
                                    elem.click(function(e) {
                                                $('#product_page').val(elem.html());
                                                getProducts(e);
                                               });
                            
                            });   
}

// columns equal height
function setEqualHeight(columns) {  
	var tallestcolumn = 0;  
	columns.each(  
	function() {  
		currentHeight = $(this).height();  
		if(currentHeight > tallestcolumn) {  
			tallestcolumn  = currentHeight;  
		}  
	});  
	
	columns.height(tallestcolumn);  
}

function updateUserWelcome(name, points) {
    $('#userwelcome').html(_('Olá')+' '+name+', '+_('tem')+' <span class="points">'+points+'</span> '+_('Zis no seu ZI CARD!')+'<br /><a class="btn11 btn1" id="update-user" href="'+ROOT+'update-user"><span>'+_('Alterar dados')+'</span></a> <a class="btn11 btn1" href="'+ROOT+'logout"><span>'+_('Logout')+'</span></a>');
    
    $('#update-user').click(function(e) {
                                Shadowbox.open({
                                                content: $('#update-user').attr('href'),
                                                player: 'iframe',
                                                width: '680px',
                                                height: '390px'
                                                });
                                
                                e.preventDefault();
    });
    
    // if in cart, proceed to step 2 of order
    if(layout == 'cart')
        window.location = ROOT+'cart/address';
    else if(layout == 'zicard.account')
        window.location = ROOT+'zi-card/my-account';
}

function allowOnly(event, regexp) {
    var regexp;
    var e    = event || window.event;
    var code = e.charCode || e.keyCode;

    if (e.charCode == 0)       return true;
    if (e.ctrlKey || e.altKey) return true;
    if (code < 32)             return true;  // ASCII control char
  
    var c = String.fromCharCode(code);
    if(c.match(regexp) == null) {
        if (e.preventDefault) e.preventDefault();
        if (e.returnValue)    e.returnValue();
        return false;
    }
    return true;
}

function allowOnlyNumbers(event) {
    
    if (allowOnly(event, "[0-9]{1}"))
        return true;
    
    return false;
}

function updateTopCart(cart_products) {
    
    if(cart_products == 0) {
        $('.shoppingcart').css('visibility', 'hidden');
        
        if(layout == 'cart') {
            $('.cart-not-empty').hide();
            $('.empty-cart').show();   
        }
    }
    else {
    
        $('.n_products').html(cart_products + ' par' + (cart_products != 1 ? 'es' : ''));
        
        if($('.shoppingcart').css('visibility') == 'hidden') {
            $('.shoppingcart').css({ visibility: 'visible', display: 'none' });
            $('.shoppingcart').fadeIn();
        }
    }
}

function addProductToCart(e) {
    
    e.preventDefault();
    
    $('#flash-loading-cart').css('visibility', 'visible');
    $('.no-stock-msg:visible').hide();
    
    var bag = document.createElement('span');
    $(bag).addClass('bag').css({ position: 'absolute',
                                 display: 'none',  
                                 top: '-9999px',
                                 left: '-9999px' });
        
    $('#wrapper').append(bag);
    
    $.getJSON($(e.currentTarget).attr('href'), function(json) {
             
              if(json.state == 1) {
                   
                  start_position = $('.buy-bag').offset();
                  end_position   = $('.top-bag').offset();
                    
                  // animate
                  
                  // mouse position
                  // $(bag).css({ top: (e.clientY+$(document).scrollTop())+'px', left: (e.clientX+$(document).scrollLeft())+'px' }).show();
                  
                  $(bag).css({ top: start_position.top+'px', left: start_position.left+'px' }).show();
                  
                  $(bag).animate({ left: end_position.left+'px', top: end_position.top+'px' }, 1000, 'swing', 
                                 
                                 function() {
                                        updateTopCart(json.cart_products);
                                        $(bag).fadeOut(300, function() { $(this).remove(); } );
                                                       
                                 });
              }
              else
                  $('.no-stock-msg').show();
              
              $('#flash-loading-cart').css('visibility', 'hidden');
    });
              
    cart_products++;
    
    if(cart_products == 1)
        reloadCart();
}

function reloadCart() {
    setInterval(function() { $.getJSON(ROOT+'cart/refresh'); }, 5 * 60 * 1000);
}

function removeProduct(e) {
    e.preventDefault();
    
    var id_parts = $(e.currentTarget).attr('href').split('/');
    var product  = $('#product_'+id_parts[id_parts.length-2]+'_'+id_parts[id_parts.length-1]);
    
    $(e.currentTarget).hide();
    $(e.currentTarget).siblings(':first').show();
    
    $.getJSON($(e.currentTarget).attr('href'), function(data) {
              
              if(data.state == 1) {
                    
                  product.remove();
                  updateTotal();
                  updateTopCart(data.cart_products);
                  
                  last_tr = $('.shopTable tr');
                  last_tr = $(last_tr[last_tr.length-1]);
    
                  if(!last_tr.hasClass('last'))
                      last_tr.addClass('last');
              }
              
              });
}

function updateProduct(e) {
    e.preventDefault();
    
    $('.no-stock-msg').hide();
    
    var form = $(e.target);
    
    form.siblings('.loader').show();
    form.hide();
    
    $.getJSON(form.attr('action'), form.serialize(), function(data) {
              
              if(data.state == 0) 
                  $('.no-stock-msg').show();
              else if(data.state == 1) {
                  
                  var tr_parent = form.parents('tr:first'); 
                  
                  // update product total
                  tr_parent.find('.total-part').html((parseFloat(tr_parent.find('.final-price').html()) * parseFloat(tr_parent.find('.product-quantity').attr('value'))).toFixed(2));
                  
                  updateTotal();
                  updateTopCart(data.cart_products);
                  
                  var pq = form.find('.product-quantity'); 
                  pq.data('ori_val', pq.attr('value'));
                  
                  form.find('.refreshValue').css('visibility', 'hidden');
              }
                
              form.siblings('.loader').hide();
              form.show();
              
              });
}

function updateTotal() {
    
    var total = 0;
    
    $('.total-part').each(function(i, elem) { total += parseFloat($(elem).html()); });
    $('.total').html(total.toFixed(2));
}

function insertVoucher(points) {
    
    if(points < POINTS_TO_VOUCHER)
        $('.voucher-field').remove();
    
    var voucher_tpl = '<tr>'+
                        '<th colspan="3">'+_('Vale de Desconto')+'</th>'+
                        '<td class="price-cell" colspan="2"><p class="price">-'+VOUCHER_VALUE.toFixed(2)+'€</p></td>'+
                      '</tr>';
                      
    $('.voucher-sibling').before(voucher_tpl);
    
    $('.final-total').html((parseFloat($('.final-total').html())-VOUCHER_VALUE).toFixed(2));
    
    $('.points').html(points);
}

function zicardLoginCallBack() {
    $('.redeem-zis').each(function(i, e) {
                                       
                                   if($(e).attr('href') == ROOT+'entry')
                                       $(e).attr('href', $(e).parents('.caption_spc:first').find('.item-url').attr('href') + '?redeem');
                                   
                                   $(e).click(function(event) {
                                              
                                                  event.preventDefault();
                                                 
                                                  Shadowbox.open({
                                                                 content:$(e).attr('href'),
                                                                 player: 'iframe'
                                                                });
                                              });
                                   });
}

function domLoaded() {
    
    /* global */
    if($("#login label").length)
        $("#login label").inFieldLabels({ fadeOpacity:0.2 });
    
    if($("#search label").length)
        $("#search label").inFieldLabels({ fadeOpacity:0.2 });
	
	$("#nav .submenu>ul>li:not(.selected)").hover(
		function () {
			$(this).addClass('showMenu');
			$(this).find('.active-item').css('display','block');
			
		}, 
		function () {
			$(this).removeClass('showMenu');
			$(this).find('.active-item').css('display','none');
		}
	);
    
    /* target blank */
    $('.target-blank').click(function(e) { this.target = '_blank'; });
    
    /* back */
    if(layout != 'cart-address' && layout != 'cart-confirm')
        $('.back, .back-link').click(function(e) { e.preventDefault(); history.go(-1); });
    
    /* keep session */
    if(cart_products > 0)
        reloadCart();
    
	switch(layout) {
	 
        case 'in-the-press':
        case 'on-the-web':
            $("#nav .submenu>ul>li:not(.selected)").hover(
                function () {
                    $(this).addClass('showMenu');
                    $(this).find('.active-item').css('display','block');
                    
                }, 
                function () {
                    $(this).removeClass('showMenu');
                    $(this).find('.active-item').css('display','none');
                }
            );
            
            break;
            
        case 'complete.collection':
            
            $('.multiCol').makeacolumnlists({cols:2,colWidth:55,equalHeight:false,startN:1});
        
            collectionHoverEffect();
            
            $('.submitonchange').change(function(e) { $('#product_page').val(1); $(e.target).parents('form:first').submit(); });
            
            // ajax request from pagination
            //initProductLoadFromPagination();
            
            //$('form.filters').submit(getProducts);
            
            break;
                
        case 'selected.collection':
            $('#slider').show();
            
            $("#slider").easySlider({
                auto: true,
                continuous: true,
                pause: 4000
            });
            break;
            
        case 'product':
            
            $('#size').change(function(e) { 
                              $('.shopcart').attr('href', window.location.pathname + '/add?size=' + $(this).val());
                          });
        
            $('.shopcart').click(addProductToCart);
            
            $('#size').sSelect();
                    
            // Initially set opacity on thumbs and add
            // additional styling for hover effect on thumbs
            var onMouseOutOpacity = 0.67;
            $('#thumbs ul.thumbs li').opacityrollover({
                mouseOutOpacity:   onMouseOutOpacity,
                mouseOverOpacity:  1.0,
                fadeSpeed:         'fast',
                exemptionSelector: '.selected'
            });
            
            // Initialize Advanced Galleriffic Gallery
            var gallery = $('#thumbs').galleriffic({
                delay:                     1500,
                numThumbs:                 15,
                preloadAhead:              10,
                enableTopPager:            true,
                enableBottomPager:         true,
                maxPagesToShow:            7,
                imageContainerSel:         '#slideshow',
                controlsContainerSel:      '#controls',
                captionContainerSel:       '#caption',
                loadingContainerSel:       '#loading',
                renderSSControls:          false,
                renderNavControls:         false,
                enableHistory:             false,
                autoStart:                 false,
                syncTransitions:           false,
                enableKeyboardNavigation:  false,
                defaultTransitionDuration: 900,
                onSlideChange:             function(prevIndex, nextIndex) {
                                            // 'this' refers to the gallery, which is an extension of $('#thumbs')
                                            this.find('ul.thumbs').children()
                                                .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                                                .eq(nextIndex).fadeTo('fast', 1.0);
                },
                onPageTransitionOut:       function(callback) {
                    this.fadeTo('fast', 0.0, callback);
                },
                onPageTransitionIn:        function() {
                    this.fadeTo('fast', 1.0);
                }
            });
            
            //console.log($('#gallery').html());
            //$('.advance-link').click(function(e) { console.log(e.currentTarget); });
            
            $('#gallery').click(function(e) { 
                                    
                                if($(e.target).is('img')) {
                                    var img_src = $(e.target).attr('src');
                                    Shadowbox.open({ content: ROOT+'zoom/?i='+img_src.substr(img_src.indexOf('_')+1), player: 'iframe', width: '950px', height: '570px' });
                                }
                                
                                });
            
            break;
            
        case 'zilian-tv':
            $('.list_col_Thumbs li').hover(function(){
                    $(".description", this).stop().animate({top:'0'},{queue:false,duration:300});
                }, function() {
                    $(".description", this).stop().animate({top:'90px'},{queue:false,duration:300});
                });		
        
        
            $('.share_video').click(function(e){
                                    $('.copy_text_tv').toggle('slow');
                                    e.preventDefault();
                                    });
            
            $('.copy_text').click(function(e) { $(this).select(); });
            
            break;
            
        case 'cart':
            
            $('.cart-remove').click(removeProduct);
            $('.update-form').submit(updateProduct);
            $('.product-quantity').keypress(allowOnlyNumbers)
                                  .each(function(i, e) {
                                        $(e).data('ori_val', $(e).attr('value'));
                                  })
                                  .keyup(function(event) {
                                            if($(this).data('ori_val') != $(this).attr('value'))
                                                 $(this).parents('.update-form:first').find('.refreshValue').css('visibility', 'visible');
                                            else
                                                $(this).parents('.update-form:first').find('.refreshValue').css('visibility', 'hidden');
                                         });
            break;
            
        case 'cart-address':
            //$('.get-voucher').submit(getVoucher);
            break;
            
        case 'zicard.list':
            $('.zicard-filter').change(function() { $('#zicard-filter-form').submit(); });
            
            $('.redeem-zis').each(function(i, elem) {
                                      $(elem).attr('onclick', '');
                                  });
            
        case 'zicard.item':
            $('.redeem-zis').click(function(e) {
                                      e.preventDefault();
                                   
                                      if(is_logged)
                                          Shadowbox.open({ content: $(e.currentTarget).attr('href'), player: 'iframe' });
                                      else {
                                          login_redir = $(e.currentTarget).attr('href');
                                          Shadowbox.open({ content: $(e.currentTarget).attr('href'), player: 'iframe' });    
                                      }
                                      
                                   });
            break;
            
        case 'zicard.partners':
            
            $('.toggler').each(function()
			{
				$(this).toggle(function() {
					$(this).next().slideDown();
				}, function() {
					$(this).next().slideUp();
				});
			});
            
			break;
	
	}
    
	if(typeof(usr_activate) != 'undefined') 
	    Shadowbox.open({ content: ROOT+'activate/?'+usr_act_msg, player: 'iframe', width: 680, height: 140 });
	
	if(typeof(usr_login) != 'undefined')
	    Shadowbox.open({ content: ROOT+'entry', player: 'iframe', width: 592, height: 185 });
}

$(document).ready(domLoaded);

