sp3TierHandlerClass = Class.create();
sp3TierHandlerClass.prototype = {
	initialize: function(options) {
		this.mode = self.urlhelper.getGetParamFromUrl(self.location.href, 'pmode');
		this.passed_pcode = self.urlhelper.getGetParamFromUrl(self.location.href, 'pcode') || self.cookies.get('pcode');
		this.ec = top.pageEnv.edition_code;
		this.channels = channels || ['aljazeera', 'cnn', 'euronews'/*, 'sntv'*/];
		this.pcodes = {
			aljazeera:'news_aj',
			bbcworld:'bbcw',
		//	bbcnews:'bbcn',
			cnn:'cnnint',
			euronews:'euronws',
			/*sntv:'sntv',*/
			comedytime:'comedytime'
		};
		
		
		this.protectedChannels = protectedChannels || [];
		this.freeChannels = freeChannels || {};

		this.addChannelsToDom();
		this.showInfo('aljazeera');
		$('upgradeUrl3Tier').innerHTML = '3tier/startFreetrial'.tr();
		this.packages = packages;
		  
		this.packageLength = {'all':this.channels.length,3:3,1:1};
		this.channelCnt = 0;
		this.channelSelected = false;
		this.editionOk = true;
		this.activeUser = false; 
		this.trackVar = false;
		this.entitles = {};

		this.uEmail = '';
		this.package = false;
		this.hasTrial = false;
		this.hadTrial = false;
		
		if (self.darf.getServiceStatusCookie(true)) {
			this.entitles = this.getEntitlementsFromCookie();
			this.darfWaiter();
		}
		else {this.onInit();}
	},
	darfWaiter: function(){
		var darf = self.frames.darfcall;
		if  (!darf){
			window.setTimeout('self.sp3t.darfWaiter();',100);
		}
		else if  (!darf.darfHandler){
			window.setTimeout('self.sp3t.darfWaiter();',20);
		}
		else{
			if (!darf.darfHandler.snValues){
				darf.darfHandler.addObserver({
					onServiceListloaded:function(){parent.sp3t.onInit();} 
				});
			}
			else {this.onInit();}
		}
	},
	onInit: function (){
	  if (this.package) {
		removeClass.each(function(val,k){Element.removeClassName('upgradeUrl3Tier',val);});
		$('upgradeUrl3Tier').innerHTML = '3tier/upgrade'.tr();
		try {
			this.uEmail = self.frames.darfcall.darfHandler.userEmail || self.frames.darfcall.darfHandler.getUserInfo().email || '';
		} catch(e){}
	  }
	  this.showMessage();
	  this.switchPackage();
	  this.checkChannels();
	  this.changeUpgradeUrl();
	},
	showMessage: function (){
		  Element.removeClassName('messageBox','alarm');
		  switch (true){
			    case this.package === false:
			    	$('messageBox').innerHTML = '3tier/selectchannels'.tr();
			    	break;
				case !this.editionOk:
					$('messageBox').innerHTML = '3tier/wrongEdition'.tr({'nonEd':'UK'}).replace('{email}',this.uEmail);
					Element.addClassName('messageBox','alarm');
					break;
			    case this.package==1:
			    case this.package==3:
			    $('messageBox').innerHTML = '3tier/msge_oldcust'.tr().replace('{email}',this.uEmail);
			    	break;
			    case this.package=='all':
			    	$('messageBox').innerHTML = '3tier/msge_full'.tr().replace('{email}',this.uEmail);
			    	break;
		  }
	},
	getCheckedChannels: function(){
		  var checked = [];
		  var oThis=this;
		  this.channels.each(
			  function(value,key){
			  	if (!oThis.freeChannels[value]){
			  		if ($('chSel_sp_'+oThis.channels[key]).checked){
			  			checked.push(oThis.channels[key]);}}});
		  return checked;
	},
	enableUpgradeButton: function (){
		  if (!this.package){
			    switch (true) {
					case this.channelSelected == 'all' &&this.channelCnt == this.channels.length:
					case this.channelSelected == 1 && this.channelCnt == 1:
					case this.channelSelected == 3 && this.channelCnt == 3:
					  return true;
			    }
		  }
		  else {
			  if (!this.editionOk) {return false;}
			    switch (true) {
					case this.channelSelected == 'all' && this.package != 'all':
					case this.package == 1 && this.channelSelected == 3 && this.channelCnt == 3: 
					  return true;
			    }
		  }
		  return false;
	},
	getCheckedProd: function (){
		if (!this.channelSelected) {return false;}
		  var prod = 'sp';
		  prod +=  (this.ec=='uk') ? 'uk' : 'eu';
		  prod += (this.channelSelected == 'all') ? '' : this.channelSelected + 'c';
		  return prod;
	},
	triggerRefreshCookie: function (){
		if (typeof self.loginModule == 'object') {self.loginModule.setRefreshCookie();}
	},
	changeUpgradeUrl:function(){
		  var prod = this.getCheckedProd();
		  if (!prod) {return;}

		  var op = (this.package && this.packages[prod]) ? this.packages[prod].url : this.packages[prod].trialUrl;
		  var src = (this.package && this.packages[prod]) ?  'fd_' + this.ec + '_'+prod+'_upgr' : 'fd_' + this.ec + '_'+prod+'_trial';
			if  ( this.channelSelected == 1 ) {
				var pcode = (this.passed_pcode && this.pcodes[this.getCheckedChannels()[0]] == this.passed_pcode) ? this.passed_pcode: this.pcodes[this.getCheckedChannels()[0]] + '_1c';
				
				op += '&pcode=' + pcode;
			}
			$('upgradeUrl3Tier').innerHTML = (this.package) ? '3tier/upgrade'.tr() : '3tier/startFreetrial'.tr();
		  var f = function (){
			  self.sp3t.triggerRefreshCookie();
			  trackClick( self.sp3t.trackVar );
		  };
		  if (this.enableUpgradeButton()){
			    if (this.channelSelected != 'all') {
					packageUrlString = '&s=' + this.getCheckedChannels().join(':');
					op += packageUrlString;
			    }
			    $('upgradeUrl3Tier').href = op + "&src=" + src + "&rsrc=" + src + "&email=" + this.uEmail;
			    Element.removeClassName('btn_over','overlay');
		  }
		  else {
			    Element.addClassName('btn_over','overlay');
			    $('upgradeUrl3Tier').href = 'javascript://';
			    f = function (){
					return false;
				};
		  }
		  $('upgradeUrl3Tier').onclick = f;
		  $('sysreqLink').onclick = function(){
			  trackClick(self.sp3t.trackVar +'_sysreq');
		  };
	},
	getEntitlementsFromCookie: function(){
		  var cookieContent = self.darf.getServiceStatusCookie();
		  if (this.mode == 'none') cookieContent = false;
		  if (this.mode == 'all') cookieContent = "SN=spuk:SS=A";
		  if (this.mode == 'eu_all') cookieContent = "SN=speu:SS=A";
		  if (this.mode == 3) cookieContent = "SN=spuk3c:SS=A|SN=aljazeera:SS=A|SN=cnn:SS=A|SN=sntv:SS=A";
		  if (this.mode == 1) cookieContent = "SN=spuk1c:SS=A|SN=aljazeera:SS=A";
		  if (this.mode == 'eu_1') cookieContent = "SN=speu1c:SS=A|SN=aljazeera:SS=A";
		  if (this.mode == 'exp') cookieContent = "SN=spuk1c:SS=I|SN=aljazeera:SS=A";
		  if (this.mode == 'dbl_1') cookieContent = "SN=spuk1c:SS=I|SN=aljazeera:SS=A|SN=spuk:SS=A";
		  if (this.mode == 'dbl_3') cookieContent = "SN=spuk3c:SS=I|SN=aljazeera:SS=A|SN=cnn:SS=A|SN=sntv:SS=A|SN=spuk:SS=A";

		  var userEntitles = {};
		  this.package = false;
		  if (cookieContent){
			    var services = cookieContent.split('|');
			    for (var i = 0; i<services.length; i++) {
				  var name = services[i].split(':')[0].split('=')[1];
				  var status = services[i].split(':')[1].substr(3,1);
				  if (name.indexOf('sp') == 0) {
					    if (this.checkRightEdition(name)){
							if(this.packages[name] && status != 'I') {
								  this.package = this.packages[name].name;
								  this.activeUser = true; 
							}
							if (status == 'I') {this.hadTrial = this.packages[name].name;}
							else if (status == 'T') {this.hasTrial = true;}
					    }
					    else {
							this.editionOk = false;
							this.triggerRefreshCookie();
					    }
				  }
				  else if (this.channels.indexOf(name) > -1){
					    userEntitles[name] = true; // single channels
				  }
			    }
			    if ( this.hadTrial && !this.activeUser ) {
					if (this.hadTrial=='all') {this.package = 3;}
					else {this.package = 1;}
			    }
				
				if ( !this.editionOk) {
					this.package = 'all';
					this.switchPackage();
			    }
		  }
		  return userEntitles;
	},
	checkRightEdition: function(sn){
		  var ec = (this.ec == 'uk') ? 'uk':'eu';
		  qsRE = new RegExp('(sp)('+ec+')(1c|3c)?');
		  var found = sn.search(qsRE);
		  return (found<0)?false:true;
	},
	countSelectedChannels: function (){
		  this.channelCnt = this.getCheckedChannels().length;
	},
	checkChannels: function (){
		 for (var i = 0; i< this.channels.length; i++){
			 if ($('chSel_sp_'+this.channels[i]) && (this.package == 'all' || this.entitles[this.channels[i]])){
				$('chSel_sp_'+this.channels[i]).checked = true;
				Form.Element.disable('chSel_sp_'+this.channels[i]);
				Element.addClassName('select_'+this.channels[i],'active');
			 }
		 }
	},
	disenableChannels: function (on_off, checked){
		 for (var i = 0; i<= this.channels.length; i++){
			 if ($('chSel_sp_'+this.channels[i])){
				  if (on_off == 'disable'){
					  Form.Element.disable('chSel_sp_'+this.channels[i]);
				  }
				   // never enable a channel the user already owns!
				  else if (this.package != 'all' && !this.entitles[this.channels[i]]) {
					   if (!this.protectedChannels[this.channels[i]]){
						   Form.Element.enable('chSel_sp_'+this.channels[i]);
					   }
					   else {
						   $('chSel_sp_'+this.channels[i]).checked = false;
						   Form.Element.disable('chSel_sp_'+this.channels[i]);
						   Element.removeClassName('select_'+this.channels[i],'active');
						   this.countSelectedChannels();
					   }
				  }
			 }
		 }
	},
	toggleAllChannels: function(check){
		  for (var i = 0; i<= this.channels.length; i++){
			    if (($('chSel_sp_'+this.channels[i]) && !$('chSel_sp_'+this.channels[i]).disabled) || this.protectedChannels[this.channels[i]]){
					$('chSel_sp_'+this.channels[i]).checked = check;
					if (check) {Element.addClassName('select_'+this.channels[i],'active');}
			    }
		  }
		  if (check) {this.channelSelected = 'all';}
		  this.countSelectedChannels();
	},
	cssHandler: function(elements, action, style){
		  elements.each(function(v){
				if (action=='add') {Element.addClassName(v,style);}
			    else {Element.removeClassName(v,style);}
		  });
	},
	switchPackage: function(p){
		if (!p && this.package){
			switch (this.package){
			    case 'all':
			    	p=3;
					this.cssHandler(['p3_over'],'add','overlay');
			    	break;
			    case  3:
			    	p=3;
			    	break;
			    case 1:
			    	p=1;
			    	break;
			}
		}
		
		for (var i =1;i<=3;i++){
			 if (p==i) {
				  Element.removeClassName('pa'+i,'inact');
				  Element.addClassName('pa'+i,'act');
			 }
			 else {
				  Element.addClassName('pa'+i,'inact');
				  Element.removeClassName('pa'+i,'act');
			 }
		}
		  
		switch (true){
			  case p==1:
				  if (this.channelSelected =="all") {this.disenableChannels('enable',true);}
				  this.channelSelected = 1;					
				  this.trackVar = 'sp_basic';
					break;
				case  p==2:
					this.channelSelected = 3;
					this.disenableChannels('enable',true);
					this.trackVar = 'sp_plus';
					break;
				case p==3:
					this.toggleAllChannels(true);
					this.trackVar = 'sp_premium';
					break;
		  }
		  this.changeUpgradeUrl();
	},
	checkSwitchPackage: function(checked){
		  var p =  (this.channelSelected)? this.channelSelected : this.package;
		  if (!this.channelCnt) {
			   Element.addClassName('pa1','inact');
			   Element.removeClassName('pa1','act');
		  }
		  switch (p) {
			  	case false:
				case 1:
					if (this.channelCnt == this.packageLength[1]){
						  this.switchPackage(1);
					}
					if (this.channelCnt > this.packageLength[1]){
						  this.switchPackage(2);
					}
					break;
				case 3:
					if (this.channelCnt > this.packageLength[3]){
						  this.switchPackage(3);
					}
					else if (this.channelCnt == this.packageLength[1]){
						  this.switchPackage(1);
					}
					break;
				case 'all':
					if (this.channelCnt <= this.packageLength[3]){
						  this.switchPackage(2);
					}
					break;
		  } 
	},
	calcChannels: function(checked){
		  this.countSelectedChannels();
		  this.checkSwitchPackage(checked);
		  this.changeUpgradeUrl();
	},
	showInfo: function (c){
		Element.addClassName('infoPanel','panel');
		var str = '3tier/info_'+c;
	 $('infoBox').innerHTML = (c) ? '<div class="logos '+c+'"></div>' + str.tr() : '';
	},
	switchChannel: function(c){
		if ($('chSel_sp_'+c).disabled || this.protectedChannels[c]||this.freeChannels[c]) {return;}
		  
		$('chSel_sp_'+c).checked = ( $('chSel_sp_'+c).checked ) ? false : true;
		  
		if ( $('chSel_sp_'+c).checked) {
			Element.addClassName('select_'+c,'active');
		}
		else {
		  Element.removeClassName('select_'+c,'active');
		}
		this.calcChannels($('chSel_sp_'+c).checked);
	},
	addChannelsToDom:function(){
		var cnt = this.channels.length;
		var brk = Math.floor(cnt/2);
		for (var i = 0; i< cnt; i++){
			  var c = this.channels[i];
			  var addclass = (brk%2 === 0) ? ' class="clear"' : '';
			  var onclick = (this.protectedChannels[c]) ? 'self.sp3t.showInfo(\'sppre_only\')': 'self.sp3t.switchChannel(\'' + c + '\');';
			  var playString = this.freeChannels[c] ? '3tier/watch'.tr() : '3tier/preview'.tr();
			  var html = '<li'+ addclass +' id="'+c+'"><div class="logo "><div class="logos '+ c + '" onclick="'+onclick+'"></div><div class="links" onclick="return false;"><span><a href="#player:partner:' + c + ':">'+playString+'</a> | <a class="info" onmouseover="self.sp3t.showInfo(\'' + this.channels[i] + '\')"  href="javascript://">'+'3tier/info'.tr()+'</a></span></div></div>';
			  
			  if (!this.freeChannels[c])  {html+='<div class="right" id="select_'+c+'" onclick="'+onclick+'"><input  type="checkbox" name="chSel[sp_'+c+']" id="chSel_sp_'+c+'" onclick="this.checked=!this.checked;" value="sp_'+c+'"></div>';}
			  
			  html+='</li>';
			  var _void = new Insertion.Bottom($('channelList'),html);
			  if (this.protectedChannels[c]) {$('chSel_sp_'+c).disabled=true;}
		}
	}
};
self.sp3t = new sp3TierHandlerClass ();
