/*FILE: /js/EventManager.js*/
EventManager = {

  storage: new Array(),
  interval_storage: new Array(),
  suspendedEvents: new Array(),

  // Supported events and posibility to generate them
  windowLoad: false,
  windowUnLoad: false,
  bodyClick: false,

  wizardClosed: true,

  receivedAdServerURL: true,
  receivedAdStreamURL: true,
  receivedStreamURL: true,
  receivedMainFreeStreamURL: true,
  beforeTabShow: true,

  onPlayerStatusChanged: true,
  onPlayerClick: true,
  onMediaTypeChanged: true,

  addListener: function(event_name, object_pointer)
  {
    if (typeof eval("this." + event_name) != "boolean")
      return false;

    for (var i = 0; i < this.storage.length; i++) {
      if (this.storage[i]['name'] == event_name)
        if (this.storage[i]['object'] == object_pointer)
          return true;
    }

    new_index = this.storage.length;
    this.storage[new_index] = new Array();
    this.storage[new_index]['name'] = event_name;
    this.storage[new_index]['object'] = object_pointer;

    return true;
  },

  generate: function(event_name, custom_event_object)
  {
    if (typeof eval("this." + event_name) != "boolean" || eval("this." + event_name) != true)
      return false;

    var called_events = 0;

    for (var i = 0; i < this.storage.length; i++) {
      if (this.storage[i]['name'] != event_name)
        continue;

      var current_object = this.storage[i]['object'];
      EventManager.runEvent(current_object, event_name, custom_event_object, null);

      called_events++;
    }

    return called_events;
  },

  runEvent: function(current_object, event_name, custom_event_object, suspended_index)
  {
    var retval = eval("current_object." + event_name + "(custom_event_object)");
    EventManager.processResult(event_name, custom_event_object, current_object, retval, suspended_index);
  },

  processResult: function(event_name, custom_event_object, current_object, retval, suspended_index)
  {
    var is_suspended = (typeof suspended_index == "numeric") ? true : false;

    if (typeof(retval) == "undefined") {
      // Object skips this event because. All right
      if (is_suspended)
        this.suspendedEvents[suspended_index]['status'] = 'skipped';
    }
    else
      if (typeof(retval) == "boolean" && retval == true) {
        // Object processes this event successfully
        if (is_suspended)
          this.suspendedEvents[suspended_index]['status'] = 'done';
      }
      else
        if (typeof(retval) == "boolean" && retval == false) {
          // Object could not process this event. Looks like logic issue
          if (is_suspended)
            this.suspendedEvents[suspended_index]['status'] = 'failed';
        }
        else
          if (typeof(retval) == "number" && retval < 0) {
            // Object want to suspend this issue because data is not ready
            if (is_suspended) {
              var index = suspended_index;
            }
            else {
              var index = this.suspendedEvents.length;
              this.suspendedEvents[index] = new Array();
              this.suspendedEvents[index]['name'] = event_name;
              this.suspendedEvents[index]['object'] = current_object;
              this.suspendedEvents[index]['event_object'] = custom_event_object;
              this.suspendedEvents[index]['suspended_times'] = 0;
              this.suspendedEvents[index]['status'] = 'waiting';
            }

            var suspended_event = this.suspendedEvents[index];
            var timer = window.setTimeout("EventManager.runSuspendedEvent(" + index + ")", (-retval));
            suspended_event['timer'] = timer;
            suspended_event['suspended_times']++;
            suspended_event['interval'] = (-retval);
          }
  },

  runSuspendedEvent: function(index)
  {
    suspended_event = this.suspendedEvents[index];
    window.clearTimeout(suspended_event['timer']);

    if (suspended_event['status'] == 'waiting')
      EventManager.runEvent(suspended_event['object'], suspended_event['name'], suspended_event['event_object'], index);
  },


  cancelSuspendedEvent: function(event_name)
  {
    for (var i = 0; i < this.suspendedEvents.length; i++) {
      if (this.suspendedEvents[i]['name'] == event_name)
        this.suspendedEvents[i]['status'] = 'canceled';
    }
  },

  initInterval: function(object_pointer, method_name, milliseconds)
  {
    var new_index = null;

    for (var i = 0; i < this.interval_storage.length; i++) {
      if (this.interval_storage[i]['name'] == method_name)
        if (this.interval_storage[i]['object'] == object_pointer) {
          if (this.interval_storage[i]['interval'])
            return true;

          new_index = i;
          break;
        }
    }

    if (!new_index)
      new_index = this.interval_storage.length;
    this.interval_storage[new_index] = new Array();
    this.interval_storage[new_index]['name'] = method_name;
    this.interval_storage[new_index]['object'] = object_pointer;
    this.interval_storage[new_index]['interval'] = milliseconds;

    return new_index;
  },

  //! \brief Execute method each milliseconds time
  startInterval: function(object_pointer, method_name, milliseconds)
  {
    var index = this.initInterval(object_pointer, method_name, milliseconds);
    if (typeof index == "boolean")
      return index;
    this.interval_storage[index]['type'] = 'interval';
    this.interval_storage[index]['timerID'] = window.setInterval("EventManager.runInterval(" + index + ")", milliseconds);

    return true;
  },

  //! \brief Execute method each milliseconds time
  startTimeout: function(object_pointer, method_name, milliseconds)
  {
    var index = this.initInterval(object_pointer, method_name, milliseconds);
    if (typeof index == "boolean")
      return index;
    this.interval_storage[index]['type'] = 'once';
    this.interval_storage[index]['timerID'] = window.setTimeout("EventManager.runInterval(" + index + ")", milliseconds);

    return true;
  },

  stopInterval: function(object_pointer, method_name)
  {
    for (var i = 0; i < this.interval_storage.length; i++) {
      if (this.interval_storage[i]['name'] == method_name)
        if (this.interval_storage[i]['object'] == object_pointer) {
          if (!this.interval_storage[i]['interval'])
            return false;

          window.clearTimeout(this.interval_storage[i]['timerID']);
          this.interval_storage[i]['interval'] = 0;
          return true;
        }
    }

    return false;
  },

  runInterval: function(index)
  {
    var interval_data = this.interval_storage[index];

    var object_pointer = interval_data['object'];
    var method_name = interval_data['name'];
    var type = interval_data['type'];

    if (type == 'once') {
      interval_data['interval'] = 0;
      window.clearTimeout(interval_data['timerID']);
    }

    var retval = eval("object_pointer." + method_name + "()");

    return true;
  },

  // Add support window.onload
  generateWindowLoad: function()
  {
    this.windowLoad = true;
    EventManager.generate("windowLoad", {});
    this.windowLoad = false;
  },

  generateWindowUnLoad: function()
  {
    this.windowUnLoad = true;
    EventManager.generate("windowUnLoad", {});
    this.windowUnLoad = false;
  },

  generateBodyClick: function()
  {
    this.bodyClick = true;
    EventManager.generate("bodyClick", {});
    this.bodyClick = false;
  }
}

/*FILE: /js/Countdown.js*/
/*
 * Class for manipulate with timer elements.
 */
function Countdown(divId, timeDifference)
{
	this.startDate = new Date();
	this.timeDifference = parseFloat(timeDifference) * 1000;

	this.oneDay = 1000 * 60 * 60 * 24,
	this.oneHour = 1000 * 60 * 60,
	this.oneMinute = 1000 * 60,
	this.oneSecond = 1000,

	this.conteiner = divId,
	this.spanDay = null;
	this.spanHour = null;
	this.spanMinutes = null;
	this.spanSeconds = null;

	this.days = 0,
	this.hours = 0,
	this.minutes = 0,
	this.seconds = 0,
	this.difference = 0,
	this.interval = null,

  /*
   *  Inicialized timer and set current datas
   */
	this.loadTimer = function()
	{
  	var currentDate =	new Date();
  	this.difference = this.timeDifference;
  	if (this.difference < 0)
  		this.difference = 0;

  	this.setCurrentTimestamp();
  	this.setConteiner();
  	this.updateConteiner();
  	this.interval = setInterval('countdown.updateTimer()',125);
    return true;
	},

  /*
   *  Update timer in setinterval
   */
	this.updateTimer = function()
	{
  	var currentDate =	new Date();
  	this.difference = this.timeDifference - (currentDate.getTime() - this.startDate.getTime());
  	if (this.difference <= 0){
      this.difference = 0;
      /* Load new nearest game */
      clearInterval(this.interval);
      var random = new Date();
      random = random.getTime();
      var url = '/' + Helper.languageCode + '/match/countdown/?random=' + random;
      setTimeout('countdown.callAJAX("'+url+'")',20000);
    }

  	this.setCurrentTimestamp();
  	this.updateConteiner();
    return true;
	},

  this.callAJAX = function(url)
  {
      new Ajax.Updater("countdownBlock", url,{
                                                    evalScripts : true,
                                                    method : "post"
                                                  }
                           );
  },


  /*
   *  Get real count of days, hours, minutes and seconds
   */
	this.setCurrentTimestamp = function()
	{
		this.days = Math.floor(this.difference / this.oneDay );
  	this.hours = Math.floor( (this.difference - this.days * this.oneDay) / this.oneHour);
  	this.minutes = Math.floor( (this.difference - this.days * this.oneDay
  																				- this.hours * this.oneHour) / this.oneMinute);
  	this.seconds = Math.floor( (this.difference - this.days * this.oneDay
																				- this.hours * this.oneHour
																				- this.minutes * this.oneMinute) / this.oneSecond);
    return true;
	},

  /*
   *  Get pointers to clock's DIV's
   */
	this.setConteiner = function()
	{
		this.spanDay = document.getElementById(this.conteiner + "Days");
		this.spanHour = document.getElementById(this.conteiner + "Hours");
	  this.spanMinutes = document.getElementById(this.conteiner + "Minutes");
	  this.spanSeconds = document.getElementById(this.conteiner + "Seconds");
    return true;
	},

  /*
   *  Update clock's DIV's
   */
	this.updateConteiner = function()
	{
		this.spanDay.innerHTML = ( this.days < 10 ? "0" : "" ) + this.days;
		this.spanHour.innerHTML = ( this.hours < 10 ? "0" : "" ) + this.hours;
	  this.spanMinutes.innerHTML = ( this.minutes < 10 ? "0" : "" ) + this.minutes;
	  this.spanSeconds.innerHTML = ( this.seconds < 10 ? "0" : "" ) + this.seconds;
    return true;
	}

}

/*
 * Configure content for current datas from server
 */
function configureCountdown(realTime, inputTeam1, inputTeam2)
{

  document.getElementById("countdownTeam1").innerHTML = inputTeam1;
  document.getElementById("countdownTeam2").innerHTML = inputTeam2;
  document.getElementById("countdownRealTime").innerHTML = realTime;
  return true;

}
/*FILE: /js/Schedule.js*/
function updateSchedule(round, currentMatchId, currentTeamCode)
{
  new Effect.Fade('schedule-container', {duration: 0.2, queue: { position: 'start', scope: 'schedule' }});
  
  new Ajax.Updater('schedule-container', '/' + Helper.languageCode +'/schedule/scheduledMatches/'+round + '/' + currentMatchId + (currentTeamCode ? ('/' + currentTeamCode) : ''),
  {
    onComplete:function() {
     new Effect.Appear( 'schedule-container', {duration: 0.2, queue: { position: 'end', scope: 'schedule' } });
    }
  });
}

function roundsListhener()
{ 
  updateSchedule(customSelectors['rounds'].index, currentMatchId, currentTeamCode)
}

function onGuestMyMatchesClick()
{
  Wizard.signIn(null, Helper.getLocation(), 'my_matches_tab', '/'+Helper.getLang()+'/playlist/');
  return false;
}

/*FILE: /js/Profile.js*/
Profile = {
  editButtonHandler: function(formName)
  {
    this.enableElements(formName);
    $(formName+'-submit-button').show();
    $(formName+'-cancel-button').show();
    $(formName+'-edit-button').hide();
  },
  enableElements: function(formName)
  {
    var elements = Form.getElements(document.forms[formName]);
    for (var i=0; i < elements.length; i++)
      elements[i].disabled = false;
  },
  disableElements: function(formName)
  {
    var elements = Form.getElements(document.forms[formName]);
    for (var i=0; i < elements.length; i++)
      elements[i].disabled = true;
  },
  cancelButtonHandler: function(formName)
  {
    tt_Hide();
    new Ajax.Updater(formName+'-container', '/'+Helper.getLang()+'/profile/renderAccountForms/'+formName,{
	   evalScripts: true
		});
  },
  onFormCompleteHandler: function(formName)
  {
    this.disableElements(formName);
    $(formName+'-submit-button').hide();
    $(formName+'-cancel-button').hide();
    $(formName+'-edit-button').show();
  },
  countryOnChangeHandler: function(value)
  {
    for(var i = 0; i < this.countriesProvincesList.length; i++)
      if(this.countriesProvincesList[i].id == value)
        if(this.countriesProvincesList[i].provinces.length > 0)
        {
          this.refreshProvinceSelect(this.countriesProvincesList[i].provinces);
          this.showProvinceSelect();
        }
        else
        {
          this.showProvinceText();
        }
  },
  showProvinceSelect: function()
  {
    $("UserProfileAccountProvinceIdField").show();
    $("UserProfileAccountProvinceTextField").hide();
  },
  showProvinceText: function()
  {
    $("UserProfileAccountProvinceIdField").hide();
    $("UserProfileAccountProvinceTextField").show();
  },
  refreshProvinceSelect: function(provinces)
  {
    var provinceSelect = $('userprofileaccount-provinceid');
    provinceSelect.options.length = 0;
    for(var i = 0; i < provinces.length; i++)
      provinceSelect.options[i] = new Option(provinces[i].name, provinces[i].id);
  },
  showChangePasswordForm: function()
  {
    $('change-password-form-container').show();
    $('change-password-link-id').hide();
    $('billing-address-block-id').style.marginTop = '66px';
  },
  onChangePasswordFormCompleteHandler: function()
  {
    tt_Hide();
    $('change-password-form-container').hide();
    $('change-password-link-id').show();
    $('billing-address-block-id').style.marginTop = '25px';
    var elements = $('change-password-form-name-form').getElements();
    for(var i = 0; i < elements.length; i++)
    {
      elements[i].value = '';
      elements[i].jControl.valid();
    }
  }
}
/*FILE: /js/Tab.js*/
Tab = Class.create({
  initialize: function( name, tabsContainer, url, isLoaded, isShowed, refresh, refreshPeriod, eventsHandlers)
	{
    this.name = name;
    this.tabsContainer = tabsContainer;
		this.url = url;
		this.isLoaded = ( typeof(isLoaded) == 'undefined'? false: isLoaded );
		this.isShowed = ( typeof(isShowed) == 'undefined'? false: isShowed );
    this.refresh = (typeof(refresh) == 'undefined' ? false : refresh);
    this.refreshPeriod = (typeof(refreshPeriod) == 'undefined' ? 60 : refreshPeriod);
    this.eventsHandlers = ( typeof(eventsHandlers) == 'undefined'? new Object(): eventsHandlers );;
     
		EventManager.addListener('beforeTabShow', this);
  },

  riseEvent: function(event)
  {
     if (typeof(this.eventsHandlers[event]) != 'undefined') 
     {       
       return this.eventsHandlers[event]();
     }
     else 
       return true;  
       
  },
  
  show: function()
	{  
    if(!this.riseEvent('beforeTabShow'))
      return false;
      
	  EventManager.generate('beforeTabShow', this);
          tt_Hide();
    if (!this.isLoaded) {
      if (this.refresh) {
        new Ajax.PeriodicalUpdater(this.getTabContainerName(), this.url, {
          frequency: this.refreshPeriod,
          method: 'get',
          evalScripts : true
        });
        this._show();
      }
      else {
        new Ajax.Updater(this.getTabContainerName(), this.url, {
          onComplete: this._show.bind(this),
          method: 'get',
         evalScripts : true
        });
      }
			this.isLoaded = true;
	  }
	  else
		  this._show();
  },

  _show: function()
	{
    new Effect.Appear( this.getTabContainerName(), {
      duration: 0.2,
      queue: { position: 'end', scope: 'tabs' }
    });

    this.isShowed = true;

		$( this.getButtonName() ).addClassName('active');
	},

	hide: function()
	{
		new Effect.Fade( this.getTabContainerName(), {
		  duration: 0.2,
			queue: { position: 'start', scope: 'tabs' }
		});

	  this.isShowed = false;

		$( this.getButtonName() ).removeClassName('active');
	},

  getTabContainerName: function ()
	{
    return this.name + '-tab';
	},

	getButtonName: function()
	{
    return this.name + '-button';
	},

	beforeTabShow: function( tab )
	{
    if ( this.isShowed
		     && tab.name != this.name
				 && tab.tabsContainer == this.tabsContainer)
		{
		  this.hide();
	  }
	}
});
/*FILE: /js/Popup.js*/
Popup = Class.create({

  initialize: function( container, url, width, height, offsetX, offsetY )
  {
		this.container = container;
    this.url = url;
		this.size = {width: width, height: height};
		this.isShowed = false;
		this.offset = {
		  X: (typeof(offsetX)=="undefined"? 0: offsetX),
			Y: (typeof(offsetY)=="undefined"? 0: offsetY)
		};

    Event.observe(window, 'scroll', this.onDocumentScroll.bindAsEventListener(this));
  },

	open: function( url )
	{
		if( this.isShowed ) return;

    tt_Hide();

		Helper.waiter( this.container + '-content' );

    var position = this.getPosition();
    var blackout = this.getBlackout();

    if( typeof(url) == "undefined" )
      url = this.url;

		new Ajax.Updater(this.container + '-content', url, { evalScripts: true,evalJS:true } );

    $( this.container + '-content' ).setStyle({
      width: this.size.width + 'px',
      height: this.size.height + 'px'
    });

    $( this.container ).setStyle({
      top: position.top + 'px',
      left: position.left + 'px',
      position: 'absolute',
      zIndex: 100
    });

    blackout.setStyle({
      width: document.body.offsetWidth + 'px',
      height: document.body.offsetHeight + 'px'
    });

    blackout.show();
    $( this.container ).show();

    this.isShowed = true;
	},

  onDocumentScroll: function()
	{
		if( this.isShowed )
		{
      var position = this.getPosition();

		  $( this.container ).setStyle({
		    top: position.top + 'px',
				left: position.left + 'px'
			});
	  }
	},

	close: function()
	{
    $( this.container ).hide();
		this.getBlackout().hide();

		this.isShowed = false;
	},

	getBlackout: function()
  {
    if ( !$('blackout') )
    {
      var body = document.getElementsByTagName('body').item(0);
      var backgroundDIV = new Element('div');
          backgroundDIV.id = 'blackout';
          backgroundDIV.addClassName('blackout');
      body.appendChild(backgroundDIV);
    }

    return $('blackout');
  },

	getPosition: function()
	{
    var windowHeight = document.viewport.getHeight();
    var windowWidth  = document.viewport.getWidth();
    var windowScroll = document.viewport.getScrollOffsets();

    var position = {
		  top: ( windowScroll[1] + windowHeight/2 - this.size.height/2 ) + this.offset.X,
      left: Math.round(( windowScroll[0] + windowWidth/2  - this.size.width/2 )) + this.offset.Y
		};

    return position;
	}
});
/*FILE: /js/Helper.js*/
Helper = {

  jumptvURL: "",
  jumptvSSLEnabled: null,
  languageCode: "",
  parnerCode: "",
  location: "",
  sessionCreateTime: "",
  
  getSecureJumpTVUrl: function()
  {
    if (this.jumptvSSLEnabled) 
      return this.jumptvURL.replace(/http:/, "https:");
    else 
      return this.jumptvURL.replace(/https:/, "http:");
  },
  
  getJumpTVUrl: function()
  {
    return this.jumptvURL.replace(/https:/, "http:");
  },
  
  getLang: function()
  {
    return this.languageCode;
  },
  
  getLocation: function()
  {
    return this.location;
  },
  
  getBrowser: function()
  {
  
    var str = navigator.userAgent;
    
    if (str.match(/Firefox\//)) 
      return 'FF';
    else 
      if (str.match(/Opera\//)) 
        return 'OP';
      else 
        if (str.match(/Safari\//)) 
          return 'SA';
        else 
          if (str.match(/Konqueror /)) 
            return 'KO';
          else 
            if (str.match(/MSIE /)) 
              return 'IE';
            else 
              return 'UNKNOWN';
  },
  
  
  getOS: function()
  {
    var str = navigator.userAgent;
    
    if (str.match(/Linux/)) 
      return 'LX';
    else 
      if (str.match(/Windows/)) 
        return 'MS';
      else 
        return 'UNKNOWN';
  },
  
  
  
  refresh: function(url)
  {
    var new_url = '';
    
    if (typeof url != 'undefined' && url) 
      new_url = url;
    else 
      new_url = document.location.href;
    
    new_url = new_url.replace(/#.*/, '');
    
    document.location.href = new_url;
  },
  
  
  getCookie: function(cookieName)
  {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    if (ind == -1 || cookieName == "") 
      return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) 
      ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
  },
  
  setCookie: function(name, value, expires, path, domain, secure)
  {
    var today = new Date();
    
    today.setTime(today.getTime());
    
    if (expires) {
      expires = expires * 1000 * 60 * 60 * 24;
    }
    
    var expires_date = new Date(today.getTime() + (expires));
    
    document.cookie = name + '=' + escape(value) +
    ((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
    ((path) ? ';path=' + path : '') +
    ((domain) ? ';domain=' + domain : '') +
    ((secure) ? ';secure' : '');
  },
  
  addGetParam: function(main_url, param_name, param_value)
  {
    var param_separator = '?';
    if (main_url.indexOf('?') > 0) 
      param_separator = '&';
    
    if (typeof(param_value) == 'object' && param_value === null) 
      return main_url;
    
    return main_url + param_separator + param_name + "=" + encodeURIComponent(param_value);
  },
  
  calculatePopUpPosition: function(width, height, horizontal_align, vertical_align)
  {
    if (horizontal_align != 'center' || vertical_align != 'middle') 
      return;
    
    
    // Calculate windows size and position
    var window_params = {
      x: 0,
      y: 0,
      width: width,
      height: height
    }
    
    if (Helper.getBrowser() == 'IE') {
      window_params.x = window.screenLeft + window.document.documentElement.clientWidth / 2;
      window_params.y = window.screenTop + window.document.documentElement.clientHeight / 2;
    }
    else {
      window_params.x = window.screenX + window.innerWidth / 2 + (window.outerWidth - window.innerWidth - 4);
      window_params.y = window.screenY + window.innerHeight / 2 + (window.outerHeight - window.innerHeight - 25);
    }
    
    window_params.x = parseInt(window_params.x - window_params.width / 2);
    window_params.y = parseInt(window_params.y - window_params.height / 2);
    
    return window_params;
  },
  
  
  getPartnerCode: function()
  {
    return this.parnerCode;
  },
  
  
  waiter: function(element)
  {
    $(element).update('<img src="/img/waiter.gif" alt="waiter"/>');
  },
  
  getElementPosition: function(obj)
  {
    var curleft = 0;
    var curtop = 0;
    
    obj = $(obj);
    
    if (typeof obj.offsetParent !== "unknown" && obj.offsetParent) {
      curleft = obj.offsetLeft;
      curtop = obj.offsetTop;
      while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft - (obj.tagName != 'HTML' ? obj.scrollLeft : 0);
        curtop += obj.offsetTop - (obj.tagName != 'HTML' ? obj.scrollTop : 0);
      }
    }
    return {
      left: curleft,
      top: curtop
    };
  },
  
  riseClickEvent: function(object)
  {
    if (Prototype.Browser.IE) {
      object.fireEvent('onClick');
    }
    else {
      var evt = document.createEvent("MouseEvents");
      evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      object.dispatchEvent(evt);
    }
  },
  
  onButtonClick: function(event)
  {
    var target = Event.element(event);
    
    if (target.tagName != 'A' && target.tagName != 'BUTTON') {
      var tBody = target.parentNode.parentNode;
      
      var links = tBody.getElementsByTagName('a');
      
      if (typeof(links[0]) != "undefined") {
        this.riseClickEvent(links[0]);
        return;
      }
      
      var buttons = tBody.getElementsByTagName('button');
      
      if (typeof(buttons[0]) != "undefined") 
        this.riseClickEvent(buttons[0]);
    }
  },
  
  detectPlayerType: function()
  {
  	if(this.getCookie('wcq_player_type'))
		return;
	
	if(Player.is_wmp_plugin_installed())
		this.setCookie('wcq_player_type', 'application/x-ms-wmp', 30*24*3600*1000, '/');
  }  
};

/*FILE: /js/Wizard.js*/
/**!
 * \file Wizard.js
 * \brief This file consists of Wizard class that can open JumpTV wizards
 *         Don't include this file inside wizards, use Wizard* instead
 * \version 1.0
 */
Wizard = {

  window: null,
  timer_check_closing: null,
  refresh_url: null,
  successful_subscription_refresh_url: null,

  signInWidth: 595,
  signInHeight: 390,

  signUpWidth: 595,
  signUpHeight: 390,

  subscriptionWidth: 595,
  subscriptionHeight: 390,


  is_opened: function()
  {
    return (typeof(this.window) == 'object' && this.window != null && this.window.closed == false);
  },


  signIn: function(product_id, location, trigger, refresh_url)
  {
    if (this.is_opened())
      return;

    if (typeof refresh_url == 'string')
      this.refresh_url = refresh_url;

    // Create URL. NULL values won't be added to URL
    var url = Helper.getSecureJumpTVUrl() + '/' + Helper.getLang() + '/' + 'signin';
    if (typeof product_id == "number" && product_id)
      url += '/' + product_id;

    url = Helper.addGetParam(url, 'cobrand_partner', Helper.getPartnerCode());
    url = Helper.addGetParam(url, 'location', location);
    url = Helper.addGetParam(url, 'trigger', trigger);

    var window_position = Helper.calculatePopUpPosition(this.signInWidth, this.signInHeight, 'center', 'middle');

    this.open(url, window_position);
  },


  signUp: function(product_id, location, trigger, refresh_url)
  {
    if (this.is_opened())
      return;

    if (typeof refresh_url == 'string')
      this.refresh_url = refresh_url;

    // Create URL. NULL values won't be added to URL
    var url = Helper.getSecureUrl() + '/' + Helper.getLang() + '/' + 'signup';
    if (typeof product_id == "number" && product_id)
      url += '/' + product_id;

    url = Helper.addGetParam(url, 'cobrand_partner', Helper.getPartnerCode());
    url = Helper.addGetParam(url, 'location', location);
    url = Helper.addGetParam(url, 'trigger', trigger);

    var window_position = Helper.calculatePopUpPosition(this.signUpWidth, this.signUpHeight, 'center', 'middle');

    this.open(url, window_position);
  },


  subscribe: function(product_id, default_pricing_model_id, location, trigger, refresh_url, successful_subscription_refresh_url)
  {
    if (this.is_opened())
      return;

    if (typeof refresh_url == 'string')
      this.refresh_url = refresh_url;

    if (typeof successful_subscription_refresh_url == 'string')
      this.successful_subscription_refresh_url = successful_subscription_refresh_url;

    // Create URL. NULL values won't be added to URL
    var url = Helper.getSecureJumpTVUrl() + '/' + Helper.getLang() + '/' + 'subscription/' + product_id;
    url = Helper.addGetParam(url, 'cobrand_partner', Helper.getPartnerCode());
    url = Helper.addGetParam(url, 'location', location);
    url = Helper.addGetParam(url, 'trigger', trigger);
    if (default_pricing_model_id)
      url = Helper.addGetParam(url, 'defaultpm', default_pricing_model_id);

    var window_position = Helper.calculatePopUpPosition(this.subscriptionWidth, this.subscriptionHeight, 'center', 'middle');

    this.open(url, window_position);
  },
  
  
  openSubscription: function(formRefence)
  {
    var productId = 0;
    var options = formRefence.elements['paymentOption'];
    for(var i = 0; i < options.length; i++)
      if(options[i].checked)
        productId = options[i].value; 
    
    var pricingId = formRefence.elements['pricing['+productId+']'].value;
    var successful_subscription_refresh_url = formRefence.elements['redirect['+productId+']'].value;
    
    this.subscribe(productId, pricingId, Helper.getLocation(), 'payment_options', null, successful_subscription_refresh_url);    
  },


  open: function(url, window_position)
  {
    var params = new Array();

    var i = -1;
    i++;
    params[i] = 'left=' + window_position.x;
    i++;
    params[i] = 'top=' + window_position.y;
    i++;
    params[i] = 'width=' + window_position.width;
    i++;
    params[i] = 'height=' + window_position.height;

    i++;
    params[i] = 'menubar=no';
    i++;
    params[i] = 'toolbar=no';
    i++;
    params[i] = 'resizable=no';
    i++;
    params[i] = 'scrollbars=no';
    i++;
    params[i] = 'status=no';
    i++;
    params[i] = 'dependent=no';


    // Open wizard
    this.window = window.open(url, 'wizard', params.join(', '));
	try {
    	this.window.focus();
		}
		catch(e) {}


    // Check closing child window
    this.timer_check_closing = window.setInterval(this.check_closing, 100);
    // It'll close child window if visitor closes main one
    EventManager.addListener('windowUnLoad', this);
    // It'll process main window if visitor closes child one
    EventManager.addListener('wizardClosed', this);
  },


  close: function()
  {
    if (this.is_opened()) {
      this.window.close();
      EventManager.generate('wizardClosed', {
        type: 'automatically'
      });
    }
  },


  signOut: function()
  {
    var signOutElement = document.createElement('script');
    signOutElement.type = "text/javascript";
    signOutElement.src = Helper.getJumpTVUrl() + '/controller.php?action=logout&writeJSCode=' + encodeURIComponent("Wizard.afterSignOut();");

    document.body.appendChild(signOutElement);
  },


  /* Events */
  afterSignOut: function()
  {
    Helper.refresh();
  },

  wizardClosed: function()
  {
    if (parseInt(Helper.getCookie('wizard_done')) > 0) {
      if (Helper.getCookie('wizard_done_type') == 'subscription' && this.successful_subscription_refresh_url)
        Helper.refresh(this.successful_subscription_refresh_url);
      else if(this.refresh_url)
        Helper.refresh(this.refresh_url);
      else
        Helper.refresh();
    }
    
    this.refresh_url = null;
    this.successful_subscription_refresh_url = null;
  },


  //! \brief Check closing for subscription window of current browser window
  //! NOTE: function called by timer and hasn't 'this' variable
  check_closing: function()
  {
    if (Wizard.is_opened())
      return;

    window.clearInterval(Wizard.timer_check_closing);

    EventManager.generate('wizardClosed', {
      type: 'manually'
    });
  },


  windowUnLoad: function()
  {
    this.close();
  },

	showPaymentOptions: function( matchId )
	{
    paymentOptionsPopup.open('/'+Helper.getLang()+'/payment_options/view/' + matchId + '/' + Helper.getLocation());
	}
}

/*FILE: /js/customerSupport.js*/
CustomerSupport = {
  sendOK: function()
  {
    document.getElementById("customerSupportFormContent").style.display = 'none';
    document.getElementById("customerSupportSendOK").style.display = 'block';
    return true;
  }
}
/*FILE: /js/topMenu.js*/

topMenu = {

  activePopUpMenu: null,
  topZIndex: 1,
  fixedPopUpMenus: {
    'pop-menu-matches': 0,
    'pop-menu-teams': 160,
    'pop-menu-teams-es': 176
  },

  bindPopUpMenu: function(menuItemId, popMenuId) {

    $(popMenuId).hide();
    $(menuItemId).onmouseover = this.showPopUpMenu.bind(this, popMenuId);
    $(popMenuId).onmouseover = this.clearPopUpMenuHideTimer.bind(this, popMenuId);
    $(popMenuId).onmouseout = this.setPopUpMenuHideTimer.bind(this, popMenuId);
    $(popMenuId + "-trans-area-1").onmouseover = this.hidePopUpMenu.bind(this, popMenuId);
    $(popMenuId + "-trans-area-2").onmouseover = this.hidePopUpMenu.bind(this, popMenuId);
    Event.observe(window, "resize", this.positionPopUpMenu.bind(this, menuItemId, popMenuId, false));
    this.positionPopUpMenu(menuItemId, popMenuId, true);
  },

  positionPopUpMenu: function(menuItemId, popMenuId, initialPosition) {

    var menuItemPosition = Helper.getElementPosition(menuItemId);
    var posLeft = 0;
    var browserOffset = !initialPosition || Helper.getBrowser() == "IE" ? 0 : -8;

    if (this.fixedPopUpMenus[popMenuId] === undefined) {
      posLeft = menuItemPosition.left - 7;
    } else {
      var menuContainerPos = Helper.getElementPosition('top-menu-items');
      var popMenuOffset = this.fixedPopUpMenus[popMenuId + "-" + Helper.getLang()];
      if (popMenuOffset === undefined) {
        popMenuOffset = this.fixedPopUpMenus[popMenuId];
      }
      posLeft = menuContainerPos.left + popMenuOffset;
    }
    posLeft += browserOffset;

    $(popMenuId).setStyle({
      top: menuItemPosition.top + 3 + "px",
      left: posLeft + "px"
    });
  },

  showPopUpMenu: function(popMenuId) {

    if (this.activePopUpMenu && this.activePopUpMenu != popMenuId) {
      this.hidePopUpMenu(this.activePopUpMenu);
    }

    this.topZIndex++;

    $(popMenuId).setStyle({zIndex: this.topZIndex});

    $(popMenuId).show();

    this.activePopUpMenu = popMenuId;
  },

  hidePopUpMenu: function(popMenuId) {

    $(popMenuId).hide();

    this.activePopUpMenu = null;
  },

  setPopUpMenuHideTimer: function(popMenuId) {

    if (!$(popMenuId).hideTimer) {
      $(popMenuId).hideTimer = setTimeout("topMenu.hidePopUpMenu('" + popMenuId + "')", 1000);
    }
  },

  clearPopUpMenuHideTimer: function(popMenuId) {

    if ($(popMenuId).hideTimer) {
      window.clearTimeout($(popMenuId).hideTimer);
      $(popMenuId).hideTimer = null;
    }
  }

}

/*FILE: /js/FormControl.js*/
FormControlPrototype = {

  focused: false,

  initialize: function( id, callback )
	{
		this.jsonHeader = 'text/x-json; charset=utf-8';
		this.owner = $( id );
    this.controls = new Array();
		this.callback = callback;
    this.tags = new Array('input', 'select', 'textarea');

		Event.observe( id, 'submit', this.send.bindAsEventListener(this) )
  },

	send: function( event )
	{
		Event.stop(event);

		for (var i = 0; i < this.controls.length; i++)
		  this.controls[i].valid();


		this.owner.request({
      evalJS: true,
      onComplete: this.onComplete.bindAsEventListener(this)
    });

		return false;
  },

	onComplete: function( transport )
	{
		if (this.jsonHeader == transport.getHeader('Content-type')) {
			var errors = transport.responseText.evalJSON(true);

		  	for (var i = 0; i < this.tags.length; i++) {
		  		var elements = this.owner.getElementsByTagName(this.tags[i]);

		  		for (var j = 0; j < elements.length; j++) {
		  			if (typeof(elements[j].jControl) == 'object' &&
		  			typeof(errors[elements[j].jControl.model]) != "undefined" &&
						typeof(errors[elements[j].jControl.model][elements[j].jControl.field]) != "undefined") {
		  				elements[j].jControl.invalid(errors[elements[j].jControl.model][elements[j].jControl.field]);
		  				return;
		  			}
		  		}
		  	}
				if (this.callback)
          eval(this.callback);
	 }
	},

	onLoad: function()
	{
     var elements = this.owner.getElements();

		  for (var i = 0; i < elements.length; i++) {
				if (elements[i].type != 'hidden' &&
				elements[i].type != 'submit' &&
				elements[i].type != 'select-one') {
			  try {
					$(elements[i]).activate();
					break;
				}
				catch (e) {}
			}
		}
	}
};

FormControl = Class.create( FormControlPrototype );

/*FILE: /js/InputControl.js*/
InputControl = Class.create({

  initialize: function( id )
  {
    var info = $( id ).name.match(/data\[(.*)\]\[(.*)\]/i);

	  this.owner = $( id );
		this.model = info[1];
		this.field = info[2];

    Event.observe( id, 'change', this.valid.bindAsEventListener(this) );
	},

	valid: function ()
	{
    this.owner.removeClassName( 'invalid' );
		tt_Hide();
	},

	invalid: function( message )
	{
		this.owner.focus();
    this.owner.addClassName( 'invalid' );
		this.toolTip( message );
	},

	toolTip: function( message )
	{
    var pos = Helper.getElementPosition( this.owner );

		var top  = pos.top + this.owner.getHeight() + 3;
		var left = pos.left

		if ( $('error-tool-tip-container') )
    {
			var content = $('error-tool-tip-container').innerHTML;
      message = content.replace( '[error-message]', message );
		}

    Tip( message,
		  FIX, [left, top],
			BGCOLOR, '#f9f9ad',
			FOLLOWMOUSE, false,
			STICKY, true,
			BORDERWIDTH, 0,
			SHADOW, true,
			SHADOWCOLOR, '#797865',
			SHADOWWIDTH, 3,
			OFFSETY, 10,
			FONTCOLOR, '#000000'
		);
	}
});
/*FILE: /js/Player.js*/
var SUSPEND_FOR_100_MILLISECONDS = -100;
var SUSPEND_FOR_1_SECOND = -1000;
var HALF_SECOND = 500;
var AS_SOON_AS_POSSIBLE = 10;

Player = {

  fastestServer: null, // contains the server URL that streams fastest between subscriber and server
  fastestServerTime: null, // contains the time in ms for roundtriping between subscriber to fastest server
  fastestBitrate: null, // contains the bitrate between subscriber and fastest server
  fastestBandwidth: null, // contains the bandwidth between subscriber and fastest server
  totalNumberOfServers: null, // contains the total number of servers under test
  updateForm: null, // form is remembered simply to re-enable controls after the test
  log: null, // for debugging
  stopTuneMyVideo: null,
  is_ad_item: false,
  is_buffering: false,
  isWindowLoaded: false,
  autoStart: null,
  fullscreen_enabled: false,

  mainFreeStream: null,
  player_object: null,
  player_type: null,

  state_undefined: 0,
  state_stopped: 1,
  state_paused: 2,
  state_playing: 3,
  state_scan_forward: 4,
  state_scan_reverse: 5,
  state_buffering: 6,
  state_waiting: 7,
  state_media_ended: 8,
  state_transitioning: 9,
  state_ready: 10,
  state_reconnecting: 11,
  state_initializing: 12,

  volume_bar_width: 50,
  progress_bar_width: 384,
  minimal_duration_for_progress_bar: 50,

  enable_move_progress_handle: true,
  previous_volume_value: null,
  previous_player_status: null,

  addGetParam: function(main_url, param_name, param_value)
  {
    var param_separator = '?';
    if (main_url.indexOf('?') > 0)
      param_separator = '&';

    if (typeof(param_value) == 'object' && param_value === null)
      return main_url;

    return main_url + param_separator + param_name + "=" + encodeURIComponent(param_value);
  },

  getStatusMessage: function(status)
  {
    if (status == 1)
      message = "Stopped";
    else
      if (status == 2)
        message = "Paused";
      else
        if (status == 3)
          message = "Streaming";
        else
          if (status == 4)
            message = "Scanning Fwd";
          else
            if (status == 5)
              message = "Scanning Back";
            else
              if (status == 6)
                message = "Buffering";
              else
                if (status == 7)
                  message = "Waiting";
                else
                  if (status == 8)
                    message = "End";
                  else
                    if (status == 9)
                      message = "Preparing";
                    else
                      if (status == 10)
                        message = "Ready";
                      else
                        if (status == 11)
                          message = "Reconnecting";
                        else
                          if (status == 12)
                            message = "Initializing";
                          else
                            message = "&nbsp;";

    if (message != "&nbsp;") ;
	//message = getErrorMessage("jumpPlayer", message);

    return message;
  },

  //! \brief Returns true if browser has WMP plug-in
  is_wmp_plugin_installed: function()
  {
    if (!navigator.userAgent.match(/Firefox/))
      return false;

  	for (var i = 0; i < navigator.plugins.length; i++) 
      for (var j = 0; j < navigator.plugins[i].length; j++) 
      	if (navigator.plugins[i][j].type == "application/x-ms-wmp") 
          return true;

    return false;
  },

  is_playing: function()
  {
    var player = this.getObject();
    if (player.playState && player.playState == this.state_playing)
      return true;

    return false;
  },

  getObject: function()
  {
    if (typeof(this.player_object) == 'object' && this.player_object !== null)
      return this.player_object;

    var player_object = document.getElementById('player_object');
    if (player_object) {
      this.player_object = player_object;
      if (typeof this.player_object.Play == "function")
        this.player_type = "linuxPlugin";
      else
        if (typeof this.player_object.controls == "object")
          this.player_type = "fullPlugin";
        else
          this.player_type = "embededObject";
    }


    return this.player_object;
  },

  is_ad_plays: function()
  {
    if (this.is_ad_item && this.is_playing())
      return true;

    return false;
  },

  fullscreenTuning: function()
  {
    this.btn_fullscreen_enable($('fullscreen_button'));
  },

  btn_play_pause: function(button_object)
  {
    if (this.is_ad_plays())
      return;

    if (this.is_playing()) {
      this.pause();
    }
    else {
      this.play();
    }
  },

  btn_play_pause_over: function(button_object, is_over, translatedTooltip)
  {
    this.Tooltip(translatedTooltip, is_over);
    this.Highlight(button_object, is_over);
  },

  btn_stop: function(button_object)
  {
    if (this.is_ad_plays())
      return;

    this.stop();
  },

  btn_stop_over: function(button_object, is_over, translatedTooltip)
  {
    this.Tooltip(translatedTooltip, is_over);
    this.Highlight(button_object, is_over);
  },

  btn_fullscreen: function(button_object)
  {
    if (this.is_ad_plays())
      return;

    this.fullscreen();
  },

  btn_fullscreen_over: function(button_object, is_over, translatedTooltip)
  {
    this.Tooltip(translatedTooltip, is_over);
    this.Highlight(button_object, is_over);
  },

  btn_fullscreen_enable: function(button_object)
  {
    if (button_object)
      button_object.className = button_object.className.replace(/_over/, '').replace(/_disabled/, '');
  },

  btn_mute: function(button_object)
  {
    if (this.is_ad_plays())
      return;

    this.mute();
  },

  btn_mute_over: function(button_object, is_over, translatedTooltip)
  {
    this.Tooltip(translatedTooltip, is_over);
    this.Highlight(button_object, is_over);
  },

  volume: function(button_object)
  {

  },

  volume_over: function(button_object, is_over, translatedTooltip)
  {
    this.Tooltip(translatedTooltip, is_over);
  },

  volumeSet: function(volume_count)
  {
  	this.setMuteButtonState(false);
  	var width = parseInt(volume_count / (100 / this.volume_bar_width));

    $('volume_count_bar').style.width = width + "px";
    $('volume_handle').style.left = width + "px";

    var player = this.getObject();
  	if (this.player_type == "linuxPlugin") {
  		player.SetVolume(volume_count);
  	}
  	else if (player.settings) {
      player.settings.volume = volume_count;
    }
  },

  progressSet: function(progress_count)
  {
    var player = this.getObject();

    if (this.player_type == "linuxPlugin") {
      player.Seek(progress_count);

      this.updateProgressBar();
    }
    else
      if (player.settings) {
        player.controls.currentPosition = progress_count;

        this.updateProgressBar();
      }
  },

  updateProgressBar: function()
  {
    var player = this.getObject();

    if (this.player_type == "linuxPlugin") {

    }
    else
      if (!(player.settings && player.currentMedia && player.currentMedia.duration > 0 && typeof(player.controls.currentPosition) == 'number'))
        return;

    if (!this.is_buffering) {
      if (this.player_type == "linuxPlugin")
        var width = parseInt((player.getTime() / player.getDuration()) * this.progress_bar_width);
      else {
        var width = parseInt((player.network.downloadProgress / 100) * this.progress_bar_width);
        var handle_pos = parseInt((player.controls.currentPosition / player.currentMedia.duration) * (this.progress_bar_width - 23));
      }

      $('progress_count_bar').style.width = width + "px";
      if (this.enable_move_progress_handle)
        $('progress_handle').style.left = handle_pos + "px";
    }
    else {
      if (this.player_type == "linuxPlugin")
        var width = parseInt((50 / 100) * this.progress_bar_width);
      else
        var width = parseInt((player.network.downloadProgress / 100) * this.progress_bar_width);

      $('progress_count_bar').style.width = width + "px";
    }
  },

  Tooltip: function(translatedMessage, need_show, tipConfig)
  {
    if (!need_show)
      return;

    if (typeof(tipConfig) == "undefined") {
      var tipConfig = new Array();
    }

    tipConfig.unshift(translatedMessage);
    tt_Tip(tipConfig);
  },

  Highlight: function(button_object, need_highlight)
  {
    if (need_highlight) {
      button_object.className = button_object.className.replace(/_over/, '') + '_over';
    }
    else {
      button_object.className = button_object.className.replace(/_over/, '');
    }
  },

  play: function()
  {
    var player = this.getObject();
    if (player.controls) {
      player.controls.play();
      this.updatePlayButton(true);
    }
    else {
      var playerHTML = $('player_container').innerHTML;
      $('player_container').innerHTML = '';
      playerHTML = playerHTML.replace(/(name="autoStart" +value=)(".*?")/gm, '$1"1"');
      $('player_container').innerHTML = playerHTML;

      EventManager.generate('onPlayerStatusChanged', {
        status: this.state_playing
      });
    }
  },
  pause: function()
  {
    var player = this.getObject();
    if (player.controls) {
      player.controls.pause();
      this.updatePlayButton(false);
    }
  },

  updatePlayButton: function(is_playing)
  {
    var player = this.getObject();
    if (!player.controls)
      return;
    if(typeof is_playing == 'undefined')
      state = this.is_playing();

    var newId;
    var oldId;
    if (is_playing)
    {
      newId = 'pause_button';
      oldId = 'play_button';
    }
    else
    {
      newId = 'play_button';
      oldId = 'pause_button';
    }

    var oldClassName = oldId;
    if ($(oldId).className.indexOf('over') > 0)
      oldClassName = oldId + '_over';

    var newClassName = newId;
    if ($(newId).className.indexOf('over') > 0)
      newClassName = newId + '_over';

    $(newId).style.display = 'block';
    $(oldId).style.display = 'none';
    $(newId).className = newClassName;
    $(oldId).className = oldClassName;
  },

  stop: function()
  {
    var player = this.getObject();
    if (player.controls) {
      player.controls.stop();
      this.updatePlayButton();
    }
    else {
      var playerParent = player.parentNode;
      playerParent.removeChild(player);
      var params = player.getElementsByTagName("param");
      for (var i = 0; i < params.length; i++) {
        if (params[i].name == "autoStart") {
          params[i].setAttribute("value", "0");
          break;
        }
      }
      playerParent.appendChild(player);

      EventManager.generate('onPlayerStatusChanged', {
        status: this.state_stopped
      });
    }
  },

  fullscreen: function()
  {
    var player = this.getObject();
    if (player.controls && this.is_playing()) {
      var player = this.getObject();

      player.fullScreen = true;
    }
  },

  mute: function()
  {
    var player = this.getObject();

    if(this.player_type == 'linuxPlugin') {
      if (this.previous_volume_value) {
        player.SetVolume(this.previous_volume_value);
        this.previous_volume_value = null;
	this.setMuteButtonState(false);
      }
      else {
        this.previous_volume_value = player.GetVolume();
        player.SetVolume(0);
	this.setMuteButtonState(true);
      }
    }
    else
      if (player.settings) {
        if (player.settings.mute) {
          player.settings.mute = false;
          this.setMuteButtonState(false);
        }
        else {
          player.settings.mute = true;
	  this.setMuteButtonState(true);
        }
      }
  },

  setMuteButtonState: function(mute)
  {
    if(mute)
    {
      $('mute_button').style.display = 'none';
      $('muted_button').style.display = 'block';
    }
    else
    {
      $('muted_button').style.display = 'none';
      $('mute_button').style.display = 'block';
    }
  },

  generateStatusChanged: function()
  {
    if (this.player_type != "linuxPlugin")
      return;

    var player = Player.getObject();

    if(this.previous_player_status != player.playState) {
      this.previous_player_status = player.playState;
      this.onStatusChanged(this.previous_player_status);
    }
  },

  onStatusChanged: function(new_status)
  {
    var status_message = this.getStatusMessage(new_status);
    $('status_bar_status').innerHTML = status_message;

    if (new_status == this.state_playing) {
      EventManager.startInterval(this, 'updateCurrentPosition', HALF_SECOND);
    }
    else {
      EventManager.stopInterval(this, 'updateCurrentPosition');
    }

    if (new_status == this.state_stopped || new_status == this.state_ready)
      this.updatePlayButton();

    EventManager.generate('onPlayerStatusChanged', {
      status: new_status
    });

    this.updateCurrentPosition();
    this.renderProgressBar();
    this.detectCurrentMediaType();
  },

  onBufferingChanged: function(is_buffering)
  {
    this.is_buffering = is_buffering;

    if (!is_buffering) {
      if (this.detectShowingProgressBar())
        $('progress_handle').style.visibility = "visible";
      $('progress_count_bar').className = $('progress_count_bar').className.replace(" download", "");
    }
    else {
      $('progress_handle').style.visibility = "hidden";
      $('progress_count_bar').className += " download";
    }
  },

  onDoubleClick: function()
  {
    if (this.is_ad_plays())
      window.setTimeout('Player.getObject().fullScreen=false', AS_SOON_AS_POSSIBLE);
  },

  onMediaChanged: function(item)
  {
    this.updateCurrentPosition();
    this.renderProgressBar();
    this.detectCurrentMediaType();
  },

  onMediaTypeChanged: function(item)
  {
    if(item.type == 'ad')
      this.is_ad_item = true;
    else
      this.is_ad_item = false;
  },

  detectCurrentMediaType: function()
  {
    var player = Player.getObject();
    if (typeof player.currentMedia != "object" || player.currentMedia === null)
      return;

    var currentMedia = player.currentMedia;
    var ad_variable1 = currentMedia.getItemInfo("ad");
    var ad_variable2 = currentMedia.getItemInfo("ENTRYID");
    var is_ad_plays = false;
    if((typeof ad_variable1 != "undefined" && ad_variable1 == "true") || (typeof ad_variable2 != "undefined" && ad_variable2))
      is_ad_plays = true;

    EventManager.generate('onMediaTypeChanged', {
      type: (is_ad_plays && (this.is_playing() || this.is_buffering)) ? 'ad' : 'mainvideo'
      });
  },

  detectShowingProgressBar: function()
  {
    var show = false;

    var player = this.getObject();
    if (player.currentMedia) {
      var url = player.currentMedia.sourceURL;

      if ((url.indexOf(".wmv") > 0 || url.indexOf(".asf") > 0) && player.currentMedia.duration >= this.minimal_duration_for_progress_bar)
        show = true;
    }

    return show;
  },

  renderProgressBar: function()
  {
    var player = this.getObject();
    if (player.currentMedia) {
      var show = this.detectShowingProgressBar();

      if (show) {
        this.updateProgressBar();
        EventManager.startInterval(this, 'updateProgressBar', HALF_SECOND);
        $('progress_bar').style.visibility = "visible";
        $('progress_handle').style.visibility = "visible";
      }
      else {
        this.hideProgressBar();
      }
    }
  },

  hideProgressBar: function()
  {
    EventManager.stopInterval(this, 'updateProgressBar');
    $('progress_bar').style.visibility = "hidden";
    $('progress_handle').style.visibility = "hidden";
  },

  updateCurrentPosition: function()
  {
    var current_position = this.getCurrentPosition();
    $('status_bar_time').innerHTML = current_position;
  },

  getCurrentPosition: function()
  {
    var player = this.getObject();
    if (player.controls && this.player_type != "linuxPlugin") {
      return player.controls.currentPositionString;
    }

    return '';
  },

  setMainFreeStream: function(stream_url)
  {
    this.mainFreeStream = stream_url;
  },

  write: function(player_string)
  {
    document.write(player_string);
  },

  panelInit: function()
  {
    var player = this.getObject();

    // Monitor status
    if (this.player_type == "linuxPlugin")
      EventManager.startInterval(this, 'generateStatusChanged', HALF_SECOND);

    // Set volume
    if (this.player_type == "linuxPlugin") {
      this.volumeSet(player.GetVolume());
    }
    else
      if (player.settings) {
        this.volumeSet(player.settings.volume);
      }

    // Enable drag
    Drag.init($('volume_handle'), null, 0, this.volume_bar_width, 9, 0);
    $('volume_handle').onDrag = function(x, y)
    {
      var volume_count = parseInt(x * parseInt(100 / Player.volume_bar_width));
      Player.volumeSet(volume_count);
    };

    Drag.init($('progress_handle'), null, 0, this.progress_bar_width, 9, 0);
    $('progress_handle').onDragStart = function(x, y)
    {
      Player.enable_move_progress_handle = false;
    }
    $('progress_handle').onDrag = function(x, y)
    {
      var player = Player.getObject();
      if (!player.controls)
        return;
    }
    $('progress_handle').onDragEnd = function(x, y)
    {
      var player = Player.getObject();
      if (!player.controls)
        return;

      if (this.player_type == "linuxPlugin")
        var progress_count = (x / Player.progress_bar_width) * player.getDuration();
      else
        var progress_count = (x / Player.progress_bar_width) * player.currentMedia.duration;
      Player.progressSet(progress_count);
      Player.enable_move_progress_handle = true;
    };
  },

  //-------------------------------------------------------------------tune my video functions

  tune_video_for_current_selection: function(forma)
  {
    var server_id = $("tunevideo_server_locn_select").value;
    var id = "server" + server_id;
    var server_url = new Array($(id).value);
    Player.updateForm = forma;
    Player.tune_video("player_object", server_url);
  },
  /*
   * Calls speed_test.js to perform the tuning
   */
  tune_video: function(playerId, servers, maxAllowedBandwidth)
  {
    Player.stopTuneMyVideo = 0;
    // do not tune the preview.
    // initialize
    Player.disableVideoForm(false);
    $('jump_tunevideo_test_results').style.display = 'none';
    //set_results("");
    Player.log = "";
    Player.fastestServer = undefined;
    Player.fastestServerTime = 999999999;
    Player.fastestBitrate = 0;
    Player.fastestBandwidth = 0;
    Player.totalNumberOfServers = servers.length;

    // show progress bar and area//
    var msg = getErrorMessage("TuneMyVideo", "Testing_location_1_of") + Player.totalNumberOfServers + ".";
    //jumpTuneVideoShowProgressArea(0, totalNumberOfServers, msg);
    Player.testProgressLine(1, msg);
    wmPlayer = $(playerId);

    var current_url = wmPlayer.URL;

    if (isMicrosoft())// && !isPreviewStream(getPlayerURL()) )
    {
      runSpeedTest(playerId, servers, Player.tune_video_test_callback, maxAllowedBandwidth);
    }
    else {
      // immediately finish the test for non Microsoft IE browsers and
      // for preview channels ( makes no sense to test the preview file )
      Player.tune_video_test_callback(-1);
    }
  },

  disableVideoForm: function(all)
  {
    if (Player.updateForm == null)
      return;

    Validation.disableForm(Player.updateForm);
    $("tunevideo_btnTestBandwidth").disabled = true;
    $("tunevideo_btnTestBandwidth_container").style.display = "none";
    $("tunevideo_btnTestBandwidth_pseudo").style.display = "block";
    $("tunevideo_btnSave").disabled = true;
    $("tunevideo_btnSave_container").style.display = "none";
    $("tunevideo_btnSave_pseudo").style.display = "block";
    if (all) {
      $("tunevideo_btnCancel").disabled = true;
      $("tunevideo_btnCancel_container").style.display = "none";
      $("tunevideo_btnCancel_pseudo").style.display = "block";
    }
  },

  testProgressLine: function(i, msg)
  {
    if (Player.stopTuneMyVideo != 1) {
      Player.jumpTuneVideoShowProgressArea(i, 20, msg);
      if (i <= 19)
        setTimeout("Player.testProgressLine(" + (i + 1) + ")", 1000);
    }
  },
  // sets progress bar area to visible (e.g. when test starts)
  jumpTuneVideoShowProgressArea: function(currPosn, maxPosn, message)
  {

    if (Player.updateForm == null)
      return;

    progObj = $('jump_tunevideo_progressbar_holder');
    if (progObj) {
      progObj.style.display = "block"; // set holder area visible
      Player.jumpTuneVideoUpdateProgressBar('jump_tunevideo_progressbar', currPosn, maxPosn, message); // start progress bar
    }
  },
  // updates progress bar from 0 to 100% and display current message.
  jumpTuneVideoUpdateProgressBar: function(parentDivID, currPosn, maxPosn, message)
  {
    if (Player.updateForm == null)
      return;

    barObj = $(parentDivID);
    if (barObj)
      barObj.style.display = "block"; // set bar visible
    var maxNotch = 20;
    for (i = 0; i < maxNotch + 1; i++) {
      notchObj = $(parentDivID + "_" + i);
      if (notchObj) {
        if ((i / maxNotch) <= (currPosn / maxPosn)) {
          notchObj.style.display = "block";
        }
        else {
          notchObj.style.display = "none";
        }
      }
    } // for i
    if (message != null) {
      Player.ProgressBarMsg(message);
    }
  },

  ProgressBarMsg: function(message)
  {
    msgObj = $('jump_tunevideo_progress_msg');
    msgObj.innerHTML = message;
  },

  tune_video_test_callback: function(server_index, server_url, time, bitrate, maxBitrate, bandwidth, maxBandwidth)
  {

    if (Player.fastestBandwidth < bandwidth) {

      Player.fastestServer = server_url;
      Player.fastestServerTime = time;
      Player.fastestBitrate = bitrate;
      Player.fastestBandwidth = bandwidth;
    }

    if (server_index == -1) {
      // test has finished

      if (Player.totalNumberOfServers > 1) {

        Player.set_server_selection();
        Player.set_closest_bitrate_selection();
      }

      Player.set_results();

      Player.enableVideoForm();

      //alert("Fastest server="+fastestServer+" bitRate="+fastestBitrate+" bandwidth="+fastestBandwidth + log);
    }
    else {

      // update progress bar
      var progressServer = server_index + 1 + 1; // show the next server
      var msg = getErrorMessage("TuneMyVideo", "Testing_location") + (progressServer) + getErrorMessage("TuneMyVideo", "of") + Player.totalNumberOfServers + ".";
      var bitrateK = Math.round(Player.fastestBandwidth / 1000);
      msg += getErrorMessage("TuneMyVideo", "Downloading_at") + bitrateK + getErrorMessage("TuneMyVideo", "KBsec"); // show fastest rate so far.
      var progressSer = progressServer - 1;
      //jumpTuneVideoUpdateProgressBar('jump_tunevideo_progressbar', progressSer, totalNumberOfServers, msg);
      if (progressServer <= Player.totalNumberOfServers)
        Player.testProgressLine(1, msg);
      else
        Player.jumpTuneVideoHideProgressArea();
    }
    Player.log += ";\nserver_url=" + server_url + " time=" + time + " bitRate=" + bitrate + " maxBitRate=" + maxBitrate + " bandwidth=" + bandwidth + " maxBandwidth=" + maxBandwidth;
  },

  set_server_selection: function()
  {
    if (Player.updateForm == null)
      return;

    var serverOptions = $("tunevideo_server_locn_select").options;

    var serv_url = Player.fastestServer;
    for (var i = 0; i < serverOptions.length; i++) {
      var id = "server" + serverOptions[i].value;
      var server = $(id).value;
      if (serv_url == server) {
        var fastestServer_id = serverOptions[i].value;
      }
    }


    for (var i = 0; i < serverOptions.length; i++) {
      if (serverOptions[i].value == fastestServer_id) {
        $("tunevideo_server_locn_select").selectedIndex = i;
        break;
      }
    }
  },

  set_closest_bitrate_selection: function()
  {
    if (Player.updateForm == null)
      return;

    var fastestBitrateK = Player.fastestBitrate / 1000;
    var bitrateSelect = $("tunevideo_bit_rate_select");
    var bitrateOptions = bitrateSelect.options;

    // bitrates are ordered from highest to lowest
    for (var i = 0; i < bitrateOptions.length; i++) {
      if (bitrateOptions[i].value < fastestBitrateK) {
        bitrateSelect.selectedIndex = i;
        break;
      }
    }
  },

  set_results: function(message)
  {

    if (Player.updateForm != null) {
      // show the results and allow the user to save or not
      Player.jumpTuneVideoHideProgressArea(); // hide progress bar
      if (message == undefined) {
        var fastestBandwidthK = Math.round(Player.fastestBandwidth / 1000);
        message = fastestBandwidthK;

      }
      if (message > 0) {
        //document.getElementById("jump_tunevideo_test_results_val").innerHTML = message;
        $("jump_tunevideo_test_results").innerHTML = getErrorMessage("TuneMyVideo", "Your_bandwidth") + " <span id='jump_tunevideo_test_results_val'>" + message + "</span> " + getErrorMessage("TuneMyVideo", "kbps");
      }
      else {
        $("jump_tunevideo_test_results").innerHTML = getErrorMessage("TuneMyVideo", "Test_failed");
      }
      $("jump_tunevideo_test_results").style.display = 'block';
    }
    else {
      // make an AJAX call to automatically save the preferred server
      var url = "controller.php?action=set_server&preferred_server_name=" + Player.fastestServer;
      HTTPGet(url, null);
    }
  },

  // set progress bar area to invisible (e.g. when test ends or is cancelled)
  jumpTuneVideoHideProgressArea: function()
  {
    if (Player.updateForm == null)
      return;

    progObj = $('jump_tunevideo_progressbar_holder');
    if (progObj) {
      progObj.style.display = "none"; // hide holder area
    }
  },
  enableVideoForm: function()
  {
    if (Player.updateForm == null)
      return;

    Validation.enableForm(Player.updateForm);
    $("tunevideo_btnTestBandwidth").disabled = false;
    $("tunevideo_btnTestBandwidth_container").style.display = "block";
    $("tunevideo_btnTestBandwidth_pseudo").style.display = "none";
    $("tunevideo_btnSave").disabled = false;
    $("tunevideo_btnSave_container").style.display = "block";
    $("tunevideo_btnSave_pseudo").style.display = "none";
    $("tunevideo_btnCancel").disabled = false;
    $("tunevideo_btnCancel_container").style.display = "block";
    $("tunevideo_btnCancel_pseudo").style.display = "none";
  },

  /* Discover the best server location and stream bit rate */

  // user wants to save the tune video settings
  use_tune_video_settings: function(selectedChannel)
  {
    tuneMyVideoTab.selectOpener();
    //		window.location.reload();
    //Player.restartPlayer(true, selectedChannel);
  },
  // user cancelled video tuning
  cancel_tune_video: function()
  {
    if (isRunningSpeedTest()) {
      // cancel the test and disable all controls,
      // which will be enabled when the test naturally finishes
      Player.set_results("Please wait...");
      cancelSpeedTest();
      Player.disableVideoForm(true);
      Player.stopTuneMyVideo = 1;
      Player.enableVideoForm();
    }
    else {
      // return back to default media info screen
      tuneMyVideoTab.selectOpener();
      //restartPlayer(false);
    }
    showBanner = false;
  },


  receivedAdStreamURL: function(event_object)
  {
    // Suspend open URL operation til WMP is waiting Main Stream URL
    if (!Player.mainFreeStream || !Player.isWindowLoaded)
      return SUSPEND_FOR_100_MILLISECONDS;

    if (event_object.url)
      var full_url = this.addGetParam(Player.mainFreeStream, 'ad', event_object.url);
    else
      var full_url = Player.mainFreeStream;

    Player.open(full_url);
  },

  receivedStreamURL: function(event_object)
  {
    var full_url = this.addStreamParams(event_object.url);
    Player.open(full_url);
  },

  receivedMainFreeStreamURL: function(event_object)
  {
    var full_url = this.addStreamParams(event_object.url);
    this.setMainFreeStream(full_url);
  },

  addStreamParams: function(stream_url)
  {
    var full_url = stream_url;

    if (!full_url.match(/[a-z]{2}\/asx\/\d+/))
      return full_url;

    if (!Prototype.Browser.IE && full_url.match(/\/defsess\//)) {
      var phpsessid_match = document.cookie.match(/PHPSESSID=([^;]*)/);
      if (phpsessid_match)
        full_url = full_url.replace(/\/defsess\//, '/' + phpsessid_match[1] + '/');
    }

    return full_url;
  },

  open: function(stream_url)
  {
    var player = this.getObject();

    if (this.player_type == "linuxPlugin") {
      this.stop();
      player.SetURL(stream_url);
      this.hideProgressBar();
      if (this.getAutoStart())
        this.play();
    }
    else
      if (this.player_type == "fullPlugin") {
        this.stop();
        player.URL = stream_url;
        this.hideProgressBar();
        if (this.getAutoStart())
          this.play();
      }
      else {
        var playerHTML = $('player_container').innerHTML;
        var autoStartString = this.getAutoStart() ? '1' : '0';

        $('player_container').innerHTML = '';
        playerHTML = playerHTML.replace(/(name="src" +value=").*?(")/gm, '$1' + stream_url + '$2');
        playerHTML = playerHTML.replace(/(name="autoStart" +value=)(".*?")/gm, '$1"' + autoStartString + '"');
        $('player_container').innerHTML = playerHTML;

        EventManager.generate('onPlayerStatusChanged', {
          status: this.state_playing
        });
      }

    Player.mainFreeStream = null;
  },

  getAutoStart: function()
  {
    if (typeof this.autoStart == "boolean")
      return this.autoStart;

    var param_collection = document.getElementsByTagName('param');
    for (var i = 0; i < param_collection.length; i++) {
      if (param_collection.item(i).name == 'autoStart') {
        this.autoStart = (param_collection.item(i).value == 'true' || param_collection.item(i).value == '1') ? true : false;
        return this.autoStart;
      }
    }
  },

  windowLoad: function()
  {
    Player.isWindowLoaded = true;
  },

  isFullAccess: function()
  {
      this.getObject(); // init
      if (Player.player_type == "fullPlugin")
        return true;

    return false;
  },

	setBitrate: function( bitrate )
	{
		Helper.setCookie('bitrate', bitrate, 100, '/');
    Helper.refresh();
	},

	enablePortugueseASX: function()
  {
    Helper.setCookie('watchPTStream', true, 100, '/');
    Helper.refresh();
  },

	disablePortugueseASX: function()
  {
    Helper.setCookie('watchPTStream', false, -100, '/');
    Helper.refresh();
  }
};

EventManager.addListener('receivedAdStreamURL', Player);
EventManager.addListener('receivedStreamURL', Player);
EventManager.addListener('receivedMainFreeStreamURL', Player);
EventManager.addListener('windowLoad', Player);
EventManager.addListener('onMediaTypeChanged', Player);

/*FILE: /js/Drag.js*/
/**************************************************
 * dom-drag.js
 * 09.25.2001
 * www.youngpup.net
 * Script featured on Dynamic Drive (http://www.dynamicdrive.com) 12.08.2005
 **************************************************
 * 10.28.2001 - fixed minor bug where events
 * sometimes fired off the handle, not the root.
 **************************************************/

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
                ondrag=1;
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y);
		else if (o.yMapper)	ny = o.yMapper(x);

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
							parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
                ondrag=0;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};
/*FILE: /js/CustomSelector.js*/
///        S E L E C T O R    C L A S S
var customSelectors = new Array();
function Selector(id,values,index)
{
  this.id = id;
  this.values = values;
  this.index = index;
  this.highlightIndex = index;
  this.searchWord = '';
  this.listeners = new Array();
  this.skipHide = false;
  this.regionId = null;


  this.showList = function()
  {
      var options = document.getElementById(this.id + "Options");
      if (options) {
        if (options.style.display == "none") {
          options.style.display = "block";
          document.getElementById(this.id + "SelectLeft").className = 'selectLeft-over';
          document.getElementById(this.id + "SelectRight").className = 'selectRight-over';
        }
        else {
          options.style.display = "none";
          document.getElementById(this.id + "SelectLeft").className = 'selectLeft';
          document.getElementById(this.id + "SelectRight").className = 'selectRight';
        }
      }
  };

  this.hideList = function(skipHideCheck)
  {
    if (skipHideCheck && this.skipHide) {
      document.getElementById(this.id + "SelectValue").focus();
      this.skipHide = false;
    }
    else {
      var options = document.getElementById(this.id + "Options");
      if (options) {
        options.style.display = "none";
        document.getElementById(this.id + "SelectLeft").className = 'selectLeft';
        document.getElementById(this.id + "SelectRight").className = 'selectRight';
      }
    }
  };

  this.cancelHide = function()
  {
    this.skipHide = true;
  }

  this.processSelect = function(index,value)
  {
    if(this.index == index){
      this.hideList();
      return;
    }

    this.index = index;
    this.highlightIndex = index;

    document.getElementById(this.id + "SelectValue").value = convertTitle(value);
    var options = document.getElementById(this.id + "Options");
    var dds = options.getElementsByTagName("DD");
    for (var i = 0; i < dds.length; i++) {
      if (dds[i].id == this.id + "Options" + index)
        dds[i].className = "selected";
      else
        dds[i].className = "";
    }

    for (var i = 0; i < this.listeners.length; i++) {

      var retval = this.listeners[i].call(this);
    }
    this.hideList();
  };

  this.keyDetect = function(e)
  {
    var keynum;

    if (window.event) { // IE
      keynum = e.keyCode;
    }
    else if (e.which) { // Netscape/Firefox/Opera
      keynum = e.which;
    }
    var keychar = String.fromCharCode(keynum);

    switch(keynum)
    {
    case 38: // UP
      this.moveOverTo(parseFloat(this.highlightIndex), "up");
      window.event.returnValue = false;
      window.event.cancelBubble = true;
      break;
    case 40: // DOWN
      this.moveOverTo(parseFloat(this.highlightIndex), "down");
      window.event.returnValue = false;
      window.event.cancelBubble = true;
      break;
    case 13: // ENTER
      index = parseFloat(this.highlightIndex);
      value = this.values[index];
      this.processSelect(index, value);
      this.showList();
      break;
    default:
      if (!keychar.search(/[A-Za-z]/)){
        this.searchWord += keychar;
        this.setOver();
        window.setTimeout("customSelectors['" + this.id +  "'].searchWord = '';",500);
      }
    }


    return true;
  };

  this.moveOverTo = function(newIndex, direction)
  {
    switch(direction) {
    	case "up":
        var prev = null;
        for (var i in this.values){
          if (i == newIndex)
            newIndex = prev;
          else
            prev = i;
        }
        moveToIndex = newIndex;
    		break;

      case "down":
        var next = null;
        var stop = false;
        for (var i in this.values){
          if (stop){
            next = i;
            stop = false;
          }
          if (i == newIndex )
            stop = true;
          else
            stop = false;
        }
        if (stop)
          next = i;
        newIndex = next;
        moveToIndex = newIndex;
        break;

      default:
        moveToIndex = index;
        break;
    }
//          document.getElementById( "title").innerHTML = newIndex + " " + this.values[newIndex] + next;
    if (newIndex === null)
      return;

    el = document.getElementById( this.id + "Options" + newIndex);
    if(!el)
      return;

    this.hideOver();
    if (el.className != 'selected' )
      el.className = 'over'
    this.highlightIndex = newIndex;

    var rows = 0;
    for (i in this.values) {
      if (i == moveToIndex)
        break;
      else
        rows += 1;
    };

  };

  this.hideOver = function ()
  {
    var options = document.getElementById(this.id + "Options");
    dds = options.getElementsByTagName("DD");
    for (var i = 0; i < dds.length; i++) {
      if (dds[i].className == "over")
        dds[i].className = "";
    }
  };

  this.setOver = function()
  {
    index = null;
    var search = null;
    var sortedValues = new Array();
    for (var i in this.values)
      sortedValues[i] = this.values[i];
    sortedValues.sort();
    for (var i = 0; i < sortedValues.length && search == null; i++) {
      if (sortedValues[i] != undefined &&
        sortedValues[i].substr(0,this.searchWord.length).toLowerCase() == this.searchWord.toLowerCase())
        search = sortedValues[i];
    }
    if (search === null)
      return;

    for (var i = 0; i < this.values.length && index == null; i++)
      if (this.values[i] == search)
        index = i;

    if (index === null)
      return;
    this.moveOverTo(index, "toIndex");
  };

  this.addListener = function(object_pointer)
  {
    var new_index = this.listeners.length;
    this.listeners[new_index] = object_pointer;

  };

}
///     \   S E L E C T O R     C L A S S

function unconvertTitle(title)
{
  if (current_language_code != "ar" )
    title = escape(title.replace(/ /g,"+"));
    if (title.match(/\.\.\.$/) != null){
      searchCountry = title.substr(0,20);
      for (var i in regionsList)
        if (searchCountry == regionsList[i].substr(0,20))
          title = regionsList[i];
    }

  return title;
}
function convertTitle(title)
{
    title = unescape(title).replace(/\+/g," ");
    if (title.length > 27)
      title = title.substr(0,25) + "...";
  return title;
}

function generateDList(title, activeElement)
{
  var DList = document.getElementById(title + "OptionsDList");
  if (DList.hasChildNodes()) {
    while (DList.childNodes.length >= 1) {
      DList.removeChild(DList.firstChild);
    }
  }

  var count = 0;
  for (var i in customSelectors[title].values) {
		if (typeof(customSelectors[title].values[i]) != 'function'){
      var ddItem = document.createElement('dd');
      if (i == activeElement) {
        ddItem.setAttribute('class', 'selected');
        ddItem.setAttribute('className', 'selected');
      }
      else {
        ddItem.setAttribute('class', '');
        ddItem.setAttribute('className', '');
      }
      ddItem.setAttribute('id', title + 'Options' + i);
      ddItem.setAttribute('count', i);
      ddItem.onmouseover = function(x)
      {
        customSelectors[title].hideOver();
        if (this.className != 'selected')
          this.className = 'over';
      }
      ddItem.onmouseout = function(x)
      {
        if (this.className != 'selected')
          this.className = ''
      }
      ddItem.onmousedown = function(x)
      {
        customSelectors[title].processSelect(this.attributes.count.nodeValue, customSelectors[title].values[this.attributes.count.nodeValue])
      }
      ddItem.innerHTML = convertTitle(customSelectors[title].values[i]);
  		count = count + 1;
      DList.appendChild(ddItem);
		}
  }

  var inputValue = document.getElementById(title + "SelectValue");
  inputValue.value = convertTitle(customSelectors[title].values[activeElement]);

  // check heigh of generated list for change backgrounds vertical aligment
  var content = document.getElementById(title + "Options");
  var conteiner = document.getElementById(title + "OptionsDList");
  content.style.visibility = 'hidden';
  content.style.display = 'block';
  if (content.offsetHeight) { //ns6 syntax
    contentHeight = content.offsetHeight + 20;
  }
  else
    if (content.scrollHeight) { //ie5+ syntax
      contentHeight = content.scrollHeight;
    }
  if (typeof(contentHeight) != 'undefined' && contentHeight < 138 && conteiner != undefined)
    conteiner.style.backgroundPosition = "left bottom";
  else
    conteiner.style.backgroundPosition = "left top";
  content.style.visibility = 'visible';
  content.style.display = 'none';

}

/*FILE: /js/emailFriend.js*/
EmailFriend = {
  emailFriendClose: function()
  {
    tt_Hide();
    document.getElementById("emailFriendFormDiv").style.display = 'none';
    document.getElementById("emailFriendSendOK").style.display = 'block';
    return true;
  },
  emailFriendReset: function()
  {
    tt_Hide();
    document.getElementById('emailFriendForm-form').reset();
    return true;
  }
}
/*FILE: /js/PreRollBannerManager.js*/
PreRollBannerManager = {
	storage: new Array(),
	params: new Object(),
	prerollBanner: null,
	companionBanner: null,
	isPrerollPlays: false,
    isCustomPreroll: null,    
	 
	addBanner: function(bannerObj)
   {     	    	       	
    bannerObj.params.tile = ++BannerManager.bannersCount;
    this.storage[bannerObj.position] = bannerObj;
    if (bannerObj.type == 'preroll') 
      this.prerollBanner = bannerObj;
    else if (bannerObj.type == 'companion') 
      this.companionBanner = bannerObj;
   },
   
   getBanner: function(position)
   {
   	return this.storage[position];      
   },
   
   getBannerCode: function(pos)
   {
  	var banner = this.getBanner(pos);		
	return banner.getBannerCode(BannerManager.params);
   },
   
   setParams: function(params)
   {
    for (var key in params) {
      this.params[key] = params[key];
    }
   },
  
   getParam: function(paramName)
   {
    return this.params[paramName];
   },
  
	queryPrerollBanner: function(stream)
	{		
		if (!this.prerollBanner || (typeof (disablePreRollClip) != 'undefined' && disablePreRollClip)) 
			return;
				
		if (typeof(stream) == "undefined") 
			stream = "";
		
		this.prerollBanner.originalStream = stream;
		this.prerollBanner.queryBanner();
	},
	
	queryCompanionBanner: function(skipProcessing)
	{
		if (!this.companionBanner) 
			return;
		
		this.companionBanner.queryBanner(skipProcessing);				
		if (Player.isFullAccess() == false) 
		{						
			EventManager.startTimeout(this, "stopAdPlaying", this.getParam('companion_hide_delay'));
			this.companionBanner.bannerContainer.style.display = 'block';
			this.startAdPlaying();
		}
	},
	
	// Only for browser without full control
	startAdPlaying: function()
	{
		this.isPrerollPlays = true;
		
		if (typeof bannerRightTab == 'object') 
			bannerRightTab.select();
		EventManager.generate('turnBottomTabs', {
			turn: 'off'
		});
		
		if (this.isCustomPreroll === false) 
			this.companionBanner.displayBannerDivs();
	},
	
	// Only for browser without full control
	stopAdPlaying: function()
	{		
		this.setPrerollPlayingStatus(false);
	},
	
	getPrerollPlayingStatus: function()
	{
		if (this.isPrerollPlays == true) 
			return true;
		
		return false;
	},
	
	setPrerollPlayingStatus: function(status)
	{
		this.isPrerollPlays = status;
		
		if (status) {
			if (typeof bannerRightTab == 'object') 
				bannerRightTab.select();
			
			EventManager.generate('turnBottomTabs', {
				turn: 'off'
			});
			this.companionBanner.bannerContainer.style.display = 'block';
		}
		else {
			EventManager.generate('turnBottomTabs', {
				turn: 'on'
			});
			
			if (typeof bannerRightTab == 'object') 
				bannerRightTab.selectOpener();
						 
			if (this.companionBanner) 
			{			  
			  //this.companionBanner.hideBanner();
			}	
		}
	},
	
	onPlayerStatusChanged: function(eventobj)
	{
		if (!this.companionBanner) 
			return;
		
		if (this.isCustomPreroll === false && typeof lcUpdatePlaylistState == 'function') {
			var mediaPlayer = Player.getObject();
			var bannerDiv = this.companionBanner.div;
			this.companionBanner.iframe.style.display = 'none';
			var auditDiv = el("lcAuditDiv");
			lcUpdatePlaylistState(mediaPlayer, auditDiv, bannerDiv, eventobj.status);
		}
	},
	
	onPlayerClick: function(eventobj)
	{
		//function (eventobj.nButton, eventobj.nShiftState, eventobj.fX, eventobj.fY);
	},
	
	onMediaTypeChanged: function(eventobj)
	{
		if (eventobj.type == 'ad') 
			this.setPrerollPlayingStatus(true);
		else 
			this.setPrerollPlayingStatus(false);
	},
	
	//Get preroll for lightningcast
	getLCPrerollURL: function(params)
	{	
		top.lcPlayerId = "player_object";
		
		if (params.nid != top.lcNetworkId) 
			top.lcNetworkId = params.nid;
		if (params.level != top.lcLevel) 
			top.lcLevel = params.level;
		if (params.format && params.format != top.lcFormat) 
			top.lcFormat = params.format;
		
		// Modified code from LC
		var mediaPlayer = document.getElementById(top.lcPlayerId);
		var playerURL = top.lcGetPlaylistPath + '?ver=2.0&nwid=';
		playerURL += top.lcNetworkId;
		
		var hasPlayerAccess = (typeof(mediaPlayer.status) != "undefined");
		
		if (hasPlayerAccess) {
			playerURL += '&audit=param';
		}
		playerURL += '&format=' + top.lcFormat + '&level=';
		playerURL += escape(top.lcLevel);
		playerURL += '&content=';
		playerURL += escape(this.getParam('loading_asx_file'));
		playerURL += '&responseType=ASX&mswmext=.asx';
		
		top.lcPlayerURL = playerURL;
		window.lcMediaPlayer = mediaPlayer;
		
		var lcLogger = document.getElementById("lcLoggerArea");
		if ("undefined" != typeof(lcLogger) && null != lcLogger) {
			lcLogger.value += playerURL + "\n";
		}
		
		return playerURL;
	},
	
	showPreroll: function(params)
	{
		if ((typeof(disablePreRollClip) != 'undefined' && disablePreRollClip) || params.type == 'empty') {
      this.setPrerollURL('');
      this.queryCompanionBanner(false);
    }
    else if (params.type == 'advertising.com') {
        this.isCustomPreroll = false;
        this.queryCompanionBanner(true);
        var prerollURL = this.getLCPrerollURL(params);
        this.setPrerollURL(prerollURL);
      }
      else {
        this.isCustomPreroll = true;
        this.queryCompanionBanner(false);
        this.setPrerollURL(params.url);
      }
	},
	
	setPrerollURL: function(adStream)
	{
		adStream = adStream.replace("https:", "http:");
		EventManager.generate('receivedAdStreamURL', {
			url: adStream
		});
		

	}
} 

EventManager.addListener('onPlayerStatusChanged', PreRollBannerManager);
EventManager.addListener('onPlayerClick', PreRollBannerManager);
EventManager.addListener('onMediaTypeChanged', PreRollBannerManager);

/*FILE: /js/Banner.js*/
function Banner(params)
{
  // Store parameters
  this.params = params;
  this.position = params.pos;
  this.type = params.type;
 
  // Store main stream URL for FTC
  this.originalStream = null; 
}

Banner.prototype.initBanner = function()
{
  // Create references to banner code elements
  this.iframe = $('iframe_' + this.position);
  this.div = $('div_' + this.position); 
  this.bannerContainer = $('bannerContainer_' + this.position);
}

Banner.prototype.setParam = function(paramName, value)
{
  this.params[paramName] = value;
}

Banner.prototype.queryBanner = function(skipProcessing)
{
  var rand = Math.random();
  rand = rand * Math.pow(10, 5);
  rand = Math.ceil(rand);
  
  var src = 'iframebanner.php?position=' + this.position + '&type=' + this.type + '&rand=' + rand;
  if (typeof skipProcessing != 'undefined' && skipProcessing) 
    src += '&skipprocessing=true';
  
  this.div.innerHTML = '';

  if (document.images) 
	frames[this.iframe.name].location.replace('/'+src); 
  else 
	frames[this.iframe.name].location.href = '/'+src;
}

Banner.prototype.hideBanner = function()
{
  if (this.params.type == 'companion') {
    this.bannerContainer.style.display = 'none';
  }
  else {
    this.div.style.display = 'none';
    this.iframe.style.display = 'none';
  }
}

Banner.prototype.showDiv = function(content)
{
  this.div.innerHTML = content;
  this.div.style.display = 'block';
  this.iframe.style.display = 'none';  
}

Banner.prototype.showIframe = function()
{
  this.div.style.display = 'none';
  this.iframe.style.display = 'block'; 
}

Banner.prototype.displayBannerDivs = function()
{
  this.bannerContainer.style.display = 'block';
  this.div.style.display = 'block';
}

Banner.prototype.getBannerCode = function(commonParams)
{
  var ad_server_url = commonParams.ad_server_url;
  var dart_site = commonParams.dart_site;
  var zone = commonParams.zone;
  var c_reg = commonParams.c_reg;
  var c_cou = commonParams.c_cou;
  var c_cou1 = null;
  if(commonParams.c_cou1)
  {
    c_cou1 = commonParams.c_cou1;
  } 
  var c_type = commonParams.c_type;
  var gen = commonParams.gen;
  var lan = commonParams.lan;
  var ord = commonParams.ord;
  var dist_partner = commonParams.dist_partner;
  var dist_type = commonParams.dist_type;
  var vstat = commonParams.vstat; 
  var pos = this.params.pos;
  var sz = this.params.sz;
  var tile = this.params.tile;
  var rb_s = this.params.rb_s;  
  var rot = this.params['rot'];  
    
  var U = 'con=' + dart_site + '/' + zone;
  if(c_cou && c_cou != 'global')  
    U += '_' + c_cou;
  if(c_cou1)
    U += '_' + c_cou1;
          
  U += '|dist_partner=' + dist_partner + '|dist_type=' + dist_type + '|size=' + sz;  
  var url = dart_site + '/' + zone + ';c_reg=' + c_reg + ';c_cou=' + c_cou;
  if(c_cou1)  
    url += ';c_cou=' + c_cou1;
    
   url += ';c_type=' + c_type + ';gen=' +  gen +';lan=' +  lan +';pos=' +  pos + ';rb_s=' + rb_s +  
   ';u=' + U + ';dist_type=' + dist_type + ';dist_partner=' + dist_partner;
   if (this.params.dcopt) 
     url += ';dcopt=' + this.params.dcopt;
           
   url += ';rot=' + rot + ';vstat=' + vstat + ';sz=' +  sz + ';tile=' + tile + ';ord=' + ord + '?'; 

  url = url.toLowerCase();
  url = ad_server_url + url;
  return '<script type="text/javascript" src="' + url + '" ></script>';
}


/*FILE: /js/BannerManager.js*/
BannerManager = {
  storage: new Array(),
  params: new Object(),
  timeIntervalID: null,
  timesBannersShowed: 0,  
  bannersCount: 0,
  
  addBanner: function(bannerObj)
  {  
    bannerObj.params.tile = ++this.bannersCount;		
    this.storage[bannerObj.position] = bannerObj;	
  },
    
  getBanner: function(position)
  { 
   return this.storage[position];
  },
  
  setParams: function(params)
  {
    for (var key in params) {
      this.params[key] = params[key];
    }
  },
  
  setParam: function(paramName, value)
  {
    this.params[paramName] = value;
  },
  
  getParam: function(paramName)
  {
    return this.params[paramName];
  },
  
  showRotatableBanners: function()
  {
    if (this.timesBannersShowed == this.params.show_times && parseInt(this.params.show_times) != 0) 
	  {
      this.finishBannerRotation();
      return false;
    }    
    var currBanner = null;
    for (var key in this.storage) {
      currBanner = this.storage[key];
      if (currBanner.type == 'rotatable') {
        currBanner.queryBanner(false);
      }
    }    
    if(PreRollBannerManager.isPrerollPlays == false)
    { 
      if(PreRollBannerManager.companionBanner)
      {
        PreRollBannerManager.companionBanner.queryBanner(false);
      }               
    }
    this.timesBannersShowed++;
    this.regenerateOrd();
  },
  
  startBannerRotation: function(startImmediately)
  {
    this.timesBannersShowed = 0;
	if(startImmediately)
	{
	  this.showRotatableBanners();
	}
	
	if(parseInt(this.params.show_interval) > 0)
	{
	  this.timeIntervalID = setInterval('BannerManager.showRotatableBanners();', this.params.show_interval);
	}    
  },
  
  finishBannerRotation: function()
  {
    clearInterval(this.timeIntervalID);
  },
  
  
  changeProduct: function(params)
  {
    for (var key in params) {
      this.setParam(key, params.key);
    }
    this.regenerateOrd();
    this.finishBannerRotation();
    this.startBannerRotation(true);
  },
  
  
  regenerateOrd: function()
  {    
    var rand = Math.random();
    while(rand < 0.1)    
      rand = Math.random();
        
    rand = rand * Math.pow(10, 9);  
    this.setParam('ord', Math.ceil(rand));
  },
  
  
  getBannerCode: function(pos)
  {
  	var banner = this.getBanner(pos);	
	return banner.getBannerCode(this.params);
  },
   
  showParams: function()
  {
    var str = '';
    for (var key in this.params) {
      str += key + ": " + this.params[key] + "\n";
    }
    alert(str);
  },
    
  showStorage: function()
  {  	
    for(var key in this.storage)
	{
		alert(key + ' => '+ this.storage[key]);
	}
  }     
};

/*FILE: /js/BannerTypeDetector.js*/
var BannerTypeDetector = {

  banner: null,
  
  setBanner: function(banner)
  {     
	  this.currentBanner = banner;			
  },
    
  detect: function()
  {  	 
    if (!this.currentBanner) 
      return;
	   
    if ((typeof jtv_advertising_network_id == 'string' || typeof jtv_advertising_original_url == 'string') && (this.currentBanner.position == 'lp_video')) 
      this.detectAdvertisingCom();
    else if (typeof jtv_preroll_url == 'string') 
      this.detectCustomPreroll();
    else if (typeof jtv_banner_image == 'string') 
      this.detectCustomImage();
    else if (typeof jtv_banner_flash == 'string') 
      this.detectCustomFlash();
    else if (this.currentBanner.type == 'preroll') 
      this.detectEmptyPreroll();
    else 
      this.currentBanner.showIframe();
  },
  
  detectOnPageLoad: function()
  {
  	if (!this.currentBanner) 
      return;
	  
   if (typeof jtv_banner_image == 'string') 
      this.detectCustomImage();
   else if (typeof jtv_banner_flash == 'string') 
      this.detectCustomFlash();	   
	  
   jtv_banner_image = null;
   jtv_banner_flash = null;	  
  }, 
  
  detectCustomFlash: function()
  {
    var id = this.currentBanner.params.pos;
    var width = this.currentBanner.params['width'];
    var height = this.currentBanner.params['height'];
    var wmode = 'transparent';
    var bgcolor = '#ffffff';
    
    if (jtv_banner_flash_wigth && jtv_banner_flash_height) {
      width = jtv_banner_flash_wigth;
      height = jtv_banner_flash_height;
    }
    
    if (jtv_banner_flash_bg_color) {
      wmode = 'window';
      bgcolor = jtv_banner_flash_bg_color;
    }
    
    var objectProperties = {
      classid: "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",
      codebase: "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0",
      width: width,
      height: height,
      id: id,
      align: "middle"
    };
    
    var objectParams = {
      allowScriptAccess: "sameDomain",
      allowFullScreen: "false",
      movie: jtv_banner_flash + "?clickTag=" + jtv_banner_url,
      width: width,
      height: height,
      quality: "high",
      wmode: wmode,
      bgcolor: bgcolor
    };
    
    var embedProperties = {
      src: jtv_banner_flash + "?clickTag=" + jtv_banner_url,
      quality: "high",
      wmode: wmode,
      swliveconnect: "TRUE",
      bgcolor: bgcolor,
      type: "application/x-shockwave-flash",
      allowscriptaccess: "never",
      width: width,
      height: height
    };
    
    var content = '';
    var objectTag = '';
    
    if (jtv_banner_flash_alternative_image) {
      if (!Helper.isFlashSupported()) {
        var size = 'width="' + width + '" height="' + height + '"';
        content = '<a href="' + jtv_banner_url + '" target="_blank"><img src="' + jtv_banner_flash_alternative_image + '" ' + size + ' alt=""></a>';
        this.currentBanner.showDiv(content);
        return false;
      }
    }
    
    if (Helper.getBrowser() == "IE") {
      for (var paramName in objectParams) 
        content += '<param name="' + paramName + '" value="' + eval('objectParams.' + paramName) + '" />';
      for (var propertyName in objectProperties) 
        objectTag += ' ' + propertyName + '="' + eval('objectProperties.' + propertyName) + '"';
      
      content = "<object" + objectTag + ">" + content + "</object>";
    }
    else {
      for (var propertyName in embedProperties) 
        objectTag += ' ' + propertyName + '="' + eval('embedProperties.' + propertyName) + '"';
      
      content = "<embed" + objectTag + " />";
    }
    content = this.wrapWithValignDivs(content, this.currentBanner.div.style.width, this.currentBanner.div.style.height);
    this.currentBanner.showDiv(content);
  },
  
  detectCustomImage: function()
  {
    var width = this.currentBanner.params['width'];
    var height = this.currentBanner.params['height'];
    
    var size = "";
    if (jtv_banner_image_wigth && jtv_banner_image_height) 
      size = 'width="' + jtv_banner_image_wigth + '" height="' + jtv_banner_image_height + '"';
    
    var content = '<a href="' + jtv_banner_url + '" target="_blank"><img src="' + jtv_banner_image + '" ' + size + ' alt=""></a>';
    content = this.wrapWithValignDivs(content, this.currentBanner.div.style.width, this.currentBanner.div.style.height);
    
    var additionalStyles = "";
    if (typeof jtv_banner_image_bg_color == 'string' && jtv_banner_image_bg_color) 
      var additionalStyles = "background:" + jtv_banner_image_bg_color;
    
    if (additionalStyles) 
      content = "<div style='" + additionalStyles + "'>" + content + "</div>";
    
    this.currentBanner.showDiv(content);
  },
  
  detectCustomPreroll: function()
  {  	
    parent.PreRollBannerManager.showPreroll({
      type: "custom",
      url: jtv_preroll_url
    });
  },
  
  detectAdvertisingCom: function()
  {
  	this.currentBanner.div.style.display = 'block';
    parent.PreRollBannerManager.showPreroll({
      type: "advertising.com",
      nid: jtv_advertising_network_id,
      level: jtv_advertising_default_level,
      format: jtv_advertising_media_format
    });
  },
  
  detectEmptyPreroll: function()
  {
    parent.PreRollBannerManager.showPreroll({
      type: "empty"
    });
  },
  
  wrapWithValignDivs: function(content, width, height)
  {
    return '<div class="valignWrap" align="center" style="height:' + height + '"><div class="valignValignCenter" style="width:' + width + '">' + content + '</div><div class="valignJustForIE"></div></div>';
  }
  
};

/*FILE: /js/AC_RunActiveContent.js*/
//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

/*FILE: /js/Tracker.js*/
/**!
 * \file Tracker.js
 * \brief This file consists of Tracker class that can work inside WCQ site to track information for tracking systems
 * \version 1.0
 */
Tracker = {

  distributionModel: 'WCQ2008',
  customerType: 'guest',

  deferred_array: [],
  timer: null,
  
  track: function(entry)
  {
    // If google JS code has not been loaded yet
    if (typeof(urchinTracker) != 'function') {
      this.track_deferred(entry);
      return;
    }
    
    urchinTracker(entry);
  },


  delay: function(entry)
  {
    Helper.setCookie("delayed_google_traking", entry, null, "/");
  },


  sendDelayed: function()
  {
    var entry = Helper.getCookie('delayed_google_traking');
    if (!entry || entry == ';')
      return;
      
    this.track(entry);
  
    Helper.setCookie("delayed_google_traking", '', null, "/");
  },
  
  
  track_deferred: function(entry)
  {
    if (typeof(this.timer) !== null) 
      window.clearTimeout(this.timer);
    
    if (entry && typeof(entry) == "string") 
      this.deferred_array[this.deferred_array.length] = entry;
    
    if (typeof(urchinTracker) == 'function') {
      for (var i = 0; i < this.deferred_array.length; i++) 
        this.track(this.deferred_array[i]);
      
      this.deferred_array = new Array();
    }
    else 
      this.timer = window.setTimeout("Tracker.track_deferred('')", 100);
  },
  
  getURL: function(location, trigger, module, destination)
  {
    var url = '/' + this.distributionModel;
    url    += '/' + 'qq.lang_' + Helper.getLang();
    url    += '/' + 'qq.usr_' + this.customerType;
    url    += '/' + (typeof location == 'string' ? location : Helper.getLocation());
    url    += '/' + module;
    url    += '/' + trigger;
    if(typeof destination == 'string' || typeof destination == 'number')
      url    += '/' + destination;

    return url;    
  },
  
  trackPageLoading: function(destination)
  {
    this.track(this.getURL(null, 'loading', 'page', destination));
  },
  
  trackCountdownBuy: function(matchId)
  {
    this.track(this.getURL(null, 'buy', 'countdown', matchId));
  },
  trackCountdownWatch: function(matchId)
  {
    this.track(this.getURL(null, 'watch', 'countdown', matchId));
  },
  
  trackBuyYourTeam: function(teamId)
  {
    this.track(this.getURL(null, 'team_link', 'buy_team', teamId));
  },
  
  trackScheduleTeamLink: function(teamId)
  {
    this.track(this.getURL(null, 'team_link', 'schedule', teamId));
  },
  
  trackStandings: function(teamId)
  {
    this.track(this.getURL(null, 'team_link', 'standings', teamId));
  },
  
  trackScheduleMatchLink: function(matchId)
  {
    this.track(this.getURL(null, 'match_link', 'schedule', matchId));
  },
  
  trackScheduleHighlights: function(matchId)
  {
    this.track(this.getURL(null, 'watch', 'schedule_highlights', matchId));
  },
  
  trackScheduleMatchBuy: function(matchId)
  {
    this.track(this.getURL(null, 'buy', 'schedule_full_match', matchId));
  },
  
  trackScheduleMatchWatch: function(matchId)
  {
    this.track(this.getURL(null, 'watch', 'schedule_full_match', matchId));
  },
  
  trackNewsMoreLink: function()
  {
    this.track(this.getURL(null, 'more_link', 'news', null));
  },
  
  trackNewsLink: function(newsId)
  {
    this.track(this.getURL(null, 'news_link', 'news', newsId));
  },
  
  trackTellAFriend: function(matchId)
  {    
    this.track(this.getURL(null, 'send_to_friend', 'send_to_friend', matchId));    
  },
  
  trackMatchStatisticTab: function(tabName)
  {
    this.track(this.getURL(null, tabName, 'match_statistics', null));
  },

  trackTeamStatisticTab: function(tabName)
  {
    this.track(this.getURL(null, tabName, 'team_statistics', null));
  },

  trackScheduleRoundFilter: function(filter)
  {
    this.track(this.getURL(null, 'rounds_filter', 'schedule', filter));
  },
  
  trackBuyFullPackage: function()
  {
    this.track(this.getURL(null, 'buy', 'offer', 'All_Access'));
  },

  trackBuyTeamPackage: function(teamId)
  {
    this.track(this.getURL(null, 'buy', 'offer', teamId));
  },
  
  trackBuyMatchOffer: function(matchId)
  {
    this.track(this.getURL(null, 'buy', 'offer', matchId));
  },
  
  trackMenu: function(menuName, menuItem)
  {
    this.track(this.getURL(null, 'open', menuName, menuItem));
  },
    
  trackMobile: function()
  {
    this.track(this.getURL(null, 'watch_link', 'cell_phone', null));
  },
    
  trackFriendlies: function()
  {
    this.track(this.getURL(null, 'more_link', 'friendlies_games', null));
  },  

  trackAffiliate: function(link)
  {
    this.track(this.getURL(null, 'link', 'affiliates', link));
  },
    
  trackStoreMoreLink: function()
  {
    this.track(this.getURL(null, 'more_link', 'store', null));
  },

  trackStoreLink: function(name)
  {
    this.track(this.getURL(null, 'link', 'store', name));
  },
    
  trackAddedFTC: function(matchId)
  {
    this.track(this.getURL(null, 'added_ftc_product', 'page', matchId));
  }
}
