$(document).ready(function () {

    $('.tweetlink').click(function (el){
        //if (!is_logged_in) return true;
        tweetTo(unescape($(this).attr('href').replace(/http:\/\/twitter.com\/home\?status=/i, '').replace(/\+/g, ' ')));
        return false;
    });
    
    $(".navigator").change(function() {
        window.location.href = $(this).attr('baseurl')+'/'+$(this).val();
    });

    $('.navigable').change(function(){
        window.location.href = $(this).attr('folder') + $(this).val();
    });


    subscribeTextCounter($('#postfield'), '#textcounter');

    $('.more_data').click(moreHandler);

   $('.labelled').blur(function(){
        if ($(this).val()=='')
            $(this).val($(this).attr('blurvalue'));
    }).focus(function(){
        if ($(this).val()==$(this).attr('blurvalue'))
            $(this).val('');
    });


 //refer:http://svgweb.googlecode.com/svn-history/r635/trunk/src/svg.htc
 //Fix for IE hang issue during page unload
if ($.browser.msie){
    window.attachEvent("onbeforeunload",function(){
        if (window.__flash__removeCallback) {
            window.__flash__removeCallback =
              (function() {
                return function(instance, name) {
                  if (instance) instance[name] = null;
                }
              })();
          }
    });
}

});

var moreHandler = function(dummy, element, c) {
    var anchor = element || $(this);
    var container = c;
    $.ajax({
        beforeSend:function(request){
            anchor.next('span.more_error').remove();
            anchor.after(loader);
        },
        complete:function(request){
            
            anchor.next('img').remove();
        },
        dataType:'json',
        type:'get',
        url: anchor.attr('href')+'/?ajax=true',
        success:function(data, textStatus) {
            //data = JSON.parse(data);
            if (data.error)
            {
                anchor.next('img').remove();
                anchor.after('<span class="more_error error">'+data.error+'</span>');
            }
            else
            {
                if ("undefined" != typeof(container))
                    container.find('.more_item:last').after(data['items']);
                else
                    $('.more_item:last').after(data['items']);
                //remove the more link, if all the tweets have been fetched
                if (data['more_exists']!=true)
                {
                    anchor.next('img').remove();
                    anchor.remove();
                }
                else //update the link otherwise
                {
                    anchor.attr('href', data['next_page']);
                    anchor.show(); //show the see more button only on success
                }

            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            anchor.after('<span class="more_error error">We encountered an error. Please try again!!</span>');
        }
    });
    return false;
};


deleteRecord = function(entry)
{
    $.post(entry.attr('href'), {
        id: entry.attr('id')
        }, function(data, textStatus) {
        if (data=='')
        {
            entry.next('img').remove();
            entry.parent().parent().fadeOut(500, function() {
                entry.parent().parent().remove();
            });
        }
    });
    entry.after(loader);
};

shareThisCallback = function(SharedObject)
{
    alert(SharedObject.properties.title + "\n" + SharedObject.properties.url);
}

function shareThis(media_id)
{
    /*var object = SHARETHIS.addEntry({
        title:'Share Photo',
    }, {onclick:shareThisCallback} );*/
    return false;
}

function subscribeTextCounter(elem, counter_seclector)
{
    elem.twitterCounter({
        limit: 140,
        counter: counter_seclector,
        okSize: 140,
        okStyle: '.ok',
        watchSize: 20,
        watchStyle: '.watch',
        warningSize: 10,
        warningStyle: '.limitwarning',
        errorSize: 0,
        errorStyle: '.limitexceeded'
    });
}

function moderate(element) {
    if (!confirm('Are you sure to do this operation?')) return false;
    var entry = $(element);
    $.post(entry.attr('href'), {info: entry.attr('info')}, function(data) {
        if (data=='')
        {
            entry.next('img').remove(); //remove the loader
            entry.before('<span style="color:#ff0000">Done</a>');
            entry.remove();
        }
    });
    entry.after(loader);
    return false;
};


/* FUCNTIONS.JS */
// Copy part of http://sports.orange.fr/includes/nav/js/functions.js
// Create tabs for the right results panel
$.fn.initTab = function(params) {
	var params = $.extend({bloc: 0}, params);
	var el = this;
	var bloc = params.bloc;
	if(bloc != 0){ bloc--; }
	$(".tab",this).each(function(i){
		$("b",this).css("padding-left","2px");
		$("b",this).css("padding-right","0");
		var pB = parseInt($(this).css('padding-left'))+parseInt($(this).css('padding-right'));
		$('li:first-child a',this).addClass('first');
		$('li:last-child a',this).addClass('last');
		if(i == 0){
			// First tabs level
			if($.browser.msie && $.browser.version<7){
				$("li a",this).css("float","none");
				$("li b",this).css("float","none");
				$("li:eq(0) a",this).css("margin-left","0");
			}
			// Resize to 100% width
			var wB = $(this).width()-pB;
			var nL = $("li",this).length;
			var wL = Math.floor(wB/nL);
			$("> li",this).width(wL);
			var d = wB - nL*wL - 1;
			for(j=0;j<d;j++){
				$("> li:eq("+j+")",this).width($("li:eq("+j+")",this).width()+1);
			}
		}else{
			// Second tabs level
			$(this).addClass('tab1');
		}
	});
	if( $(this).attr('id') != 'actu' ){
		$(".tab",this).tabs(bloc);
	}
	else{
		$("#actu .tab li:eq(0)").addClass('ui-tabs-selected');
	}
}	 ;

$(function(){
	$("#actu .tab li").click(function () {
		var id = $(this).children().attr("id");
		$("#actualites").load("/includes/nav/features/"+ id +".htm");
		$("#actu .tab li").removeClass();
		$(this).addClass("ui-tabs-selected");
		o_audience();
		return false;
	});
});

function set_all_twitts_tab (elSel) {
	var elNoSel = '2424' ;
	if(elSel == '2424') elNoSel = 'Cup' ;
	document.getElementById('allTwittsTitle' + elNoSel).className = 'all-twitts-title' ;
	document.getElementById('allTwitts' + elNoSel).className = 'all-twitts-tab' ;

	document.getElementById('allTwittsTitle' + elSel).className = 'all-twitts-title all-twitts-titles-selected' ;
	document.getElementById('allTwitts' + elSel).className = 'all-twitts-tab all-twitts-tab-selected' ;
}

// Country Selection
var cs = {
	nbCountries: 32,
	sel: 0,
	marginLeft: 40,
	elMarginRight: 30,

	init: function () {
		for(var i = 1; i < this.nbCountries; i++) {
			$('#playersC'+i).animate({opacity: .5}, 1) ;
			$('#playersT'+i).animate({opacity: 0}, 1) ;
			$('#playersT'+i).css({display: 'none'}) ;
			$('#playersS'+i).animate({opacity: 0}, 1) ;
			$('#playersS'+i).css({display: 'none'}) ;

			$('#playersC'+i).click(function () {
				cs.slideTo('left', parseInt(this.id.substr(8, this.id.length - 8)) + 1) ;
			}) ;
			$('#playersC'+i).mouseenter(function () {
				var id = parseInt(this.id.substr(8, this.id.length - 8)) ;
				if(id != cs.sel) $('#playersC'+id).animate({opacity: 1}, 1) ;
			}) ;
			$('#playersC'+i).mouseleave(function () {
				var id = parseInt(this.id.substr(8, this.id.length - 8)) ;
				if(id != cs.sel) $('#playersC'+id).animate({opacity: .5}, 1) ;
			}) ;
		}

		if(document.getElementById('countriesMenu')) {
			document.getElementById('countriesMenu').style.left = this.marginLeft + 'px' ;
		}

		$('#countriesLeft').click(function () { cs.slideTo('left') ; }) ;
		$('#countriesRight').click(function () { cs.slideTo('right') ; }) ;
	},

	slideTo: function (dir, force) {
		force = force || false ;
		if(force === false && dir == 'left' && this.sel == 0) return ;
		if(force === false && dir == 'right' && this.sel == this.nbCountries - 1) return ;

		var sel = this.sel ;
		var newSel = sel ;
		if(force !== false) newSel = force ;
		var newLeft = this.marginLeft ;

		if(dir == 'right') newSel++ ;
		else if(dir == 'left') newSel-- ;

		for(i = 0; i < newSel; i++) {
			newLeft -= ($('#playersC'+i).width() + this.elMarginRight) ;
		}

		$('#playersT'+sel).animate({opacity: 0}, 175, function () {
			$('#playersT'+sel).css({display: 'none'}) ;
			$('#playersT'+newSel).css({display: 'block'}) ;
			$('#playersT'+newSel).animate({opacity: 1}, 175) ;
		}) ;
		$('#playersS'+sel).animate({opacity: 0}, 175, function () {
			$('#playersS'+sel).css({display: 'none'}) ;
			$('#playersS'+newSel).css({display: 'block'}) ;
			$('#playersS'+newSel).animate({opacity: 1}, 175) ;
		}) ;

		$('#countriesMenu').animate({left: newLeft}, 350) ;
		$('#playersC'+sel).animate({opacity: .5}, 350) ;
		$('#playersC'+newSel).animate({opacity: 1}, 350) ;
		this.sel = newSel ;
	},

	selectionCountries: function (country) {
		country = country || 'all' ;
		var elOneTop = document.getElementById('countriesOneT') ;
		var elAllTop = document.getElementById('countriesAllT') ;

		if(country == 'all') {
			elOneTop.style.display = 'none' ;
			elAllTop.style.display = 'block' ;

			this.slideTo('left', 0) ;
		}
		else {
			elOneTop.style.display = 'block' ;
			elAllTop.style.display = 'none' ;
			document.getElementById('countriesOneTContent').innerHTML = document.getElementById('playersC'+country).innerHTML ;


			if(country != this.sel) {
				var sel = this.sel ;
				$('#playersC'+sel).animate({opacity: .5}, 350) ;
				$('#playersT'+sel).animate({opacity: 0}, 175, function () {
					$('#playersT'+sel).css({display: 'none'}) ;
					$('#playersT'+country).css({display: 'block'}) ;
					$('#playersT'+country).animate({opacity: 1}, 175) ;
				}) ;
				$('#playersS'+sel).animate({opacity: 0}, 175, function () {
					$('#playersS'+sel).css({display: 'none'}) ;
					$('#playersS'+country).css({display: 'block'}) ;
					$('#playersS'+country).animate({opacity: 1}, 175) ;
				}) ;
				this.sel = country ;
			}
		}
	}
} ;

function accounts_sort (colNb) {
	for(var i = 1; i < 4; i++) {
		if(i == colNb) {
			if(document.getElementById('accountsTitleCol'+i).className == 'accounts-titles-col accounts-col-'+i+' accounts-titles-col-b') {
				document.getElementById('accountsTitleCol'+i).className = 'accounts-titles-col accounts-col-'+i+' accounts-titles-col-t' ;
			}
			else {
				document.getElementById('accountsTitleCol'+i).className = 'accounts-titles-col accounts-col-'+i+' accounts-titles-col-b' ;
			}
		}
		else {
			document.getElementById('accountsTitleCol'+i).className = 'accounts-titles-col accounts-col-'+i ;
		}
	}
} ;

var inResizeTwitts = false ;
function resize_twitts_containers () {
    return;
	if(!inResizeTwitts) {
		inResizeTwitts = true ;
		lastSel = '2424' ;
		if(document.getElementById('allTwittsCup').className == 'all-twitts-tab all-twitts-tab-selected') lastSel = 'Cup' ;

		document.getElementById('allTwitts2424Content').style.height = '' ;
		document.getElementById('allTwittsCupContent').style.height = '' ;
		document.getElementById('followTwittsContent').style.height = '' ;

		set_all_twitts_tab('2424') ;
		var height2424 = $('#allTwitts2424').outerHeight() ;
		var height2424Content = $('#allTwitts2424Content').height() ;
		set_all_twitts_tab('Cup') ;
		var heightCup = $('#allTwittsCup').outerHeight() ;
		var heightCupContent = $('#allTwittsCupContent').height() ;
		set_all_twitts_tab(lastSel) ;
		var heightFollowContent = $('#followTwittsContent').height() ;

		var heightTitles = $('#allTwittsTitles').outerHeight() ;
		var heightDay = $('#dayTwitt').outerHeight() ;
		var heightFollow = $('#followTwitts').outerHeight() ;

		var heightTab2424 = heightTitles + height2424 ;
		var heightTabCup = heightTitles + heightCup ;
		var heightRight = heightDay + heightFollow + 15 ;

		var tipHeight = 15 ;
                if($.browser.msie) tipHeight = 0 ;

		if(height2424Content > heightCupContent) {
			$('#allTwittsCupContent').height(height2424Content) ;
			heightCupContent = height2424Content ;
			heightTabCup = heightTab2424 ;
		}
		else if(heightCupContent > height2424Content) {
			$('#allTwitts2424Content').height(heightCupContent) ;
			height2424Content = heightCupContent ;
			heightTab2424 = heightTabCup ;
		}

		var heightTabDif = heightTab2424 - height2424Content ;
		var heightRightDif = heightRight - heightFollowContent ;

		if(heightTab2424 > heightRight) {
			$('#followTwittsContent').height((heightTab2424 - heightRightDif) + tipHeight) ;
		}
		else if(heightRight > heightTab2424) {
			$('#allTwitts2424Content').height(heightRight - heightTabDif) ;
			$('#allTwittsCupContent').height(heightRight - heightTabDif) ;
		}
		inResizeTwitts = false ;
	}
}

$(document).ready(function(){
	


}) ;

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};


/** TEMPLATE.js */

/*Refer: http://briancray.com/2009/05/06/twitter-style-alert-jquery-cs-php/*/
function twitterStyleAlert(message, rawText)
{
    if (typeof(rawText) == 'undefined') rawText = false;
    var $alert = $('#alert');
    var alerttimer = window.setTimeout(function () {
        $alert.trigger('click');
    }, 5000);
    rawText? $alert.text(message):$alert.html(message);
    $alert.animate({height: $alert.css('line-height') || '50px'}, 200)
    .click(function () {
        window.clearTimeout(alerttimer);
        $alert.animate({height: '0'}, 200, function(){
            $alert.html('');
        });
    });
}

function onPost(f)
{
    var form = $(f);
    if ($('#postfield', form).val().length > 140) {
        twitterStyleAlert('Tweet should be within 140 characters!!');
        return false;
    }

    if ($('#postfield', form).val().length == 0) {
        twitterStyleAlert('Please enter a tweet!!');
        return false;
    }

    $.ajax({
        beforeSend:function(request){
            $('.twitter_update_submit', form).attr('disabled','true');
            $.fn.fancybox.showLoading();
        },
        complete:function(request){
            $('.twitter_update_submit', form).removeAttr('disabled');
            $("#fancy_loading").hide();
        },
        data:$.param($(form).serializeArray()),
        dataType:'json',
        type:'post',
        url:$(form).attr('action'),
        success:function(data, textStatus) {
            if (data.error)
                twitterStyleAlert(data.error);
            else
            {
                twitterStyleAlert('Your reaction has been posted to Twitter');
                $('#postfield', form).val($('#postfield', form).attr('default'));
                $('.textcounter', form).html(140 - $('#postfield', form).val().length);
                $('.reply_to', form).val("0");

                if (data.tweet)
                    insertMediaTweet(data.tweet);
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            twitterStyleAlert(textStatus);
        }
    });
    return false;
}

jQuery.fn.twitterCounter = function(options)
{
    if(!$(this)[0])
        return false;
    var curSize=$(this).val().length;
    var charsLeft=options['limit']-curSize;
    var types=['ok','watch','warning','error'];
    var x={};$.each(types,function(){
        var el=this.toString();
        x[el]={
            'Max':options[el+'Size'],
            'Style':options[el+'Style'].substring(0,1)=='.'||options[el+'Style'].substring(0,1)=='#'?options[el+'Style'].substring(1,options[el+'Style'].length):options[el+'Style'],
            'Type':options[el+'Style'].substring(0,1)=='.'?'class':'id'
            };
    });
    for(var i=0;i<types.length;i++)
    {
        var el=types[i].toString();
        if(i+1<types.length){
            var nextEl=types[i+1].toString();
            if(charsLeft>x[nextEl]['Max']&&charsLeft<x[el]['Max']+1){
                clean();
            }
        }
        else
        {
            if(charsLeft<x[el]['Max'])
                clean();
        }
    }
    $(options['counter']).text(charsLeft);
    $(this).one('keyup',function(){
        $(this).twitterCounter(options);
    });

    function clean(){
        if(x[el]['Type']=='class'){
            $.each(types,function(){
                var temp=this.toString();
                if($(options['counter']).hasClass(temp)){
                    $(options['counter']).removeClass(temp);
                }
            });
            $(options['counter']).addClass(x[el]['Style']);
        }
        else
        {
            $(options['counter']).id(x[el]['Style']);
        }
    }
};


function draftTweet(){
    $('#postbox #postfield').trigger('keyup');
    $('#postbox #postfield').focus();
    $('#postbox').slideDown(1000);
    return false;
}

function replyTo(screen_name, status_id){
    if (!is_logged_in)
    {
        window.location.href = '/' + get_site_lang() + '/session/login/?back=' +
            escape(stripSlashAtEnd(window.location.pathname) +
            '/?status=' + escape(encodeURIComponent('@'+screen_name+ ' ') + '&reply_to=' + status_id ));
        return false;
    }
    oldValue=$('#postbox #postfield').val();
    $('#postbox #postfield').val("@"+screen_name+" ");
    $('#postbox .reply_to').val((status_id==null)? 0:status_id); //Set the reply_to_status_id here. This will be sent to server while posting the form
    $('#postbox .dm_reply_to').val('');
    draftTweet();
    return false;
}

function stripSlashAtEnd(s)
{
    if (s.indexOf('/', s.length-1)>=0)
        s = s.substring(0, s.length-1);
    return s;
}

function rtreplyTo(screen_name, status_id, container){
    var tweet = $('.message', container).text();
    try {tweet = tweet.replace(/\n/g, '').trim();} catch(exp){};
    if (!is_logged_in)
    {
        window.location.href = '/' + get_site_lang() + '/session/login/?back=' + escape(encodeURI(stripSlashAtEnd(window.location.pathname)) +
            '/?status=' + escape(encodeURIComponent('RT @'+screen_name + ' ' + tweet.replace(/\./g, '___') + ' ')));
        return false;
    }

    $('#postbox #postfield').val("RT @"+screen_name+" "+tweet + " ");
    $('#postbox .reply_to').val(0);
    $('#postbox .dm_reply_to').val('');
    draftTweet();
    return false;
}

function dmreplyTo(screen_name, status_id){
    if (!is_logged_in) return alertLogin('send direct messages');
    $('#postbox #postfield').val("D "+screen_name+' ');
    $('#postbox .reply_to').val(0);
    $('#postbox .dm_reply_to').val(screen_name);
    draftTweet();
    return false;
}

function tweetTo(status)
{
    $.fn.fancybox.showLoading();
    g_status = status;
    //shortenUrl(window.location.href, '_tweetTo'); //@todo bit.ly
    _tweetTo('123');
    return false;
}

function _tweetTo(data)
{
    $("#fancy_loading").hide();

    //@todo bit.ly
    /*/ this is how to get a result of shortening a single url
    var first_result = false;
    for (var r in data.results) {
        first_result = data.results[r];
        break;
    }

    var shortUrl = '';
    if (first_result) shortUrl = (first_result['shortUrl']);

    g_status = g_status + ' ' + shortUrl + ' (via @FootTweet)';*/

    if (!is_logged_in)
    {
        window.location.href = '/' + get_site_lang() + '/session/login/?back=' + escape(encodeURI(stripSlashAtEnd(window.location.pathname) + '/?status=' + 
            escape(encodeURIComponent(g_status.replace(/\./g, '___')))));
        return false;
    }

    $('#postbox #postfield').val(g_status);
    $('#postbox .reply_to').val(0);
    $('#postbox .dm_reply_to').val('');
    draftTweet();
}

function shortenUrl(url, callback_name)
{
    BitlyClient.shorten(url, callback_name);
}


function alertLogin(message)
{
    twitterStyleAlert('Please login to '+message+' <a href="/en/session/login"><img src="/images/signin.png"/></a>');
    return false;
}


jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

function get_site_lang()
{
   var url_str = window.location.pathname;
   var url_arr = url_str.split("/");
   cur_lang = "fr";
   if(url_arr.length > 1)
      cur_lang = url_arr[1];

  return cur_lang;
}

function cookie_hide(el, key)
{
    $('.select_the_team_wrap').parent().slideUp(600);
    $.cookie(key, true, {'expires': 10000, 'path' : '/'});
    return false;
}

function toggleInput(button)
{
    var image = $('img', button);
    $.ajax({
        url: button.attr('href') + image.attr('src').replace(/.png/, ''),       //extension corrupts the url
        dataType: 'text',
        beforeSend:function(){
            button.after(loader);
        },
        complete:function(){
            button.show();
            button.next('img').remove();
        },
        success:function(data, textStatus) {
            image.attr('src', data);
        }
    });
}
