/* - - - - - - - - - - - - - - - - - - - - 
T E C H N O G Y M - H O M E
THE WELLNESS SYSTEM
http://www.technogym.com
website by websolute
- - - - - - - - - - - - - - - - - - - - */


/*--------------------------------------------------
showreel - linea
--------------------------------------------------*/
function showreelLinea() {
    var thumbs = $("#linea_thumbs .thumb").size();


    $(".thumb").wrapAll('<div class="wrap"><div class="scroll"></div></div>');

    if (thumbs != 6) {
        $("#linea_thumbs").append('<div class="arr_left_1"></div><div class="arr_right_1"></div>');
    }

    var i = 0;
    var e = thumbs - 6;
    $(".arr_right_1").live("click", function () {
        if (i < e) {
            i++;
            $(".scroll").animate({ "left": "-" + ($("#linea_thumbs .thumb").outerWidth() * i) + "px" }, 400);
        }
        return false;
    });
    $(".arr_left_1").live("click", function () {
        if (i > 0) {
            i--;
            $(".scroll").animate({ "left": "-" + ($("#linea_thumbs .thumb").outerWidth() * i) + "px" }, 400);
        }
        return false;
    });
}

/*--------------------------------------------------
why technogym slider
--------------------------------------------------*/
function showreelWhy() {
    var thumbs = $("#thumbs_why .thumb_why").size();
    var $thumb = $("#thumbs_why .thumb_why a");


    $(".thumb_why").wrapAll('<div class="wrap"><div class="scroll_why"></div></div>');
    $("#thumbs_why").append('<div class="arr_left_why"></div><div class="arr_right_why"></div>');
    var i = 0;
    var e = thumbs - 5;
    $(".arr_right_why").live("click", function () {
        if (i < e) {
            i++;
            $(".scroll_why").animate({ "left": "-" + ($("#thumbs_why .thumb_why").outerWidth() * i) + "px" }, 400);
        }
        return false;
    });
    $(".arr_left_why").live("click", function () {
        if (i > 0) {
            i--;
            $(".scroll_why").animate({ "left": "-" + ($("#thumbs_why .thumb_why").outerWidth() * i) + "px" }, 400);
        }
        return false;
    });

    $thumb.click(function () {
        $("#thumbs_why .thumb_why a.on").removeClass("on");
        $(this).addClass("on");
        ind = $thumb.index($(this));
        $('.why_technogym_home .abstract div').hide();
        $(".why_technogym_home .abstract div:eq(" + ind + ")").fadeIn(500);
        $("#viewport_why #scroller_why").animate({ "left": "-" + (ind * 317) + "px" }, 500, function () {
            $("#viewport_why .item").not($("#viewport_why .item:eq(" + ind + ")")).hide().show();
        });
        return false;
    });

    $thumb.eq(0).click();

    /*$(".arr_right_1").click(function() {
    $("#thumbs .thumb a.on").parent().next().find('a').click();
    return false;
    });
    $(".arr_left_1").click(function() {
    $("#thumbs .thumb a.on").parent().prev().find('a').click();
    return false;
    });*/

}


/*--------------------------------------------------
get last tweet
--------------------------------------------------*/
function getTweet() {

    var user = 'Technogym';

    $.getJSON('http://twitter.com/statuses/user_timeline.json?screen_name=' + user + '&count=1&trim_user=true&include_rts=true&callback=?', function (data) {
        if (data.length == 0) return;
        
        var tweet = data[0].text;

        tweet = tweet.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&;\?\/.=]+/g, function (url) {
            return '<a href="' + url + '">' + url + '</a>';
        }).replace(/B@([_a-z0-9]+)/ig, function (reply) {
            return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
        });

        $("#last_tweet p").html(tweet);
    });


}


/*--------------------------------------------------
slide json
--------------------------------------------------*/
function slideJson() {
    // start slideshow 
    var obj = eval(json_data);
    var images = 0;
    for (_obj in obj) images++;
    var totalSlideCount = images;
    var captionStart = 1 + ' / ' + images;
    var eccezione_nazione = false;
    var inizializzazione = true;

    //if (technogym_page.country.toLowerCase() == 'nl' || technogym_page.country.toLowerCase() == 'be') { eccezione_nazione = true; }

    $('.wid_right').html(captionStart);
    if (images > 1) {
        $('#background_home_img').append('<img src="' + json_data.documento1.immagine1.path + '"><img src="' + json_data.documento2.immagine1.path + '">');
    } else {
        $('#background_home_img').append('<img src="' + json_data.documento1.immagine1.path + '">');
    }


	$('#background_home_img').cycle({
		fx: 'fade',
		speed: 700,
		timeout: 5000,
		next: '.widget_header .arr_right',
		prev: '.widget_header .arr_left',
		before: onBefore,
		after: onAfter
	});
   
    function onBefore(curr, next, opts) {
        if (!opts.addSlide)
            return;
        var currentImageNum = $('#background_home_img img').size();
        if (currentImageNum == totalSlideCount) {
            opts.addSlide = null;
            return;
        }
        var pathDoc = json_data["documento" + (opts.currSlide + 3)];
        var nuovoPath = pathDoc.immagine1.path;
        opts.addSlide('<img src="' + nuovoPath + '" />');
    };

    function onAfter(curr, next, opts) {
        /* gestione slider benelux */
//        if (!inizializzazione && totalSlideCount == 2) {
//            if (opts.currSlide == 0) { opts.currSlide = 1; }
//            else { opts.currSlide = 0; }
//        }

        var caption = (opts.currSlide + 1) + ' / ' + images;
        var currDoc = json_data["documento" + (opts.currSlide + 1)];
        var titolo1 = currDoc.titolo;
        var descrizione = currDoc.descrizione;
        var urlimage = currDoc.url;
        var payoff = currDoc.payoff;

        $('.wid_right').html(caption);
        $('.widget_header .heading').html('<a href="' + urlimage + '">' + titolo1 + '</a>').fadeIn(10);
        $('.widget_header .learn_more').attr("href", urlimage);
        $('.widget_header .wid_left').text(descrizione);

        if (payoff === undefined) {
            $('.widget_header .heading').css({ 'font-size': '27px', 'line-height': '1.2' });
            $('.widget_header .heading div').remove();
        } else {
            $('.widget_header .heading').append('<div>' + payoff + '</div>');
            $('.widget_header .heading').css({ 'font-size': '16px', 'line-height': '1.2' });
        };

        /* modifica per il benelux */
//        if (eccezione_nazione) {
//            $('.heading').children('a').css('color', '#FFF797').css('font-weight', 'bold').css('font-size', '16px');
//            $('.heading').children('div').css('font-weight', 'bold').css('font-size', '13px');
//
//            switch ($('.wid_right').text()) {
//                case '1 / 2':
//                    $('a.eccezione_benelux').text('naar de shop');
//                    break;
//                case '2 / 2':
//                    $('a.eccezione_benelux').text('');
//                    break;
//                default:
//                    break;
//            }
//        }

        inizializzazione = false;
        /* -------------- */
    }

};



/*--------------------------------------------------
WELLNESS BLOG
--------------------------------------------------*/
function htmlToText(html) {
    return html
    .replace(/(?:\n|\r\n|\r)/ig, "")
    .replace(/<\s*br[^>]*>/ig, "\n")
    .replace(/<\s*\/li[^>]*>/ig, "\n")
    .replace(/<\s*p[^>]*>/ig, "\n\n")
    .replace(/<\s*script[^>]*>[\s\S]*?<\/script>/mig, "")
    .replace(/<\s*style[^>]*>[\s\S]*?<\/style>/mig, "")
    .replace(/<!--.*?-->/mig, "")
    .replace(/<\s*a[^>]*href=['"](.*?)['"][^>]*>([\s\S]*?)<\/\s*a\s*>/ig, "$2")
    .replace(/(<([^>]+)>)/ig, "")
    .replace(/\n{2,}/g, "\n\n")
    .replace(/\t/g, "")
    .replace(/^\n+/m, "")
    .replace(/ {2,}/g, " ")
    .replace(/&([^;]+);/g, decodeHtmlEntity);
}

decodeHtmlEntity = function (m, n) {
    var code;
    if (n.substr(0, 1) == '#') {
        if (n.substr(1, 1) == 'x') {
            code = parseInt(n.substr(2), 16);
        } else {
            code = parseInt(n.substr(1), 10);
        }
    } else {
        code = ENTITIES_MAP[n];
    }
    return (code === undefined || code === NaN) ? '&' + n + ';' : String.fromCharCode(code);
}
var ENTITIES_MAP = {
    'nbsp': 160,
    'iexcl': 161,
    'cent': 162,
    'pound': 163,
    'curren': 164,
    'yen': 165,
    'brvbar': 166,
    'sect': 167,
    'uml': 168,
    'copy': 169,
    'ordf': 170,
    'laquo': 171,
    'not': 172,
    'shy': 173,
    'reg': 174,
    'macr': 175,
    'deg': 176,
    'plusmn': 177,
    'sup2': 178,
    'sup3': 179,
    'acute': 180,
    'micro': 181,
    'para': 182,
    'middot': 183,
    'cedil': 184,
    'sup1': 185,
    'ordm': 186,
    'raquo': 187,
    'frac14': 188,
    'frac12': 189,
    'frac34': 190,
    'iquest': 191,
    'Agrave': 192,
    'Aacute': 193,
    'Acirc': 194,
    'Atilde': 195,
    'Auml': 196,
    'Aring': 197,
    'AElig': 198,
    'Ccedil': 199,
    'Egrave': 200,
    'Eacute': 201,
    'Ecirc': 202,
    'Euml': 203,
    'Igrave': 204,
    'Iacute': 205,
    'Icirc': 206,
    'Iuml': 207,
    'ETH': 208,
    'Ntilde': 209,
    'Ograve': 210,
    'Oacute': 211,
    'Ocirc': 212,
    'Otilde': 213,
    'Ouml': 214,
    'times': 215,
    'Oslash': 216,
    'Ugrave': 217,
    'Uacute': 218,
    'Ucirc': 219,
    'Uuml': 220,
    'Yacute': 221,
    'THORN': 222,
    'szlig': 223,
    'agrave': 224,
    'aacute': 225,
    'acirc': 226,
    'atilde': 227,
    'auml': 228,
    'aring': 229,
    'aelig': 230,
    'ccedil': 231,
    'egrave': 232,
    'eacute': 233,
    'ecirc': 234,
    'euml': 235,
    'igrave': 236,
    'iacute': 237,
    'icirc': 238,
    'iuml': 239,
    'eth': 240,
    'ntilde': 241,
    'ograve': 242,
    'oacute': 243,
    'ocirc': 244,
    'otilde': 245,
    'ouml': 246,
    'divide': 247,
    'oslash': 248,
    'ugrave': 249,
    'uacute': 250,
    'ucirc': 251,
    'uuml': 252,
    'yacute': 253,
    'thorn': 254,
    'yuml': 255,
    'quot': 34,
    'amp': 38,
    'lt': 60,
    'gt': 62,
    'OElig': 338,
    'oelig': 339,
    'Scaron': 352,
    'scaron': 353,
    'Yuml': 376,
    'circ': 710,
    'tilde': 732,
    'ensp': 8194,
    'emsp': 8195,
    'thinsp': 8201,
    'zwnj': 8204,
    'zwj': 8205,
    'lrm': 8206,
    'rlm': 8207,
    'ndash': 8211,
    'mdash': 8212,
    'lsquo': 8216,
    'rsquo': 8217,
    'sbquo': 8218,
    'ldquo': 8220,
    'rdquo': 8221,
    'bdquo': 8222,
    'dagger': 8224,
    'Dagger': 8225,
    'permil': 8240,
    'lsaquo': 8249,
    'rsaquo': 8250,
    'euro': 8364
};

function getWellnessBlog(){
	// loading
	
	$('.blog_entry').append('<div class="loading" style="text-align:center;"><img src="/img/net/loading.gif"></div>');
	if($('body').is('.it')) {
		RSS = "/blog/feed/";
	} else {
		RSS = "/blog/en/feed/";
	}
	$.ajax({  
		type: "GET",
		url: RSS,
		dataType: "xml",
		contentType: "text/xml",
		success: parseXml,
		error: function(){
			//alert('error');
		}
	});

	function parseDate($date)	{		
	// convert to local string and remove seconds and year //		
		var date = $date.split(' ');
		var d = date[1];
		var m = date[2];
		var y = date[3];
		var mesi = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dec'];
		$.each(mesi,function(i,val){
			if (m==val){
				m = i;
			}
		});
		function toDec(i){
			return ((i>9)?i:'0'+i);
		}
		var month = $('.translate .month span').eq(m).text();
		return '<span class="mese">' + month + '</span> <span class="giorno">' + toDec(d) + '</span> <span class="anno">' + y + '</span>';
	}
	
	function parseXml(xml) {
		// $(".loading").remove();
		$(xml).find('item').each(function(i) {
			if (i==0){
				var tit = '<h3 class="conduit">' + $(this).find('title:eq(0)').text() + '</h3>';
				var date = '<div class="data">' + parseDate($(this).find('pubDate:eq(0)').text()) + '</div>';
				var desc = htmlToText($(this).find('description:eq(0)').next().text());
				var img = '<img src="' + $(this).find('description').next().text().split('src="')[1].split('"')[0] + '" onerror="this.style.display=\'none\';" />';
				var lnk = $(this).find('link:eq(0)').text();
				var readmore = $('.translate .read_more').text();
				str = '<div class="last_post"> <a href="' + lnk + '" target="_blank" class="blog_img">' + img + '</a>' + tit + '<p class="desc">' + desc + '</p><p><a href="' + lnk + '" target="_blank">' + readmore + '</a></p></div>' + date;
				
				$('.blog_entry .loading').remove();
				$('.blog_entry').append(str);
				$('.last_post p.desc').height(342-(140 + $('.last_post h3').height()));
			}
		});
	}
}


/*--------------------------------------------------
init
--------------------------------------------------*/
$(document).ready(function () {

    if (location.search.indexOf('social=false') > 0)
        $.cookie('social', 'false', { expires: 365, path: '/' })

    if (location.search.indexOf('social=true') > 0)
        $.cookie('social', '', { expires: 0, path: '/' })

    if ($.cookie('social') == 'false')
        $("#likebox-frame").remove();
    else
        getTweet();

    showreelLinea();
    showreelWhy();
    //getTweet()
    slideJson();
		getWellnessBlog();
});
