/*Apri e chiudi*/
function openClose() {
var el = document.getElementById("questions");
var display = el.style.display;
el.style.display = (display == "block") ? "none" : "block";
	if (el.style.display == "block"){
		document.getElementById("listopener").className='open';
	}else{
		document.getElementById("listopener").className='close';
	}
}

/*
 * Copyright 2005 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *
 * Serializes the data from all the inputs in a Web form
 * into a query-string style string.
 * @param docForm -- Reference to a DOM node of the form element
 * @param formatOpts -- JS object of options for how to format
 * the return string. Supported options:
 *    collapseMulti: (Boolean) take values from elements that
 *    can return multiple values (multi-select, checkbox groups)
 *    and collapse into a single, comman-delimited value
 *    (e.g., thisVar=asdf,qwer,zxcv)
 * @returns query-string style String of variable-value pairs
 */
function formData2QueryString(docForm, formatOpts) {
  
  var opts = formatOpts || {};
  var str = '';
  var formElem;
  var lastElemName = '';
  if(docForm){
	  for (i = 0; i < docForm.elements.length; i++) {
		formElem = docForm.elements[i];
		
		switch (formElem.type) {
		  // Text fields, hidden form elements
		  case 'text':
		  case 'hidden':
		  case 'password':
		  case 'textarea':
		  case 'select-one':
			if (formElem.name == 'username') {
				str += formElem.name + '=' + encodeURI(formElem.value).toLowerCase() + '&'
			}else{
				str += formElem.name + '=' + encodeURI(formElem.value) + '&'
			}
			break;
			
		  // Multi-option select
		  case 'select-multiple':
			var isSet = false;
			for(var j = 0; j < formElem.options.length; j++) {
			  var currOpt = formElem.options[j];
			  if(currOpt.selected) {
				if (opts.collapseMulti) {
				  if (isSet) {
					str += ',' + encodeURI(currOpt.value);
				  }
				  else {
					str += formElem.name + '=' + encodeURI(currOpt.value);
					isSet = true;
				  }
				}
				else {
				  str += formElem.name + '=' + encodeURI(currOpt.value) + '&';
				}
			  }
			}
			if (opts.collapseMulti) {
			  str += '&';
			}
			break;
		  
		  // Radio buttons
		  case 'radio':
			if (formElem.checked) {
			  str += formElem.name + '=' + encodeURI(formElem.value) + '&'
			}
			break;
			
		  // Checkboxes
		  case 'checkbox':
			if (formElem.checked) {
			  // Collapse multi-select into comma-separated list
			  if (opts.collapseMulti && (formElem.name == lastElemName)) {
				// Strip of end ampersand if there is one
				if (str.lastIndexOf('&') == str.length-1) {
				  str = str.substr(0, str.length - 1);
				}
				// Append value as comma-delimited string
				str += ',' + encodeURI(formElem.value);
			  }
			  else {
				str += formElem.name + '=' + encodeURI(formElem.value);
			  }
			  str += '&';
			  lastElemName = formElem.name;
			}
			break;
			
		}
	  }
  }
  // Remove trailing separator
  str = str.substr(0, str.length - 1);
  
  return str;
}

/**
Esegue il post di un form.

Paramatetri
postForm= 		oggetto form
actionValue=	action URL

autore: 		alberto.catania@antliateam.it
ver: 			1.0
data:			09/08/2007
*/
function postSubmit(postForm, strURL) {

	postForm.action = strURL;
	postForm.submit();
}

function xmlhttpGet(postFormName, strURL, idDiv) {
	
    var xmlHttpReq = false;
    var self = this;
    // Xhr per Mozilla/Safari/Ie7
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // per tutte le altre versioni di IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('GET', strURL, false);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText, idDiv);
        }
    }
    self.xmlHttpReq.send(getquerystring(postFormName));
}

function xmlhttpPost(postFormName, strURL, idDiv) {
   
	if (postFormName == 'formLogin')
	{
		xmlhttpPostEt(postFormName, '/EtSkyIt/pwlogin.do', idDiv);
	}
	else {
	
			var xmlHttpReq = false;
			var self = this;
			
			// Xhr per Mozilla/Safari/Ie7
			if (window.XMLHttpRequest) {
				self.xmlHttpReq = new XMLHttpRequest();
			}
			// per tutte le altre versioni di IE
			else if (window.ActiveXObject) {
				self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}
			self.xmlHttpReq.open('POST', strURL, true);
			self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			self.xmlHttpReq.onreadystatechange = function() {        
				if (self.xmlHttpReq.readyState == 4) {
					  if(self.xmlHttpReq.status < 300) {
						  //document.cookie='cluster=non_abbonato; expires=Thu, 2 Aug 2009 20:47:11 UTC; path=/'
						  //document.cookie="cluster=non_abbonato;";
				
						  //alert(self.xmlHttpReq.responseText);
						  document.cookie = self.xmlHttpReq.getResponseHeader('Set-Cookie');
						  if(self.xmlHttpReq.responseText.indexOf('http://salwebcol.skytv.it/ecustomer_ita/start.swe')>1){
							  url=self.xmlHttpReq.responseText.substring(self.xmlHttpReq.responseText.indexOf('http://salwebcol.skytv.it/ecustomer_ita/start.swe'),self.xmlHttpReq.responseText.indexOf('_</a>.</p>'));
							  if(self.xmlHttpReq.responseText.indexOf('302 Moved Temporarily')>1){
										 document.body.style.display="none";
										 location.href = url;
								  }
								//alert(url);				         	    
						  }	     
						  updatepage(self.xmlHttpReq.responseText, idDiv);          
					  }         	        	
				 }
			}
		   self.xmlHttpReq.setRequestHeader("connection", "close");
		   self.xmlHttpReq.send(getquerystring(postFormName));

	}
}

function getCookie(sNome) {
    var asCookies = document.cookie.split("; ");
    for (var iCnt = 0; iCnt < asCookies.length; iCnt++) {
       alert(asCookies[iCnt]);
       var asCookie = asCookies[iCnt].split("=");
       if (sNome == asCookie[0]) { 
         return (unescape(asCookie[iCnt]));
       }
    }
    return("");
}

function getquerystring(formName) {
    var form = document.forms[formName];
    qstr = formData2QueryString(form);
    return qstr;
}

function updatepage(str, idDiv){
	try{
		document.getElementById(idDiv).innerHTML = str;
	}catch(e){
	}
}





function xmlhttpGetEt(postFormName, strURL, idDiv) {
	
	var u=document.getElementById("username").value;
	var p=document.getElementById("password").value;

	if (u=="Username")
	{
		document.getElementById("username").value = "";
	}
	if (u=="Password")
	{
		document.getElementById("password").value = "";
	}

    var xmlHttpReq = false;
    var self = this;

	self.xmlHttpReq = getHTTPObject(); // We create the HTTP Object
    self.xmlHttpReq.open('GET', strURL, false);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText, idDiv);
        }
    }
    self.xmlHttpReq.send(getquerystring(postFormName));
}


function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }

  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}


//Funzione chiamata all'ONLOAD della pagina
function xmlhttpPostEt(postFormName, strURL, idDiv) {

	if (document.getElementById('parentUrl') != null)
	{
		document.getElementById('parentUrl').value=""; 
	}

	//In caso di insuccesso della login
	var urlQs = document.location.search;
	if (urlQs.indexOf('resLogin') != -1)
	{
		var pre = "";
		if (strURL.indexOf('?') != -1) pre = "&";
		else pre = "?";

		if (urlQs.indexOf('resLogin=wp') != -1) strURL = strURL + pre+"resLogin=wp";
		else if (urlQs.indexOf('resLogin=une') != -1) strURL = strURL + pre+"resLogin=une";
		else if (urlQs.indexOf('resLogin=una') != -1) strURL = strURL + pre+"resLogin=una";
	}


	if (strURL.indexOf('/EtSkyIt/logout.do') != -1)
    {
	  strURL = strURL + '?type=w';
    }


	var queryString=getquerystring(postFormName);

	//Aggiungo alla query string lo skylifer
	if (typeof( skylife ) != 'undefined' && skylife!=null && skylife!="" && queryString!="")
	{
	var data=skylife.split("_");
	queryString=queryString+"&username="+data[0]+"&password="+data[1];
	}

	
	var xmlHttpReq = false;
    var self = this;
    
	self.xmlHttpReq = getHTTPObject(); // We create the HTTP Object
	self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {        
        if (self.xmlHttpReq.readyState == 4) {
        	  if(self.xmlHttpReq.status < 300) {
		         	     
			      updatepage(self.xmlHttpReq.responseText, idDiv);   
				  
      	      }         	        	
         }
    }
   self.xmlHttpReq.setRequestHeader("connection", "close");
   self.xmlHttpReq.send(queryString);
}


//Funzione chiamata quando si effettua il LOGIN
function httpsLogin() 
{

	if (document.getElementById('username').value == 'Username'){
	return false;
	}

	if (document.getElementById('parentUrl') != null)
	{	
		var verif = verifypassword();
		var tmp = document.cookie;
		if (verif != 0 && !existCookie('SETPWD'))
		{	
			//creazione cookie SETPWD
			createCookie('SETPWD', 'Y');
		}
			
		document.getElementById('parentUrl').value=document.location.href; 
	}

	//if(document.location.hostname = 'xfactor.sky.it'){
	//	strURL = 'https://xfactor.sky.it/EtSkyIt/pwlogin.do';
	//}
	strURL = 'https://www.sky.it/EtSkyIt/pwlogin.do';
	//strURL = '/EtSkyIt/pwlogin.do';
	document.getElementById("formLogin").action=strURL;
	document.getElementById("formLogin").submit();
}

function verifypassword(){

	var username = $('#username').val();
	var password = $('#password').val();
	
	if (username==password){
		return 1;
	}
	if(!checktwocharpassword(password )){
		return 2;
	}
	return 0;
	
	
} 
function checktwocharpassword(password){

		var toReturn = false;
			for(i=0; i < password.length; i++){
				if(password.charAt(i) != password.charAt(0)){
					toReturn = true;
				}
			}
			return toReturn;

}

$(document).ready(function(){
		
	$.getJSON("/EtSkyIt/data.do",
		function(data){
			if (data.customer == 'C') {
				$('#pwdusername').val(data.username);
				$('#mail').val(data.email);
				$('#referral').val(document.location.href);

				if (existCookie("SETPWD") && document.cookie.indexOf('PETERWITT') != -1) { 
	  
					$.blockUI({ message: $('#passwordForm'), css: {height: '215', width: '400'}});
					
					
					
					var bindEvent = function() {
						$("#pwdconferma").click(function(e) {
							e.preventDefault();	
							nielsenRefreshVP("ModificaPassword");
							if ($("#password1").val() == '' || $("#password2").val() == '') { 
								alert('Attenzione! Dati obbligatori');
								return;
							}
							else if (!checktwocharpassword($("#password1").val())) { 
								alert('La password deve contenere almeno due caratteri differenti'); 
								return;
							}
							else if ($("#password1").val() != $("#password2").val()) { 
								alert('Le password non coincidono');
								return;
							}
							else if ($("#password1").val().length < 8) { 
								alert('La password deve essere di almeno 8 caratteri');
								return;
							}
							else if ($("#password1").val() == $('#pwdusername').val()) { 
								alert('La password deve essere diversa dalla username');
								return;
							}
							
							
							$("#box_password_form").submit();			
							
						});
					}
						
					$(bindEvent);

				}
				else {
					createCookie('SETPWD', '', -1);
				}
			}
			else {
				createCookie('SETPWD', '', -1);
			}
		});

	}
);
		



//Funzione chiamata per reinserire i dati dopo INSUCCESSO del login
function cleanUrl() 
{
	if (document.getElementById('parentUrl') != null)
	{
		document.getElementById('parentUrl').value=""; 
	}

	var actualUrl = location.href;
	if (actualUrl.indexOf('?resLogin') != -1) actualUrl = actualUrl.substring(0, actualUrl.indexOf('?resLogin'));
	else if (actualUrl.indexOf('&resLogin') != -1) actualUrl = actualUrl.substring(0, actualUrl.indexOf('&resLogin'));
	setTimeout("goPg('"+actualUrl+"')", 250);
	
}

function goPg(pg){
	location.href = pg;
}

function popupOW(url,name, width, height, otherSettings) { 
	var pw = width ? width : 450;
	var ph = height ? height : 300;
	var leftPos = (screen.width-pw)/2;
   	var topPos = (screen.height-ph)/2;
	var os = otherSettings ? ',' + otherSettings : '';
	var popup = window.open(url, name, 'width='+pw+',height='+ph+',top='+topPos+', left='+leftPos + os);
	popup.moveTo(leftPos, topPos);
	if (popup.focus) popup.focus();
}


function goGSA()
{
	var searchQ=document.getElementById("q").value;
	if (searchQ!="Ricerca in SKY" && searchQ!="")
	{document.location.href="http://www.sky.it/itstatic/googlesearch/GSA.html?q="+searchQ;}
}

function movepic(img_name,img_src) 
{
	document[img_name].src=img_src;
}

function OpenCloseForm(ID) {
	var el = document.getElementById(ID);
	if (el.style.display == "block"){
		el.style.display="none";
	}
	else{
		el.style.display="block";
	}
}

function CloseForm(ID,cod) {
	var el = document.getElementById(ID);
	if(cod != 0)	
		el.style.display="none";	
}	




/*

// OVERLAY ELEZIONI

// Funzioni per cookie
function getCookieTG(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function setCookieTG(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

// Chiude Overlay
function removeOverlay() {
	var myOv = document.getElementById('advOverlay');
	if (myOv!=null){
		document.body.removeChild(myOv)
	}
}
// Visulizza Overlay
function viewOverlay() {
	if(document.layers) {
		width = window.innerWidth;
		height = window.innerHeight;
	} else { 
		width = document.body.clientWidth;
		height = document.body.clientHeight;
	}
	posx=(width/2)-(550/2)
	
	// Crea div
	var flO= '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="550" height="453" id="Overllayer_964x720" align="middle">'
	flO+='<param name="allowScriptAccess" value="always" />'
	flO+='<param name="movie" value="http://www.sky.it/swf/overlayelezioni/overlayelezioni.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />'
	flO+='<embed src="http://www.sky.it/swf/overlayelezioni/overlayelezioni.swf" quality="high" bgcolor="#ffffff" width="550" height="453" name="Overllayer_964x720" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
	flO+='</object>'
	
	var myOv = document.createElement('div');
	myOv.setAttribute('id','advOverlay');
	myOv.setAttribute('name','advOverlay');
	myOv.innerHTML = flO;
	
	myOv.style.position="absolute"
	myOv.style.zIndex="1";
	myOv.style.top=138; 
	myOv.style.left=posx-1;  
	myOv.style.width="550px"; 
	myOv.style.height="453px";
	//myOv.style.backgroundColor="transparent";
	//myOv.style.backgroundColor="transparent";
	myOv.style.display = "block";
	
	document.body.appendChild(myOv);
}
	
if (!/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))	{
	// Controlla cookie
	myChk=getCookieTG('chktg24over');
	if (myChk!=null && myChk!="")
  {
  }else{
  	setCookieTG('chktg24over','tg24SE',1);
		setTimeout("viewOverlay()", 2000);
		setTimeout("removeOverlay()", 15800);
	}
}


// FINE OVERLAY ELEZIONI*/


/*
Creazione cookie.
name: nome;
value: valore;
days: durata in ms.
*/
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + days);
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/; domain=.sky.it";
}

/*
Controllo esistenza cookie.
name: nome.
*/
function existCookie(name) {
	var ca = document.cookie.split(';');
	for( var i=0; i < ca.length; i++ ) {
		if (ca[i].substring(0, ca[i].indexOf('=')).indexOf(name) != -1) {
			return true; 
		}
	}
	return false;
}

function nielsenRefreshVP(url) {
	var baseUrl = "http://secure-it.imrworldwide.com/cgi-bin/m?ci=sky-it&rnd="+new Date().getTime()+"&cg=&si=";
	url = baseUrl + escape(url);
	$("#counter").attr("src", url);
}


//EVITA CACHING BANNER

$(document).ready(function(){


	var cacheRnd = Math.floor(Math.random()*10000);

	$("img.noCache").each(function(index) {
	
		$(this).attr("src", $(this).attr("src") + "?" + cacheRnd);
		
	});
	
	var search = '")';
	var subst = '?'+cacheRnd+'")';

	$("div.noCache").each(function(index) {
	
		$("img",$(this)).each(function(index) {
	
			$(this).attr("src", $(this).attr("src") + "?" + cacheRnd);
					
		});
							
        if($(this).css("background-image").indexOf(search) > -1)
                    
			$(this).css("background-image", $(this).css("background-image").replace(search,subst));

		
	});

});

