﻿var basket = function(type, fbVersionsWithCar, fbVersionsWithNoCar){
    this.type = type;
    this.fbVersionsWithCar = fbVersionsWithCar || 380;
    this.fbVersionsWithNoCar = fbVersionsWithNoCar || 240;
}

basket.prototype.AddParams = function(co_id, inSearchPage, config/*, checkFreeProd*/){
    return {"co_id":co_id, "inSearchPage":!!inSearchPage}
}

// add a product
basket.prototype.Add = function(co_id, inSearchPage, config/*, checkFreeProd*/){
    $.fancybox.showActivity();
    
    var me = this;
    
    $.ajax({
        type: "POST",
        url: "/WS/wsProdotti.asmx/" + this.type + "Add",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(this.AddParams(co_id, inSearchPage, config/*, checkFreeProd*/)),
        dataType: "json",
        success: function(data){
            $.fancybox.hideActivity();
            if (data.d.htmlPop){
                if(data.d.type === "versions"){
                    var div = $(data.d.htmlPop);
					//alert ($(div).height());
                    //var width = div.find('div.version_wrap').size() * 145;
					var width = 750;
                    var height = div.find('p.caratteristiche').size() ? me.fbVersionsWithCar : me.fbVersionsWithNoCar;
                    $.fancybox(data.d.htmlPop, {width:width, height:height, autoDimensions:false});
                    
                    var opz_1 = 0;
   					var opz_2 = 0;
   					var opz_3 = 0;
					var versionScroll = $('.scrollable');
					versionScroll.css('margin-top','22px');
					versionScroll.find(".opz_1").each(function() {
						opz_1 = $(this).height() > opz_1 ? $(this).height() : opz_1;
					}).height(opz_1);
					versionScroll.find(".opz_2").each(function() {
						opz_2 = $(this).height() > opz_2 ? $(this).height() : opz_2;
					}).height(opz_2);
					versionScroll.find(".opz_3").each(function() {
						opz_3 = $(this).height() > opz_3 ? $(this).height() : opz_3;
					}).height(opz_3);
                    
					var opz_title = 0;
					var altezzaEl = $('#fancybox-content .version_wrap:eq(0)').height() + 29;
					$('#fancybox-content .scrollable').css('height', altezzaEl.toString() + 'px');
					$("#fancybox-content p.title").each(function() {
						opz_title = $(this).height() > opz_title ? $(this).height() : opz_title;
						}).height(opz_title);
				    $.fancybox.resize();
                }else{
                    me.refreshHTML(data.d, true);
                    $.fancybox(data.d.htmlPop,
                        // nel caso ci siano select
                        {onComplete:function(){
                        beautifySelect.call($('#fancybox-content'))
                        }});
                    
                }
            }else{
                //if (inSearchPage)
                me.refreshHTML(data.d, true);
                $.fancybox.close();
            }
        }
    })
    
    return false;
}

//*****************************
//  aratari: aggiungo un metodo che non mostra il fancy ma manda direttamente sul form di richiesta
// LO AGGIUNGO PER EVITARE RIPERCUSSIONI ANCHE SUL CARRELLO DELLO SHOP
basket.prototype.AddAndGo = function(co_id, inSearchPage, pagina_redirect, config/*, checkFreeProd*/) {

    var me = this;

    $.ajax({
        type: "POST",
        url: "/WS/wsProdotti.asmx/" + this.type + "Add",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(this.AddParams(co_id, inSearchPage, config/*, checkFreeProd*/)),
        dataType: "json",
        success: function(data) {
            if (data.d.htmlPop) {
                window.location.href = "/" + technogym_page.country + "/offer/" + pagina_redirect
            } else {
                //if (inSearchPage)
                me.refreshHTML(data.d, true);
                $.fancybox.close();
            }
        }
    })

    return false;
}


// increment a product
basket.prototype.Inc = function(index){
    $.fancybox.showActivity();
    
    var me = this;
    
    $.ajax({
       type: "POST",
       url: "/WS/wsProdotti.asmx/" + this.type + "Inc",
       cache: false,
       contentType: "application/json; charset=utf-8",
       data: '{index:' + index + '}',
       dataType: "json",
       success: function(data){
         me.refreshHTML(data.d, true);
         $.fancybox.hideActivity();
       }
    })
    
    return false;
}
    
// dec a product
basket.prototype.Dec = function(index){
    $.fancybox.showActivity();
    
    var me = this;
    
    $.ajax({
       type: "POST",
       url: "/WS/wsProdotti.asmx/" + this.type + "Dec",
       cache: false,
       contentType: "application/json; charset=utf-8",
       data: '{index:' + index + '}',
       dataType: "json",
       success: function(data){
         me.refreshHTML(data.d);
         $.fancybox.hideActivity();
       }
    })
    
    return false;
}

// dec a product
basket.prototype.Remove = function(index){
    $.fancybox.showActivity();
    
    var me = this;
    
    $.ajax({
       type: "POST",
       url: "/WS/wsProdotti.asmx/" + this.type + "Remove",
       cache: false,
       contentType: "application/json; charset=utf-8",
       data: '{index:' + index + '}',
       dataType: "json",
       success: function(data){
         me.refreshHTML(data.d);
         $.fancybox.hideActivity();
       }
    })
    
    return false;
}
// ricarica l'html se glielo passo, altrimenti lo carico via ajax
basket.prototype.Reload = function(data){
    if (data){
        this.refreshHTML(data);
        return;
    }
    
    var me = this;
    
    $.ajax({
       type: 'POST',
       url: '/WS/wsProdotti.asmx/' + this.type + 'Reload',
       cache: false,
       contentType: 'application/json; charset=utf-8',
       data: '{w:"s"}',
       dataType: 'json',
       success: function(data){
         me.refreshHTML(data.d);
       }
    })
    
    return false;
}

basket.prototype.GetConfValues = function(){
    var cars = $('#fancybox-content').find('select');
    
    // validate data
	var err = false;	
	cars.each(function(i){
	    var lbl = $(this).parent().prev().find('label');
        if (lbl.filter(":contains('*')").html() != null)  
        {
            if ($(this).val().length == 0){
                err=true; 
                lbl.css({color: "#c00" })
            } 
			else
			    lbl.css({color: "" })
        } 
	});	
	
	if (err) return;
	//

    var config = {};
    cars.each(function(){
        config[this.id.substring(6)] = Number($(this).val());
    })
    
    return config;
}

// configura un nuovo prodotto
basket.prototype.Configure = function(co_id, inSearchPage/*, checkFreeProd*/){
    var config = this.GetConfValues();
    if (config)
        this.Add(co_id, inSearchPage, config/*, checkFreeProd*/)
}

// modifica la configurazione di un prodotto già inserito
basket.prototype.Edit = function(index, pop){
    $.fancybox.showActivity();
    
    var me = this;
    
    if (pop === true){ // step 1, apro il popup
        $.ajax({
           type: "POST",
           url: "/WS/wsProdotti.asmx/" + this.type + "Edit",
           cache: false,
           contentType: "application/json; charset=utf-8",
           data: '{index:' + index + ', config:null}',
           dataType: "json",
           success: function(data){
             $.fancybox(data.d.html,
                // nel caso ci siano select
                {
                    onComplete:function(){beautifySelect.call($('#fancybox-content'))}
                }
             );
             //$.fancybox.hideActivity();
           }
        })
    }else{ // step 2, salvo la nuova configurazione
        var config = this.GetConfValues();
        if (config){
            $.ajax({
               type: "POST",
               url: "/WS/wsProdotti.asmx/" + this.type + "Edit",
               cache: false,
               contentType: "application/json; charset=utf-8",
               data: JSON.stringify({index:index, config:config}),
               dataType: "json",
               success: function(data){
                 me.refreshHTML(data.d);
                 $.fancybox.close();
               }
            })
        }
    }
    
    return false;
}


/* offer */
var offerBasket = new basket('Offer')
offerBasket.refreshHTML = function(data, productAdded){
    $('div.col_right').html(data.html);
    
    offerBasket.quoteboxOverlay();
    
    if (productAdded === true){
        var inte = 140;
	    $("#button_modifica").fadeOut(inte).fadeIn(inte).fadeOut(inte).fadeIn(inte).fadeOut(inte).fadeIn(inte);
	}
}
offerBasket.quoteboxOverlay = function() { // funzione che rende opaca la lista se è vuota
    var lq = $('.right_quote ul.list_quoted');
    
    if (lq.find('>li>span.title').size() === 0){
        lq.find('li:first').prepend('<div class="semitrans"></div>');
	    var transLayeH = lq.height() + 26;
	    var transLayeW = lq.width() + 26;
	    lq.find('div.semitrans').css({'height' : + transLayeH + 'px', 'width' : + transLayeW + 'px'});
    }
}

/* offer */

/* offer form */
var offerFormBasket = new basket('OfferForm')
offerFormBasket.refreshHTML = function(data){
    $('#conferma_ordine').parent().html(data.html)
}
/* offer form */


/* shop */
var shopBasket = new basket('Shop', 400, 260)

shopBasket.setHeaderCounter = function(count){
    if (typeof(count) == 'undefined') return
    
    var counterHeader = $('div.header_top li.shopping_cart_link span span');
    counterHeader.html(count);
    
    // gestione colore carrello su header
    if (count == "0")
        counterHeader.parent().removeClass('bg_giallo');
    else
        counterHeader.parent().addClass('bg_giallo');
}

shopBasket.refreshHTML = function(data){
    $('#shop_frame').html(data.html + '<div id="chiudi_shopcart"></div>');
    $('div.box_carrello li.shopping_cart_link span').html(data.count);
    shopBasket.setHeaderCounter(data.count);
}

shopBasket.AddParams = function(co_id, inSearchPage, config/*, checkFreeProd*/){
    var p = basket.prototype.AddParams(co_id, inSearchPage, config/*, checkFreeProd*/);
    p.config = config || null;
    //p.checkFreeProd = checkFreeProd === true;
    return p;
}

shopBasket.view = function() {
	$('#choice_iframe, #log_reg_iframe').remove();
            if ( $("#log_reg_iframe, #choice_iframe, #shop_frame").size() == 0 ) {
				
				if ( $('.shopping_cart_link span span').text() != 0 ) {
					$('.header_menu').animate({ height: "470px" }, 800);
				} else {
					$('.header_menu').animate({ height: "200px" }, 800);
				}
				
				$('.header_menu').append("<div id='shop_frame'></div>");
				
				$.ajax({
				   type: 'POST',
				   url: '/WS/wsProdotti.asmx/ShopReload',
				   cache: false,
				   contentType: 'application/json; charset=utf-8',
				   data: '{w:"s"}',
				   dataType: 'json',
				   success: function(data){
						shopBasket.refreshHTML(data.d);
						if (data.d.count === 0) $('#wrap_carrello').height(100);
						$('#shop_frame').delay(800).fadeIn(500);
				   }
				})
				
				
                //$('#shop_frame').delay(800).fadeIn(500);
            } else {
                $('#shop_frame').fadeOut(500);
                $('.header_menu').delay(500).animate({ height: "32px" }, 800);
                	setTimeout("$('#shop_frame').remove();", 800);
            }
	
    return false;
}

shopBasket.promo = function(code){
    $.fancybox.showActivity();
    
    var me = this;
    
    $.ajax({
	   type: 'POST',
	   url: '/WS/wsProdotti.asmx/' + this.type + 'Promo',
	   cache: false,
	   contentType: 'application/json; charset=utf-8',
	   data: JSON.stringify({promocode: code}),
	   dataType: 'json',
	   success: function(data){
			me.refreshHTML(data.d);
			$.fancybox.hideActivity();
	   }
	})
	
	return false;
}

$(document).ready(function() {
		// pulsante chiudi carrello
		$('#shop_frame #chiudi_shopcart').live('click', shopBasket.view);	
		
		// gestione banners offerte shop
		//var lingua = $('body').attr('class');
		//var paese = $('body').attr('id');

		
});

$(function(){
    if (window == parent){
        var basketLinks = $('.shopping_cart_link a');
        if (basketLinks.size() > 0){
			$(".menu ul li:last-child span").addClass("shop_ico");
            shopBasket.Reload()
// @version PAYPAL001
            basketLinks.click(typeof($.fn.formShopStep1) == 'undefined' ? shopBasket.view : function(){return false});
        }
        basketLinks = null;
    }
    return false;
})
/* shop */

/* shop form */
var shopFormBasket = new basket('ShopForm')

shopFormBasket.AddParams = shopBasket.AddParams;
//shopFormBasket.Configure = function(co_id, inSearchPage){shopBasket.Configure.call(shopFormBasket, co_id, inSearchPage)};

shopFormBasket.refreshHTML = function(data){
    if (data.count == 0){
        document.location = '/' + technogym_page.country + '/';
    }else{
        $('#conferma_ordine').parent().html(data.html);
        shopBasket.setHeaderCounter(data.count);
    }
}

shopFormBasket.promo = shopBasket.promo;
/* shop form */

/* offer con redir */
var offerGoBasket = new basket('Offer');
offerGoBasket.redir = 748;

offerGoBasket.AddParams = function(co_id, inSearchPage, config){
    offerBasket.refreshHTML = function(){offerGoBasket.refreshHTML()};
    
    return {'co_id':co_id, 'inSearchPage':'prod'}
}

offerGoBasket.refreshHTML = function(){
    if (typeof(this.redir) == 'numeric')
        document.location = '/' + technogym_page.country + '/viewdoc.aspx?' + this.redir;
    else
        document.location = this.redir;
}

/* offer con redir */
