  
 var zoneFromPath;
 var zone;
  
 var zonesMap = {
    'fiba':'20300',
    'europe':'19961,20244',
    'asia':'19963,20243',
    'africa':'19962,20241',
    'americas':'19965,20242',
    'oceania':'19964,20245'
 };
  
  var zonesArticleMap = {
      'africa':'6263',
      'americas':'6264',
      'asia':'6265',
      'europe':'6266',
      'oceania':'6267',
      'fiba':'6907'
 };
  
  function isUserLoggedIn() {
    return ($.cookie("UIC")!=null && $.cookie("user")!=null);  
  }
  
  function logout() {
     
       $.cookie('userSubscribed', null, {path:'fibatv.com'});
     
     document.cookie = 'UIC=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';  
     document.cookie = 'userRegistered=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';  
     document.cookie = 'userSubscribed=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com'; 
     document.cookie = 'UIS=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com'; 
     document.cookie = 'SIC=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';
     document.cookie = 'ptvliv=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';
     document.cookie = 'ptvliet=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';
     document.cookie = 'ptvuid=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';
     document.cookie = 'ptvzon=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';
     document.cookie = 'user=e;expires=Fri, 17 Dec 2010 10:00:00 GMT;path=/;domain=fibatv.com';
     location.reload();
  }

function updateHomeVideos(zone) {
  updateLatestVideos('latestVideoContent', zone);
  updateMostWatchedVideos('mostWatchedVideoContent', zone);
}
  
function updateFooterNews(container, zone) {
   var url = '/fragment/fibatv/fragments/pageContent/footer/footerNewsRSSFeed/rssFeedXml/' + zone;
  
   $.ajax({
    url: url,
    dataType: "html",
    beforeSend: function(){$('.footer_news .loading').show();},
    success: function (data) {
      $('.footer_news .loading').hide();
      $('.' + container).html(data);
      if(zone == 'allzones') {
        $('.' + container + ' .allZones').html('All Zones');
      } else {
        $('.' + container + ' .allZones').html(capitalize(zone));
      }
    }
  });
}
  
function updateMostWatchedVideos(container, zone) {
   var url = '/fragment/fibatv/fragments/assets/mostWatchedVideoAjax/searchString/';
  
   var filterAppend = 'iTypeIds=11&sortf=numberViews&sortd=desc&sortfType=number&rl=3';
  
   if(zone != 'allzones') {
     filterAppend = filterAppend + '&11filterIn_categoryId=' + zonesMap[zone] + '/zone/' + zone;
   }
  
   var url = url + filterAppend;
  
   $.ajax({
    url: url,
    dataType: "html",
    success: function (data) {
      $('.' + container).html(data);
      if(zone == 'allzones') {
        $('.' + container + ' .allZones').html('All Zones');
      } else {
        $('.' + container + ' .allZones').html(capitalize(zone));
      }
    }
  });
}
  
function updateLatestVideos(container, zone) {
   var url = '/fragment/fibatv/fragments/assets/latestVideoAjax/searchString/';
  
   var filterAppend = 'iTypeIds=11&sortf=videoDate&sortd=desc&rl=3';
  
   if(zone != 'allzones') {
     filterAppend = filterAppend + '&11filterIn_categoryId=' + zonesMap[zone] + '/zone/' + zone;
   }
  
   var url = url + filterAppend ;
  
   $.ajax({
    url: url,
    beforeSend: function(){$('.homeVideoListing .loading').show();},
    dataType: "html",
    success: function (data) {
      $('.homeVideoListing .loading').hide();
      $('.' + container).html(data);
      if(zone == 'allzones') {
        $('.' + container + ' .allZones').html('All Zones');
      } else {
        $('.' + container + ' .allZones').html(capitalize(zone));
      }
    }
  });
}
  
function updateNewsreaderVideos (container, zone) {
  var url = '/fragment/fibatv/fragments/assets/carouselAjax/searchString/';

  var filterAppend = 'iTypeIds=1&sortf=publishedDate&sortd=desc&sortftype=number&1filterIn_detailTypeCategoryIdExpr=6082';
  
  if(zone != 'allzones') {
    filterAppend = filterAppend + 'a' + zonesArticleMap[zone] + '/zone/' + zonesArticleMap[zone];
  }
  
  var url = url + filterAppend;
  
  $.ajax({
    url: url,
    beforeSend: function(){$('#newsreaderWrap .loading').show();},
    dataType: "html",
    success: function (data) {
      $('#newsreaderWrap .loading').hide();
      $('#' + container).html(data);
      if(zone == 'allzones') {
        $('#' + container + ' .allZones').html('All Zones');
      } else {
        $('#' + container + ' .allZones').html(capitalize(zone));
      }
    }
  });
  
}

function capitalize(obj) {
        val = obj;
        newVal = '';
        val = val.split(' ');
        for(var c=0; c < val.length; c++) {
           newVal += val[c].substring(0,1).toUpperCase() +
           val[c].substring(1,val[c].length) + ' ';
        }
        return newVal;
}

var userRegistered;
  
function isUserRegistered() {
if(!isUserLoggedIn()) {
                       return false;
                      } 
                 else {  
                       userRegistered = true;
                       } 
                        return userRegistered; 
                     }
  
var userSubscribed;
  
function isUserSubscribed() {
  if(!isUserLoggedIn()) {
    return false;
  } else {  
    return perform.isSubscribed();
  }
}
 
$(function() {
  
  if ( isUserLoggedIn() ) {
      var subscribed = isUserSubscribed();
      
      if(!subscribed) {
        $('#homeSubBanner a').attr('href', '/buy');
        $("#homeSubBanner").show();
        $(".subscribeOverlay").show();
      }
  
      if(subscribed) {
        $(".subscribeOverlay").hide();
        $(".footerRegisterNowBanner").hide();
        $("#homeSubBanner").hide();
      }
  
      $(".nav_loggedOut").hide();
      $(".nav_loggedIn").show();
      var firstName = $.cookie('user').substring($.cookie('user').indexOf('firstname=')+10,$.cookie('user').indexOf('&lastname='));
      $('.navSignup').prepend('Hi, '+firstName);
    } else {
      $(".footerRegisterNowBanner").show();
      $(".subscribeOverlay").show();
      $('#homeSubBanner a').attr('href', '/buy');
      $("#homeSubBanner").show();
      $(".nav_loggedOut").show();
      $(".nav_loggedIn").hide();  
    }
  
  $(".schedule_tournament img").error(function () {
    $(this).unbind("error").attr("src", "/javaImages/59/a3/0,,12805~9872217,00.gif");
  });
  
  $("#homeCarousel li").live('mouseover', function() {
      $(this).find('.carouselTeaserImage').hide();
      $(this).find('.carouselWatchNow').show();
  });
  
  $("#homeCarousel li").live('mouseout', function () {
      $(this).find('.carouselTeaserImage').show();
      $(this).find('.carouselWatchNow').hide();
  });
  
  $('.sign_out').click(function() {
    logout();
    return false;
  });
  $('.jcarousel-zones .fibaZonesDropDown ul li').live('click', function() {
    var className = this.className.replace('Zone','');
    updateNewsreaderVideos('homeCarouselWrap', className);
    $('.jcarousel-zones .fibaZonesDropDown ul').toggle();
  });
  
  $('.homeVideoListing .fibaZonesDropDown ul li').live('click', function() {
    var className = this.className.replace('Zone','');
    updateHomeVideos(className);
    if(className == 'allzones') {
       $('.homeVideoListing .allZones').html('All Zones');
    } else {
       $('.homeVideoListing .allZones').html(capitalize(className));
    }
    
    $('.homeVideoListing .fibaZonesDropDown ul').toggle();
  });
  
  $('.footer_news .fibaZonesDropDown ul li').live('click', function() {
    var className = this.className.replace('Zone','');
    updateFooterNews('footerLatestNews', className);
    if(className == 'allzones') {
       $('.footer_news .allZones').html('All Zones');
    } else {
       $('.footer_news .allZones').html(capitalize(className));
    }
   
    $('.footer_news .fibaZonesDropDown ul').toggle();
  });
  
  $('#siteSearchNavValue').click(function() {
    this.value='';
  });
  
  $('#siteSearchNav .navSearch').click(function(){
    var search_term = $('#siteSearchNavValue').val();
    if(search_term == '') {
      $(location).attr('href',zone+'/videolist');
    } else {
      $(location).attr('href',zone+'/search/searchText/'+search_term);
    }
    return false;
  });
});
  
  $('#siteSearchNav').submit(function() {
  if ($(siteSearchNavValue).val() != '') {
  var searchValue = $(siteSearchNavValue).val();
  location.href = "http://www.fibatv.com/search?" + searchValue;
  }
  else {
  alert('please enter a search value');
  }
  return false;
  });
$(function() {  
  $('.sitedropDownLink a').click(function() {
        $('.siteDropDown').toggle();
        $(this).toggleClass('dropped');
        return false;
  });
 });
  
$(function() {  
  $('.navSignIn a').click(function() {
        $('.siteNavLogin').toggle();
        $(this).toggleClass('dropped');
        return false;
  });
 });  
  
function showVideo(clipId, configXML, divId, width, height, startSec, endSec) {
        $('#teaserImage' + clipId).hide();   
        $('.teaserPlay').hide();
        if (swfobject.hasFlashPlayerVersion("10")) {
          var params = {
            wmode:"transparent",
            allowScriptAccess:"always",
            base:"/",
            bgcolor: "#ffffff",
            allowFullScreen:"true"
          };
          var flashVars = {
            configXML: configXML,
            selectedBandwidth:"med",
            setPlayerType:"vod",
            locale:"en_GB",
            resourceLocalePath:"/ptvFlash/unifiedplayer/assets/resources/",
            useMetaSizing:"true",
            disableControls:"false",
            omnitureAccount: "",
            useInitialSplashScreen: "false",
            clipId:clipId,
            vodStartTime:startSec,
            vodEndTime:endSec
          };
          swfobject.embedSWF("/flash/unifiedplayer/UnifiedPlayer.swf", divId, width, height, "10", false, flashVars, params, {})
        }
          document.getElementById(divId).style.display = 'block';
          document.getElementById(divId).style.visibility = 'visible';    
          $('#teaserVideo' + clipId).show();
}
  
function hoverItem(index) {
  $("#homeCarousel li").removeClass("selected");
  $("#homeCarousel li:eq("+index+")").addClass("selected");
  jQuery.newsreader.pause();
  jQuery.newsreader.changeItem(jQuery.newsreader.getPosition(),index);
  jQuery.newsreader.start();
  if('.teaserPlay') {
      $('.teaserImage').show();
      $('.teaserPlay').show();
      $('.teaserVideo').hide();
      $('.vodPlayer').html("");
  }
}
  
$(function() {  
    //alert($.cookie("UIS"));
    if($.cookie("UIS") == 'false'){
      $('.promo_lb.sub .promo_links').attr('href','/buy');  
    }
  
    $('.subContent').live('click', function() {

      if(!isUserSubscribed()) {
        $(".promo_l #loginForm input[name='login.successRedirectUrl']").val($(this).children("a:first").attr('href'));
        $('.promo_lb.sub').jqm();
        $('.promo_lb.sub').jqmShow();
        return false;
      }
    });
  
    $('.footerLatestNews ul li').ellipsis();
    $('.vodListings .innerHeadline').ellipsis();
  
    $('.promo_lb.sub .close_promo').live('click', function() {
      $('.promo_lb.sub').jqmHide();
      
      return false;
    });
  
    $('.promo_lb.reg .close_promo').live('click', function() {
      $('.promo_lb.reg').jqmHide();
      
      return false;
    });
  
    $('.promo_lb.sub .forgot_user, .promo_lb.sub .forgot_pass').live('click', function() {
      $('.promo_lb.sub').jqmHide();
      $('#forgot_user').jqmShow();
      return false;
    });
  
     $('.promo_lb.reg .forgot_user, .promo_lb.reg .forgot_pass').live('click', function() {
      $('.promo_lb.reg').jqmHide();
      $('#forgot_user').jqmShow();
      return false;
    });
});


$(function() {
//  $('.allZones').click(function() {
  //  $(this).next().toggle();
 // });
  
  $(document).click(function(e) {
    var target = e.target;
    if (!$(target).is('.fibaZonesDropDown ul') && !($(target).is('.allZones')) && !$(target).parents().is('.fibaZonesDropDown ul')) {
        $('.fibaZonesDropDown ul').hide();
    }
  });
});  

  
$(function(){  
  
  if (window.location.search == '?loginError'){
    $('.siteNavLogin .warning').css('display','block');
    $('.siteNavLogin').show();
  }
  
  $('#loginForm .username,#loginForm .password').change(function(){
 
    if($(this).val() == ''){
      $(this).prev('.error').show().prev('.label').hide();
      $('.error.warning').show();
    }
    else{
      $(this).prev('.error').hide().prev('.label').show();
      $('.error.warning').hide();
    }
  });
  
  $('.login_form').submit(function(){
    
    $(this).children('.username,.password').each(function(){
      if($(this).val() == ''){
        $(this).prev('.error').show().prev('.label').hide();
        $('.error.warning').show();
      }
      else{
        $(this).prev('.error').hide().prev('.label').show();
        $('.error.warning').hide();
      }
    });
  
    if($(this).children('.username').val() != '' && $(this).children('.password').val() != ''){
      return true;
    }
    else{
     return false;
    }
  
  });
    
  function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  }
  
  var myClose = function() {
    $('.navigationBand #forgot_user form, #forgot_pass form,.navigationBand #forgot_user .visible, .navigationBand #forgot_pass .visible').show();
    $('.navigationBand #forgot_user .failed, .navigationBand #forgot_pass .failed').hide();
    $('.navigationBand #forgot_user .success, .navigationBand #forgot_pass .success').hide();
  };
  
  $('#forgot_user').jqm({
    trigger: '.navigationBand .forgot_user',
    overlay: 70
  });
  
  $('#forgot_pass').jqm({
    trigger: '.navigationBand .forgot_pass',
    overlay: 70
  });
  
  $('.close_lb').click(function(){
    $('.navigationBand #forgot_pass,.navigationBand #forgot_user').jqmHide();
    myClose();
    return false;
  });
  
  
  $('#forgotPassForm').ready(function(){
    $('#forgotPassForm').validate({
      rules:{
        email: {
          required: true,
          email: true
        }
      },
      messages: {
        email:{
  required: '<div class="formError">Please enter a valid email address</div>',
  email: '<div class="formError">Please enter a valid email address</div>'
        }
      },
      submitHandler: submitPasswordRecovery,
      errorPlacement: function(error, element) {
       $('#forgotPassForm .visible').after(error);
      },
       success: function(label) {
        // set &nbsp; as text for IE
        label.html("&nbsp;").addClass("checked");
      }
    });
  });
  
  
  
  $('#forgottenUsernameForm').submit(function(){
    
    var forgot_email = $(this).children("input[type='text']").val();
    var forgot_field_name = $(this).children("input[type='text']").attr('name');
    var form_action = $(this).attr('action');
  
    var current_form = $(this);

    $.ajax({
                  url: form_action,
                  type: "POST",
                  dataType: "xml",
                  data: forgot_field_name + '=' + forgot_email,
                  beforeSend: function(){current_form.hide(); current_form.parent().children('div.loading').show

(); },
                  error:function(){alert('There was an error please try again.');},
                  success: function(xml){
                    current_form.parent().children('div.loading').hide();
  
                    $(xml).find('recoveryusername').each(function(){
                      var success = $(this).attr('success');
                    
                      if(success=='true'){
                        current_form.parent().children('div.success').show();
                        current_form.hide();
                      }
                      else{
                        current_form.show();
                        current_form.children('div.visible').hide();
                        current_form.children('div.failed').show();
                      }
                    });
  
                    $(xml).find('recoveryPasswordToken').each(function(){
                      var success = $(this).attr('success');
                    
                      if(success=='true'){
                        current_form.parent().children('div.success').show();
                        current_form.hide();
                      }
                      else{
                        current_form.show();
                        current_form.children('div.visible').hide();
                        current_form.children('div.failed').show();
                      }
                    });
                    
                 }
    });
  
    return false;
  });
  
});
  
  function submitPasswordRecovery(){

    $.ajax({
      url: '/system/recovery/passwordtoken',
      type: 'POST',
      data: 'url=/ForgottenPassword/Step/2/&email='+$('#forgotPassForm input[name="email"]').val(),
      cache: false,
      dataType: "xml",
      error: function(jqXHR, textStatus, errorThrown){
        alert(textStatus);
      },
      success: function(data){
        var errorMsg = '';
        var recoveryPasswordToken= $('recoveryPasswordToken', data);
        if (recoveryPasswordToken.length === 0 || typeof recoveryPasswordToken.attr('success')==='undefined' || (recoveryPasswordToken.attr('success')!== 'false' && recoveryPasswordToken.attr('success')!=='true')){
          errorMsg += 'Some enexpected error occured, please try again. We are sorry for inconvinience.';
        }else if(recoveryPasswordToken.attr('success') === 'false'){
          var errors = {};
          var anyMessages = false;
          $('field', recoveryPasswordToken).each(function(){
            var message = "Unexpected error occured, please try again with different value. We are sorry for inconvinience";
            switch ($(this).attr('errorCode')){
              case "MISSING":
                message = "This field is required";
                break;
              case "RECOVERY_PASSWORD_EMAIL_NOT_FOUND":
                message = "The specified email was not found";
                break;
            }

  errors[$(this).attr('name').replace('.','_')] = '<div class="formError"><div class="message">'+message+'</div></div>';
            anyMessages = true;
          });
          if (anyMessages){
            $.data($('#forgotPassForm').get(0),'validator').showErrors(errors);
          }else{
            errorMsg += 'Some enexpected error occured, please try again. We are sorry for inconvinience.';
          }
        }else{
          //success redirect to payment area
          displayPasswordEmailSentMessage();
        }
        if (errorMsg!==''){
          alert(errorMsg);
        }
      }
    });
  }
 
  
  function displayPasswordEmailSentMessage(){
    $('#forgotPassForm').replaceWith(
      $('<p>Follow instructions sent to your email to change your password.</p>')
    );
  }
  
  
/*  
function logFormCheck(form) {
  SetCookie('attemptedSubscribeAjax', 'false');
  var formSubmitted = false;
  if (qs['target']) {
   setTargetLoginTarget($(form),qs['target']);
 } else if (GetCookie('target')) {
   setTargetLoginTarget($(form),GetCookie['target']);
 }

 var errorMsg = "";
 var makeFocus = "";

 if (form.login_username.value == "") {
   errorMsg += "Please enter your userName first.\n";
   makeFocus = form.login_username;
 }
 if (form.login_password.value == "") {
   errorMsg += "Please enter a Password\n";
   if (typeof makeFocus != "object" && makeFocus == "") {
     makeFocus = form.login_password;
   }
 }
 if (errorMsg != "") {
   var errorMsgPre = "Sorry, there are some errors with the form!\n\n";
   var errorMsgPost = "\nPlease review the errors before submitting the form.";
   alert(errorMsgPre + errorMsg + errorMsgPost);
   if (makeFocus != "") {
     makeFocus.focus();
   }
 } else {
   formSubmitted = true;
 }
 if(formSubmitted){
  var redirectPath = window.location.href;
  setTargetLoginTarget(redirectPath);
 }
 return formSubmitted;
}              
*/
  

  
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10){minutes = "0" + minutes}

var s = ((13-hours)*60 + (30-minutes))*60 ; 
  
//alert(s);  
  
setTimeout(function(){make_live();home_make_live();},4000); 
setInterval(function(){make_live();home_make_live();},60000);
  
function make_live(){
  $('.later .tournament_time').each(function(index){
    var secs_to_live = $(this).attr('class').replace('tournament_time ','').substring(1);
  
    t = $(this).parent().parent().parent().prev().children('.schedule_tournament:last .tournament_title').text();
    this_header = $(this).parent().prev().children('.tournament_title').text();
  
    if(secs_to_live <= 1800){
  
      if($(this).parent().parent().parent().prev().children('.schedule_tournament').length != 0){
        if(this_header == t){$(this).parent().prev().hide();}  
        $(this).parent().parent().insertAfter($(this).parent().parent().parent().prev().children('.schedule_tournament:last'));
      }
      else{
        $(this).parent().parent().insertAfter($(this).parent().parent().parent().prev().children('.no_events'));
        $('.live .no_events').removeClass('visible');
      }
  
      if($('.later .schedule_tournament').length == 0){$('.later .no_events').addClass('visible');}
    }
    else{
      new_time = secs_to_live - 120;
      $(this).removeClass('m'+secs_to_live).addClass('m'+new_time);
    }
    
  });
}  
  
function home_make_live(){
  $('#home_schedule .on_today .tournament_time').each(function(index){
    var secs_to_live = $(this).attr('class').replace('tournament_time ','').substring(1);
  
    if(secs_to_live <= 1800){
      $(this).siblings('.tournament_status').children('.blank').hide();
      $(this).siblings('.tournament_status').children('.live').css({'display':'block'}).removeClass('soon');
  
  // Update Friday night - remove if statement if things go awry
      if(!($(this).parent().children('.tournament_status').children('.live').is(":visible"))) {
         updateNewsreaderVideos('homeCarouselWrap', $('#homeCarouselWrap .allZones').html().replace(' ', '').toLowerCase());
      } 
    }
    else{
      new_time = secs_to_live - 120;
      $(this).removeClass('m'+secs_to_live).addClass('m'+new_time);
    }
  });
}  
 
$(function(){  
    var zoneFromPath = location.pathname.split('/')[1];
  
    if(zoneFromPath == 'europe' || zoneFromPath == 'africa' || zoneFromPath == 'asia' || zoneFromPath == 'americas' || zoneFromPath == 'oceania') {
      zone = '/' + zoneFromPath;
    } else {
      zone = '';
    }

    var d = new Date();
    var gmtOffset = -d.getTimezoneOffset()/60;

    function no_zero(string){
     if(string.length == 1){
      string = new String(string);
      return string = "0" + string;
     }
     else{
      string = new String(string);
      return string = string.toString();
     }
    }

    da = new Date();
    dy = da.getFullYear();  
    m = da.getMonth() + 1;  
    dd = da.getDate();  
    ys = new String(dy);
    ms = new String(m);
    ds = new String(dd);

    var local_today = ys + no_zero(ms) + no_zero(ds);
    var today = '/today/'+local_today

    var s_zone = "";    

    if(zone!=""){s_zone = "/zone"+zone;}
  
   var s_date= local_today;
  
   $.Tache.Get({
        url: "/fragment/fibatv/fragments/assets/home_schedule/date/"+s_date+s_zone + "/gmtOffset/"+gmtOffset+today ,
        beforeSend: function(){$('#home_schedule #s_loading').show();},  
        success: function(data){
          $('#s_loading').hide();  
          $('#home_schedule .schedule_main').html(data);

          sort_matches('.schedule_main');
        }
   });
  
   /*
   $.Tache.Get({
        url: "/fragment/fibatv/fragments/assets/footer_schedule/date/"+s_date+s_zone + "/gmtOffset/"+gmtOffset+today ,
        success: function(data){ 
          $('.footer_live .live').html(data);
        }
   });
  
   $.Tache.Get({
        url: "/fragment/fibatv/fragments/assets/footer_schedule_later/date/"+s_date+s_zone + "/gmtOffset/"+gmtOffset+today ,
        success: function(data){ 
          $('.footer_live .later').html(data);
        }
   });*/

   $('#home_schedule .fibaZonesDropDown li').click(function(){
     var zone_id = $(this).attr('class').replace("Zone", "");
     $('#home_schedule .no_events').hide();

     if(zone_id == 'allzones'){
       //if($('#home_schedule .schedule_tournament').length ==0){$('#home_schedule .no_events').show();}
       $('#home_schedule .schedule_tournament').show();
       $('#home_schedule .fibaZonesDropDown .allZones').text($(this).text());

     }
     else{
       //if($('#home_schedule .schedule_tournament.' + zone_id).length ==0){$('#home_schedule .no_events').show();}
       $('#home_schedule .schedule_tournament').hide();
       $('#home_schedule .schedule_tournament.' + zone_id).show();
       $('#home_schedule .fibaZonesDropDown .allZones').text($(this).text());
       
     }
     var t_zone = "/t_zone/"+zone_id;
     $.Tache.Get({
        url: "/fragment/fibatv/fragments/assets/home_schedule/date/"+s_date+s_zone + "/gmtOffset/"+gmtOffset+today+t_zone ,
        beforeSend: function(){$('#home_schedule #s_loading').show();},  
        success: function(data){
          $('#s_loading').hide();  
          $('#home_schedule .schedule_main').html(data);
  
          sort_matches('.schedule_main');  
        }
     });
   
     $('#home_schedule .fibaZonesDropDown ul').toggle();

     return false;
   });
  
   
});
  
function sort_matches(container_div){

  var t_array = [];
  var tournament ='';
  var last_tournament='';
  var t_round ='';
  var last_round ='';
    
  $(container_div+" .schedule_tournament").each(function(){
      var match_class = $(this).attr('class').split(" ");
      var match_count = match_class.length;

      t = match_class[match_count-1].substring(1);
      
      t_array.push(t);
  });
  
  t_array = remove_dups(t_array);
  t_array.sort();
  t_array.reverse();
  
  $(container_div+' .schedule_tournament .tournament_header').removeClass('visible');
  $(container_div+' .schedule_tournament .tournament_round').removeClass('visible');;

  for(var i in t_array){
    if (isNumber(t_array[i])){
      $(container_div+' .no_events').after($(container_div+' .schedule_tournament.s'+t_array[i]));
    }
  }

  $(container_div+' .schedule_tournament').each(function(){
    
    var tournament = $(this).children().children('.tournament_title').html();
    var t_round = $(this).children().children('.tournament_round').html();
    
    if(last_tournament != tournament){$(this).children('.tournament_header').addClass('visible');}
    if((last_tournament != tournament || last_round != t_round) && t_round!=''){$(this).children().children('.tournament_round').addClass('visible');}
    
    last_tournament = tournament;
    last_round = t_round;
  });
}  
  
function remove_dups(arrayName){
  var newArray=new Array();
  label:for(var i=0; i<arrayName.length;i++ )
  {  
  for(var j=0; j<newArray.length;j++ )
  {
  if(newArray[j]==arrayName[i]) 
  continue label;
  }
  newArray[newArray.length] = arrayName[i];
  }
  return newArray;
} 
 
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}  

