/*
todo:
- implementare il getToken sull'SSO solo nei siti esterni a *.rai.it
- testare .test al posto di .exec nella regexp
- verificare url con i ../../..
*/

if (!APDefined) {

var APDefined = true;

var apdebug = false;
var apdata = [];

var Hash;
var oldHash;
var Opening;
var DomainSuffix;
var token;

var LoginWindow;
var LoginError;
var isLoginOnTheFly;
var isLogin = false;
var isSubmit = false;

var WidgetList = [];
var WidgetSource = [];
var WidgetTitle = [];

var WidgetOpeningList = [];

var BrowserInfo;

//var absoluteLink;

var username;

var AjaxRefresh;

var objList = [];

var PopupWindow;
var PopupCode = '<div class="popup_container" style="position: absolute; visibility: hidden;">\
<div style="position: relative;  bottom: 4px;  margin-right: 20px;  margin-top:15px;  left:15px;">\
    <div style="margin:-10px 8px -10px -35px;    padding: 10px;    text-align: left;    background-color: #FFFFFF;    border: 1px solid #E6E6E6;    -webkit-border-radius: 10px;    -moz-border-radius: 10px;">\
        <div style="background-color:#AFC2DA;">\
            <div style="height:12px;padding:6px;color:#000000;">\
                <div style="float:left;	text-align:left;"></div>\
                <div class="popup_button_close" style="float:right;	background-image:url(\'/ajax-bz/common/data/image/button_widget_gray.gif\');	background-repeat:no-repeat;	width:15px;	height:15px; display:block; color:#000000;	font-size:10px; padding-top:1px; text-align:center; font-weight:bold; cursor: pointer;">X</div>\
                <div style="clear: both;"></div>\
            </div>\
            <div style="border-top:1px solid #999999;	padding:10px 17px 10px 17px;	font-weight:bold;	text-align:left;">\
                <div class="popup_alert" style="text-align:center;line-height:28px;">\
                </div>\
            </div>\
        </div>\
    </div>\
</div>\
</div>';

$jq(document).ready(function(){
   url = document.URL.split('/');
   tmp = url[2].split('.');
   if (tmp[tmp.length - 1] == 'rai') DomainSuffix = '.rai';
   else DomainSuffix = '.widget.rai.it';

   if (tmp[tmp.length - 2] == 'rai' && tmp[tmp.length - 1] == 'it') RAIdomain = true;
   else RAIdomain = false;

   BrowserInfo = $jq.browser;

   urlVars = $jq.getUrlVars();
   hashVars = $jq.getHashVars();

   /*if ($jq.getUrlVars()['token']) {
      $jq.cookie('token', $jq.getUrlVars()['token'], { path: '/' });
      token = $jq.getUrlVars()['token'];
   }*/

   if ($jq.getUrlVars()['d']) {
      apdebug = true;
      $jq("#ajax_crosssitebar_embed").bind('click', function() {
         $jq("#ajax_crosssitebar_embed").html(apdata.join('<br>'));
      });
   }

   if ($jq.cookie && (($jq.cookie('token') == null && $jq.cookie('tokenExt') == null) || fromOutside()) && !$jq.getUrlVars()['logout']) {    // logout si puņ togliere
      //location.href = "http://sso' + DomainSuffix + '/getToken.php?referer=" + location.href;
      $jq.ajax({
         url: 'http://sso' + DomainSuffix + '/getToken.php?callback=?',
         //url: 'http://ssoi.rai.it/getToken.php?callback=?',
         dataType: 'jsonp',
         success: function(data) {
            if (data['token']) {
               var expiry = new Date();
               if (data['ricordami']) expiry.setDate(expiry.getDate() + 365);
               else expiry.setHours(expiry.getHours() + 10);
               if (!RAIdomain) $jq.cookie('tokenExt', data['token'], { path: '/', expires: expiry });
               else $jq.cookie('token', data['token'], { path: '/', expires: expiry, domain: '.rai.it' });
               token = data['token'];
            }
            loadWidget();
         }
      });
   } else {
      if ($jq.cookie && ($jq.cookie('token') || $jq.cookie('tokenExt'))) {
         if ($jq.cookie('token')) token = $jq.cookie('token');
         else token = $jq.cookie('tokenExt');
      }
      loadWidget();
   }

   /*if (RAIdomain) {
      if ($jq.cookie && $jq.cookie('token')) token = $jq.cookie('token');
   } else {
      if (fromOutside()) {
         $jq.ajax({
            url: 'http://sso' + DomainSuffix + '/getToken.php?callback=?',
            dataType: 'jsonp',
            success: function(data) {
               if (data['token']) {
                  var expiry = new Date();
                  if (data['ricordami']) expiry.setDate(expiry.getDate() + 365);
                  else expiry.setMinutes(expiry.getMinutes() + 30);
                  $jq.cookie('token', data['token'], { path: '/', expires: expiry });
                  token = data['token'];
               }
               loadWidget();
            }
         });
      } else {
         if ($jq.cookie && $jq.cookie('token')) token = $jq.cookie('token');
      }
   }*/

   $jq(".loginonthefly-open").bind('click', function() {
      return LoginOnTheFly(this);
   });

   if (hashVars['ajax_anchor']) {
      onAjaxLoaded(function () {
         anchorList = $jq('a[name="' + hashData['ajax_anchor'] + '"]');
         if (anchorList.length == 0) return false;
         offset = $jq(anchorList[0]).offset();
         scrollto = offset.top;
         $jq('html, body').animate({scrollTop:scrollto}, 300);
         //$jq(window).scrollTop(scrollto);
      });
   }
});

function traceNielsen(key, val) {
   var l = window.location;

   if (!window.setNielsen) return true;

   if (key) {
      h = '#' + $jq.setHashVar(key, val);
   } else {
      h = l.hash;
   }

   setNielsen(l.protocol + '//' + l.host + l.pathname + l.search + h);
}

function hashPolling() {
   Hash = window.location.hash.slice(1);

   if (Hash != oldHash) {
      if ((decodeURIComponent(Opening) != Hash) && (Opening != Hash)) {
         apdata.push('hashPolling');
         apdata.push(decodeURIComponent(Opening));
         apdata.push(Hash);

         if (AjaxRefresh) {
            loadWidget(null, null, AjaxRefresh);
            AjaxRefresh = false;
         } else {
            loadWidget(null, true);
         }

         hashVars = $jq.getHashVars();
         if (hashVars['ajax_anchor']) {
            onAjaxLoaded(function () {
               anchorList = $jq('a[name="' + hashData['ajax_anchor'] + '"]');
               if (anchorList.length == 0) return false;
               offset = $jq(anchorList[0]).offset();
               if (!offset) return;
               scrollto = offset.top;
               $jq('html, body').animate({scrollTop:scrollto}, 300);
            });
         }
      }
   }
   oldHash = Hash;
   setTimeout('hashPolling();', 100);
}

function fromOutside() {
   if (!document.referrer) return true;
   if (document.referrer.split('/')[2] = String(document.location).split('/')[2]) return false;
   return true;
}

function FBLogin(url) {
   var base = 'https://graph.facebook.com/oauth/authorize?client_id=6b31ef27cc95e23864bfb232575d9b8b&scope=email,user_location,user_hometown,publish_stream,read_stream&redirect_uri=';
   url = url + '?redirect=' + encodeURIComponent(window.location.href);
   base = base + encodeURIComponent(url);
   window.location.href = base;
   return false;
}

function loadWidget(selector, preserve, exclude) {
   var data;

   if (apdebug) apdata.push('loadWidget(' + selector + ', ' + preserve + ')');
   oldHash = window.location.hash.slice(1);
   hashPolling();
   hashData = $jq.getHashVars();

   if (!selector) {
      selector = '.ajaxwidget'; // div
   } else {
      selector = selector + ' .ajaxwidget';
   }

   delay = 1;

   $jq(selector).each(function(index) {
      id = $jq(this).attr('id');
      if (id == exclude) return true;
      tmp = id.split('_');
      if (hashData[id]) {
         file = decodeURIComponent(hashData[id]);
      } else if (preserve && WidgetList[id]) {
         return;
      //else if ($jq("#" + id).html()) file = $jq("#" + id).html();
      } else if ($jq("#" + id).attr('title')) {
         file = $jq("#" + id).attr('title');
      } else if (WidgetTitle[id]) {
         file = WidgetTitle[id];
      } else {
         file = '';
      }
      if ($jq("#" + id).attr('title')) {
         WidgetTitle[id] = $jq("#" + id).attr('title');
         $jq("#" + id).attr('title', '');
      }
      widgetname = tmp[1];
      widgetmethod = tmp[2];
      if ((widgetname == 'crosssitebar' || widgetname == 'loginform') && LoginError) {
         //file = '?error=' + LoginError;
         data = 'error=' + LoginError;
         LoginError = '';
      }
      if (widgetname == 'crosssitebar' && isLogin) {
         if (data) data = data + '&Login=true';
         data = 'Login=true';
      }
      if (file.slice(0, 1) == '/') {
         file = file.slice(1);                                     // temporaneo
         path = "\/ajax-bz\/" + widgetname + "/" + file;
      } else {
         path = "\/ajax-bz\/" + widgetname + "/" + widgetmethod + "\/" + file;
      }
      WidgetList[id] = true;
      $jq("#" + id).html('<img src="/ajax-bz/common/data/images/loading.gif" />');
      if (apdebug) {
         loadAjax(path, '#' + id, data);
      } else {
         if (selector != '.ajaxwidget') loadAjax(path, '#' + id, data);
         else setTimeout('loadAjax("' + path + '", "#' + id + '", "' + data + '")', delay);
      }
      delay = delay + 100;
   });
}

function loadAjax(sourceURL, selector, senddata, sendmethod) {
   setOpening(sourceURL, selector);
   
   if (apdebug) {
      apdata.push(sourceURL + ' - ' + selector);
   }

   if (!senddata) {
      senddata = "__divID=" + selector.slice(1);
   } else {
      senddata = senddata + "&__divID=" + selector.slice(1);
   }
   if (token) senddata = senddata + "&token=" + token + "&mincache=true"
   if (location.search) senddata = senddata + "&__search=" + encodeURIComponent(location.search);
   if (location.host) senddata = senddata + "&__host=" + encodeURIComponent(location.host);
   if (!sendmethod) sendmethod = 'get';
   else sendmethod = sendmethod.toLowerCase();
   $jq.ajax({
      async : true,
      dataType : "html",
      evalScripts : true,
      data : senddata,
      type : sendmethod,
      cache : false,
      error : function (jqXHR, textStatus) {
         $jq(selector).html(textStatus);
         unsetOpening(sourceURL, selector);
      },
      success : function (data, textStatus) {
                   //if (BrowserInfo.msie && BrowserInfo.version < 9) {
                      $jq(selector).html(parseData(data, sourceURL, selector));
                      bindWidget(selector, sourceURL, true);
                   /*} else {
                      $jq(selector).html(data);
                      bindWidget(selector, sourceURL);
                   }*/
                   //$jq(selector).html(data);

                   //$jq(selector).html(parseData(data, sourceURL, selector));

                   loadWidget(selector);

                   unsetOpening(sourceURL, selector);
                },
      url : sourceURL}
   );
}

function setOpening(selector, sourceURL) {
   WidgetOpeningList[sourceURL + selector] = true;
}

function unsetOpening(selector, sourceURL) {
   delete (WidgetOpeningList[sourceURL + selector]);
   if (objectLength(WidgetOpeningList) == 0) setTimeout('checkOpening()', 300);
}

function objectLength(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function checkOpening() {
   if (objectLength(WidgetOpeningList) == 0) ajaxLoaded();
}

function ajaxLoaded() {
   while((obj = objList.pop()) !== undefined){
      obj();
   }
}

function onAjaxLoaded(obj) {
   objList.push(obj);
}

function parseData(data, sourceURL, selector) {

   var pattern = /href="([^"]+)"/gi;
   var patternClass = /class="([^"]+)"/gi
   var regexpmatch = pattern.exec(data);
   var results = new Array();

   data = data.replace(/<a[^>]+href="([^"]*)"[^>]*>/ig, function () {
       match = patternClass.exec(arguments[0]);
       if (match) {
          classList = match[1].split(' ');
          for (var p in classList) {
            if (classList[p] == 'ajax_exclude') return arguments[0];
          }
       }
       if (arguments[1] == '#') return arguments[0];
       if (arguments[1].slice(0, 1) == '#') {
          return (arguments[0].replace(arguments[1], '#ajax_anchor=' + arguments[1].slice(1)));
       }
       url = arguments[1];
       newURL = parseURL(arguments[1], sourceURL, selector);
       if (url == newURL) return arguments[0];
       else return (arguments[0].replace(url, newURL));
   });

   return data;
}

var patternABS = /\b\w+:\/\/(.*)/;

function parseURL(url, sourceURL, selector) {
   if (!url) return url;
   if (!patternABS.test(url)) {
      if (url == '#') return url;
      tmp = sourceURL.split('/');
      if (url.substr(0, 1) == '/') {
         tmp = tmp.slice(0, 3);
         dest = tmp.join('/') + url;
      } else {
         tmp = tmp.slice(0, tmp.length - 1);
         dest = tmp.join('/') +  '/' + url;
      }
      var ajaxanchor = '';
      tmp = dest.split('#');
      if (tmp.length > 1) {
         tmp2 = tmp[1].split('=');
         if (tmp2.length == 1) {
            ajaxanchor = tmp[1];
         } else if (tmp2.length == 2 && tmp2[0] == 'ajax_anchor') {
            ajaxanchor = tmp2[1];
         }
      }
      tmp = dest.split('#');
      dest = tmp[0];
      tmp = dest.split('/');
      tmp = tmp.slice(3, tmp.length);
      hashhref = '/' + tmp.join('/');
      data = new Array();
      data[selector.slice(1)] = hashhref;
      if (ajaxanchor) data['ajax_anchor'] = ajaxanchor;
      //var result = window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search + "#" + $jq.setHashVar(selector.slice(1), hashhref, true);
      var result = window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search + "#" + $jq.setHashVars(data);
      //if (ajaxanchor) result = result + '&ajax_anchor=' + ajaxanchor;
      return result;
   } else {
      return url;
   }
}

function getAnchor(dest) {
   tmp = dest.split('#');
   if (tmp.length > 1) {
      tmp2 = tmp[1].split('=');
      if (tmp2.length == 1) {
         ajaxanchor = tmp[1];
      } else if (tmp2.length == 2 && tmp2[0] == 'ajax_anchor') {
         ajaxanchor = tmp2[1];
      }
      return ajaxanchor;
   }
   return false;
}

function bindWidget(selector, sourceURL, parsedData) {
   if (parsedData) {
      $jq(selector + " a").bind('click', function() {
         if ($jq(this).hasClass('loginonthefly-open')) {
            if (!LoginOnTheFly(this)) return false;
         }

         if ($jq(this).hasClass('ajax_refresh')) AjaxRefresh = selector.slice(1);

         dhref = $jq(this).attr("href");
         currentPage = window.location.protocol + '//' + window.location.host + window.location.search;
         if (dhref.indexOf(currentPage) == 0) {
            dhref = dhref.slice(currentPage.length + 1);
         }

         if (dhref == '#') return false;

         if (dhref.slice(0, 13) == '#ajax_anchor=') {
            ajaxanchor = getAnchor(dhref);
            anchorList = $jq('a[name="' + ajaxanchor + '"]');
            if (anchorList.length == 0) return false;
            offset = $jq(anchorList[0]).offset();
            scrollto = offset.top;
            $jq('html, body').animate({scrollTop:scrollto}, 300);
            return false;
         }
      });
   } else {
      $jq(selector + " a:not(.ajax_exclude)").bind('click', function() {
         if ($jq(this).hasClass('loginonthefly-open')) {
            if (!LoginOnTheFly(this)) return false;
         }
         
         if ($jq(this).hasClass('ajax_refresh')) AjaxRefresh = true;

         dhref = $jq(this).attr("href");

         if (dhref == '#') return false;

         ajaxanchor = getAnchor(dhref);

         if (dhref.slice(0, 1) == '#') {
            anchorList = $jq('a[name="' + ajaxanchor + '"]');
            if (anchorList.length == 0) return false;
            offset = $jq(anchorList[0]).offset();
            scrollto = offset.top;
            $jq('html, body').animate({scrollTop:scrollto}, 300);

            Opening = $jq.setHashVar('ajax_anchor', dhref.slice(1));
            if (!$jq(this).hasClass('ajax_urlexclude')) window.location.hash = Opening;

            return false;
         }

         var pattern = /\b\w+:\/\/(.*)/;
         regexpmatch = pattern.exec(dhref);

         if (!regexpmatch) {
            /*if ((p = dhref.indexOf('#ajax_anchor=')) != -1) {
               anchorName = dhref.slice(p + 13);
               dhref = dhref.slice(0, p);
               onAjaxLoaded(function () {
                  anchorList = $jq('a[name="' + anchorName + '"]');
                  offset = $jq(anchorList[0]).offset();
                  scrollto = offset.top;
                  $jq('html, body').animate({scrollTop:scrollto}, 300);
               });
            }*/
            if (ajaxanchor) {
               onAjaxLoaded(function () {
                  anchorList = $jq('a[name="' + ajaxanchor + '"]');
                  if (anchorList.length == 0) return false;
                  offset = $jq(anchorList[0]).offset();
                  scrollto = offset.top;
                  $jq('html, body').animate({scrollTop:scrollto}, 300);
               });
            }
         }

         // IE workaround
   
         /*currentPage = window.location.protocol + '//' + window.location.host;
         if (dhref.indexOf(currentPage) == 0) {
            dhref2 = dhref.slice(currentPage.length + 1);
            if (dhref2.indexOf('embed/') == 0 || dhref2.indexOf('manager/') == 0 || dhref2.indexOf('config/') == 0 || dhref2.indexOf('data/') == 0) {
               // percorso assoluto
               dhref = '/' + dhref2;
   
               regexpmatch = false;
            }
         }*/

         // /IE workaround

         if (!regexpmatch) {
            tmp = sourceURL.split('/');
            if (dhref.substr(0, 1) == '/') {
               tmp = tmp.slice(0, 3);
               dest = tmp.join('/') + dhref;
            } else {
               tmp = tmp.slice(0, tmp.length - 1);
               dest = tmp.join('/') +  '/' + dhref;
            }
            tmp = dest.split('#');
            dest = tmp[0];
            tmp = dest.split('/');
            tmp = tmp.slice(3, tmp.length);
            hashhref = '/' + tmp.join('/');
            data = new Array();
            data[selector.slice(1)] = hashhref;
            if (ajaxanchor) {
               data['ajax_anchor'] = ajaxanchor;
            }
            Opening = $jq.setHashVars(data);
            if (selector.split('_').length == 3) {
               if (!$jq(this).hasClass('ajax_urlexclude')) window.location.hash = Opening;
            }
            traceNielsen();

            if (AjaxRefresh) {
               onAjaxLoaded(function () {
                  loadWidget(null, null, selector.slice(1));
               });
               AjaxRefresh = false;
            }

            loadAjax(dest, selector);
            return false;
         } else {
            //absoluteLink = true;
            return true;
         }
      });
   }
   $jq(selector + " .loginonthefly-open").bind('click', function() {
      if ($jq(this).hasClass('ajax_exclude')) {
         if (!LoginOnTheFly(this)) return false;
      }
   });
   $jq(selector + " form:not(.ajax_exclude)").bind('submit', function() {
      if (isSubmit) return false;
      if ($jq(this).hasClass('ajax_login')) {
         isSubmit = true;
         var values = {};
         $jq.each($jq(this).serializeArray(), function(i, field) {
             values[field.name] = field.value;
         });

         if (selector == '#loginonthefly') isLoginOnTheFly = true;
         else isLoginOnTheFly = false;

         username = values['username'];

         if (values['ricordami'] == 'true') ricordami = true;
         else ricordami = '';
         $jq.ajax({
            url: 'http://sso' + DomainSuffix + '/smartLogin.php?username=' + values['username'] + '&password=' + values['password'] + '&ricordami=' + ricordami + '&callback=?',
            dataType: 'jsonp',
            success: function(data) {
               isSubmit = false;
               if (data['token']) {
                  var expiry = new Date();
                  if (values['ricordami']) expiry.setDate(expiry.getDate() + 365);
                  else expiry.setHours(expiry.getHours() + 10);

                  if (!RAIdomain) $jq.cookie('tokenExt', data['token'], { path: '/', expires: expiry});
                  token = data['token'];

                  isLogin = true;

                  setRaiTV(token, data['username']);

                  /*if (location.hostname == 'www.rai.tv') {
                     location.reload(true);
                     return;
                  }*/

                  hideLoginOnTheFly();
               }
               if (data['redirect']) {
                  window.location.href = decodeURIComponent(data['redirect']);
               }
               if (data['error']) {
                  if (isLoginOnTheFly) {
                     LoginOnTheFlyError(data['error']);
                  } else {
                     LoginError = data['error'];
                     if ($jq('#ajax_crosssitebar_embed').attr('id') != null) {
                        loadAjax('/ajax-bz/crosssitebar/embed/?error=' + LoginError, '#ajax_crosssitebar_embed');
                        if ($jq('#ajax_loginform_embed').attr('id') != null) {
                          loadAjax('/ajax-bz/loginform/embed/?error=' + LoginError, '#ajax_loginform_embed');
                        }
                        return false;
                     }
                  }
               }
               loadWidget();
            },
            error: function(xhr, ajaxOptions, thrownError) {
               isSubmit = false;
            }
         });
         return false;
      } else {
         if ($jq(this).hasClass('loginonthefly-open')) {
            if (!LoginOnTheFly(this)) return false;
         }
         dhref = $jq(this).attr('action');
         var pattern = /\b\w+:\/\/(.*)/;
         regexpmatch = pattern.exec(dhref);
         if (!regexpmatch) {
            isSubmit = true;
            tmp = sourceURL.split('/');
            if (dhref.substr(0, 1) == '/') {
               tmp = tmp.slice(0, 3);
               dest = tmp.join('/') + dhref;
            } else {
               tmp = tmp.slice(0, tmp.length - 1);
               dest = tmp.join('/') +  '/' + dhref;
            }
            tmp = dest.split('/');
            tmp = tmp.slice(3, tmp.length);
            hashhref = '/' + tmp.join('/');
            traceNielsen(selector.slice(1), hashhref);
            //loadAjax(dest, selector, $jq(this).serialize(), $jq(this).attr('method'));
            /*extradata = "__divID=" + selector.slice(1);
            if (token) senddata = senddata + "&token=" + token + "&mincache=true"
            if (location.search) senddata = senddata + "&__search=" + encodeURIComponent(location.search);
            if (location.host) senddata = senddata + "&__host=" + encodeURIComponent(location.host);*/
            WidgetSource[selector] = dest;

   			 $jq(this).ajaxSubmit({
              url: dest,
   			 	target: selector,
   			 	success: bindInterface,
               error: function(xhr, ajaxOptions, thrownError) {
                  isSubmit = false;
               },
   			 	data: { __divID: selector.slice(1),
   			 	        token: token,
   			 	        __search: encodeURIComponent(location.search),
   			 	        __host: encodeURIComponent(location.host) }
   			 });
            return false;
         } else {
            return true;
         }
      }
   });
}

function bindInterface(responseText, statusText, xhr, $form) {
   isSubmit = false;
   selector = '#' + $jq(this).attr('id');
   sourceURL = WidgetSource[selector];

   bindWidget(selector, sourceURL);
}

function checkLoginOnTheFly(formData, jqForm, options) {
   if (jqForm.hasClass('loginonthefly-open')) {
      if (!LoginOnTheFly(jqForm)) return false;
   }
   return true;
}

function setRaiTV(token, username) {
   var data = token+'-'+username;
   $jq('iframe#MyRaiTvLogin').remove();
   $jq('<iframe id="MyRaiTvLogin" src="http://www.rai.tv/dl/js/cookieUtils.html?m=s&amp;n=MyRaiTvUser&amp;c='+data+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($jq('body'));
   $jq('iframe#RaiItLogin').remove();
   $jq('<iframe id="RaiItLogin" src="http://www.rai.it/dl/js/cookieUtils.html?m=s&amp;n=MyRaiTvUser&amp;c='+data+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($jq('body'));
}

function Logout() {
   if ($jq.cookie('token') != null || $jq.cookie('tokenExt') != null) {
      $jq.ajax({
         url: 'http://sso' + DomainSuffix + '/smartLogout.php?callback=?',
         dataType: 'jsonp',
         success: function(data) {
            //if ($jq.cookie('token') != null)
            $jq.cookie('token', null, { path: '/', domain: '.rai.it' });
            //if ($jq.cookie('tokenExt') != null)
            $jq.cookie('tokenExt', null, { path: '/' });
            if (location.hostname == 'www.rai.tv') {
               location.reload(true);
               return;
            }
            $jq('iframe#MyRaiTvLogin').remove();
            $jq('<iframe id="MyRaiTvLogin" src="http://www.rai.tv/dl/js/cookieUtils.html?m=r&amp;n=MyRaiTvUser" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($jq('body'));
            $jq('iframe#RaiItLogin').remove();
            $jq('<iframe id="RaiItLogin" src="http://www.rai.it/dl/js/cookieUtils.html?m=r&amp;n=MyRaiTvUse" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($jq('body'));
            token = null;
            loadWidget();
         }
      });
   }
}

function LoginOnTheFly(object) {
   if ($jq.cookie('token') != null || $jq.cookie('tokenExt') != null) return true;

   offset = $jq(object).offset();
   dw = $jq(document).width();

   if (!LoginWindow) {
      $jq("body").prepend('<div id="loginonthefly" style="position: absolute; visibility: hidden;"></div>');
      LoginWindow = true;
      loadAjax("/ajax-bz/loginonthefly/embed/", "#loginonthefly");
   }

   if (offset.left < (dw / 2)) {
      positionX = offset.left;
   } else {
      positionX = offset.left - $jq("#loginonthefly").width();
   }

   positionY = offset.top;

   showLoginOnTheFly(positionX, positionY);
   
   return false;
}

function Popup(object, code) {
   offset = $jq(object).offset();
   dw = $jq(document).width();

   if (!PopupWindow) {
      $jq("body").prepend(PopupCode);
      $jq('.popup_button_close').click(function() {
         hidePopup();
      });
      PopupWindow = true;
   }
   $jq(".popup_alert").html(code);

   if (offset.left < (dw / 2)) {
      positionX = offset.left;
   } else {
      positionX = offset.left - $jq(".popup_container").width();
   }

   positionY = offset.top;

   showPopup(positionX, positionY);

   return false;
}

function showPopup(positionX, positionY) {
   $jq(".popup_container").attr('style', 'position: absolute; visibility: visible; left: ' + positionX + 'px; top: ' + positionY + 'px; z-index: 10000000;');
}

function hidePopup() {
   $jq(".popup_container").attr('style', 'position: absolute; visibility: hidden;');
}

function showLoginOnTheFly(positionX, positionY) {
   $jq("#loginonthefly").attr('style', 'position: absolute; visibility: visible; left: ' + positionX + 'px; top: ' + positionY + 'px; z-index: 10000000;');
}

function hideLoginOnTheFly() {
   $jq("#loginonthefly").attr('style', 'position: absolute; visibility: hidden;');
}

function LoginOnTheFlyError(error) {
   if (error == 'auth') {
      $jq("#loginonthefly .error_alert").html("Errore Nickname o Password errati");
   } else if (error == 'confirm') {
      $jq("#loginonthefly .error_alert").html("Account non verificato. Conferma l'account della registrazione del tuo indirizzo email.");
   }
}

$jq.getScripts = function(scripts, onComplete) {
        var i = 1;
        var ii = scripts.length;
        var onScriptLoaded = function(data, response) { if (i++ == ii && typeof onComplete == 'function') onComplete(); } ;
        for(var s in scripts) {
				$jq.ajaxSetup({ cache: true });
	 			$jq.getScript(scripts[s], onScriptLoaded);
				$jq.ajaxSetup({ cache: false });
	 	} ;
};

$jq.getScriptsB = function(scripts, onComplete) {
   getScriptsList = scripts;
   getScriptsOnComplete = onComplete;
   $jq.getScriptRecursive();
};

var getScriptsList;
var getScriptsOnComplete;

$jq.getScriptRecursive = function() {
   var script = '';

   if (getScriptsList.length == 0) {
      if (typeof getScriptsOnComplete == 'function') getScriptsOnComplete();
   } else {
      script = getScriptsList.shift();
		$jq.ajaxSetup({ cache: true });
      $jq.getScript(script, function(data, response) { $jq.getScriptRecursive(); });
		$jq.ajaxSetup({ cache: false });
   }
}

var loadedStyles = new Array();

$jq.getStyles = function(scripts) {
        for(var s in scripts) {
			if (-1 == $jq.inArray(scripts[s],loadedStyles)){
				$jq("head").append("<link>");
                    css = $jq("head").children(":last");
                    css.attr({
                      rel:  "stylesheet",
                      type: "text/css",
                      href: scripts[s]
                    });
				loadedStyles.push(scripts[s]);
				
			}
                
        };
};

// $jq.getStyles = function(scripts) {
//         for(var s in scripts) {
// /*                $jq("head").append("<link>");
//                     css = $jq("head").children(":last");
//                     css.attr({
//                       rel:  "stylesheet",
//                       type: "text/css",
//                       href: scripts[s]
//                     });*/
// $jq("head").append('<link rel="stylesheet" href="' + scripts[s] + '" type="text/css" />');
//         } ;
// };

$jq.extend({
  getUrlVars: function(){
    var vars = [], hash;
    if (window.location.href.indexOf('#') != -1) to = window.location.href.indexOf('#');
    else to = window.location.href.length;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1, to).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $jq.getUrlVars()[name];
  },
  getHashVars: function(hash){
    var vars = [];
    if (!hash) hash = window.location.hash;
    else hash = '#' + hash;
    var hashes = hash.slice(1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      //vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getHashVar: function(name){
    return $jq.getHashVars()[name];
  },
  setHashVar: function(key, val){
     var out = '';
     key = encodeURIComponent(key);
     val = encodeURIComponent(val);
     hashData = $jq.getHashVars();
     hashData[key] = val;
     for (var k1 in hashData)
     {
        if (!hashData[k1]) continue;
        out = out + '&' + k1 + '=' + hashData[k1];
     }
     return out.slice(1);
  },
  setHashVars: function(data, hashData){
     var out = '';
     if (!hashData) hashData = $jq.getHashVars();
     for (var k in data) {
        key = k;
        val = data[k];
        hashData[key] = val;
     }
     for (var k1 in hashData)
     {
        if (!hashData[k1]) continue;
        out = out + '&' + k1 + '=' + hashData[k1];
     }
     return out.slice(1);
  }
});

}

