/**
 * geolocation 
 * 
 * author: Nico Kaiser
 * email: nico.kaiser@sport1.de
 * 
 */
SPORT1_Geolocation = new function(){
  this.url = new Object();
  this.url["ch"] = "http://www.sport1.ch";
  this.url["other"] = "http://www.sport1.de";
  
  this.randomizer = 200;
  // time in ms for checking script value
  this.checkScriptInterval = 50;
  
  this.geolocationApi = "http://geolocation.sport1.de/geo.js";
  this.geolocationApiTimeout = 1000;
  
  // cookie params
  this.cookieExpires = 315360000000;  //60*60*24*365*10*1000 = 10 years
  this.cookieDomain = "sport1.de";
  this.cookiePath = "/";
  this.geoCookieName = "SPORT1_Geolocation_geo";
  this.preferredCookieName = "SPORT1_Geolocation_preferred";
  
  // text 
  this.textIntro = "Ausgabe w&auml;hlen: ";
  this.textLinkSeparator = " | ";
  this.htmlContainerId = "header_center";
  this.htmlTargetContainerId = "sport1View";
  
  this.countryText = new Object();
  this.countryText['other'] = "Deutschland";
  this.countryText['ch'] = "Schweiz";
  
  // global vars
  this.currentDomain;
  this.geoCookieValue;
  this.preferredCookieValue;
  this.redirectURLParam = "r";
  
  //domains that not group as other
  this.domainGroupWhiteList = new Array( 'ch' );
  this.disableRandomizer = true;
  
  this.init = function() {
    if ( SPORT1_Geolocation.getURLParameter( "RAND" ) == "true" ) {
      SPORT1_Geolocation.disableRandomizer = true;
    }
    SPORT1_Geolocation.addEvent( window, 'load' , SPORT1_Geolocation.displayBackLink);
    SPORT1_Geolocation.currentDomain = SPORT1_Geolocation.getCurrentDomain();
    
    if ( navigator.cookieEnabled ) {
      SPORT1_Geolocation.log( 'SPORT1_Geolocation.init | Cookie enabled' );
      SPORT1_Geolocation.geoCookieValue = SPORT1_Geolocation.getCookie( SPORT1_Geolocation.geoCookieName );
      var redirectValue = SPORT1_Geolocation.getUrlData( SPORT1_Geolocation.redirectURLParam );
      SPORT1_Geolocation.preferredCookieValue = SPORT1_Geolocation.getCookie( SPORT1_Geolocation.preferredCookieName );
      if ( typeof( redirectValue ) != "undefined" ) {
        SPORT1_Geolocation.writeCookieData( SPORT1_Geolocation.preferredCookieName, redirectValue );
        SPORT1_Geolocation.preferredCookieValue = redirectValue;
      }
      SPORT1_Geolocation.evaluateApiCall();
      
    } else {
      SPORT1_Geolocation.log( 'SPORT1_Geolocation.init | Cookie disabled' );
    }
  }
  
  this.evaluateApiCall = function() {
    if ( typeof( SPORT1_Geolocation.geoCookieValue ) == "undefined" ) {
      if( SPORT1_Geolocation.checkRandomizer() ) {
        SPORT1_Geolocation.writeGeolocationScript();
      }
    } else {
      SPORT1_Geolocation.evaluateAllData();
    }
  }
  
  /**
   * checks if the randomize equal 1 and returns true otherwise false
   * 
   * @return bool
   */           
  this.checkRandomizer = function() {
    SPORT1_Geolocation.log( 'SPORT1_Geolocation.checkRandomizer' );
    if ( SPORT1_Geolocation.disableRandomizer === true ) {
      return true;
    }
    
    try {
      var rand = Math.floor( Math.random() * SPORT1_Geolocation.randomizer );
      SPORT1_Geolocation.log( 'SPORT1_Geolocation.checkRandomizer | Number: ' + rand );
      if ( rand <= 1 ) {
        return true;
      } else {
        return false;
      }
    } catch( e ) {
      SPORT1_Geolocation.log( 'SPORT1_Geolocation.checkRandomizer | Error: ' + e );
      return true;
    }
  }
  
  /**
  * write a script tag in head with src geotarget api
  * 
  * @return void
  */
  this.writeGeolocationScript = function() {
    SPORT1_Geolocation.log('SPORT1_Geolocation.writeGeolocationScript');
    try {
      document.write('<scr' + 'ipt type="text/javascr' + 'ipt" src="' + SPORT1_Geolocation.geolocationApi + '"></scr' + 'ipt>');
      var dateObj = new Date();
      SPORT1_Geolocation.checkScriptIntervalTimer = dateObj.getTime();
      SPORT1_Geolocation.checkScriptDataInterval = window.setInterval("SPORT1_Geolocation.checkScriptData()", SPORT1_Geolocation.checkScriptInterval);
    } catch (e) {
      SPORT1_Geolocation.log('SPORT1_Geolocation.writeGeolocationScript | Error: ' + e);
    }
  }
  
  /**
  * check if the api set a defined value
  * 
  */
  this.checkScriptData = function() {
    SPORT1_Geolocation.log('SPORT1_Geolocation.checkScriptData');
    try {
      var dateObj = new Date();
      if ( ( dateObj.getTime() - SPORT1_Geolocation.checkScriptIntervalTimer ) >= SPORT1_Geolocation.geolocationApiTimeout ) {
        window.clearInterval( SPORT1_Geolocation.checkScriptDataInterval );
        SPORT1_Geolocation.log('SPORT1_Geolocation.checkScriptData | clearInterval after timeout');
        SPORT1_Geolocation.validateRequestData(geolocation);
      } else {
        if( typeof(geolocation) != "undefined" ) {
          window.clearInterval( SPORT1_Geolocation.checkScriptDataInterval );
          SPORT1_Geolocation.log('SPORT1_Geolocation.checkScriptData | clearInterval found value: ' + geolocation);
          SPORT1_Geolocation.validateRequestData(geolocation);
        }
      }
    } catch(e) {
      SPORT1_Geolocation.log('SPORT1_Geolocation.checkScriptData | Error: ' + e);
    }
  }
  
  /**
   * evaluate the api return value
   *    
   * @return void
   */
  this.validateRequestData = function(pValue) {
    SPORT1_Geolocation.log('SPORT1_Geolocation.evaluateRequestData');
    if ( typeof(pValue) != "undefined" && pValue != "" ) {
      pValue = pValue.toLowerCase();
      if ( !SPORT1_Geolocation.inArray(SPORT1_Geolocation.domainGroupWhiteList , pValue)) {
        pValue = 'other';
      }
      SPORT1_Geolocation.writeCookieData(SPORT1_Geolocation.geoCookieName, pValue);
      SPORT1_Geolocation.geoCookieValue = pValue;
      SPORT1_Geolocation.evaluateAllData();
    }
  }

  this.evaluateAllData = function() {
    if ( typeof(SPORT1_Geolocation.preferredCookieValue) != "undefined" && SPORT1_Geolocation.geoCookieValue == "ch") {
  /*      //show backlink
      SPORT1_Geolocation.log('SPORT1_Geolocation.checkCookieData | show Backlink');
      SPORT1_Geolocation.log('SPORT1_Geolocation.checkCookieData | document.readyState = ' + document.readyState);
    if (document.readyState == "complete") {
        SPORT1_Geolocation.displayBackLink();
      } else {
         SPORT1_Geolocation.addEvent( window, 'load' , SPORT1_Geolocation.displayBackLink);
      }*/
    } else if(typeof(SPORT1_Geolocation.preferredCookieValue) == "undefined" && SPORT1_Geolocation.geoCookieValue == "ch") {
      SPORT1_Geolocation.log('SPORT1_Geolocation.checkCookieData | redirect to: ' + SPORT1_Geolocation.url[SPORT1_Geolocation.geoCookieValue]);
      SPORT1_Geolocation.writeCookieData(SPORT1_Geolocation.geoCookieName, SPORT1_Geolocation.geoCookieValue);
      SPORT1_Geolocation.redirect(SPORT1_Geolocation.url[SPORT1_Geolocation.geoCookieValue]);
    }
  }
  
  
  
  
  /**
   * show the backlink
   * 
   * @return void
   */
  this.displayBackLink = function() {
    SPORT1_Geolocation.log('SPORT1_Geolocation.displayBackLink');
    try {
      var array = new Array();
      for( var domain in SPORT1_Geolocation.countryText ) {
        if ( domain != SPORT1_Geolocation.currentDomain ) {
          array.push('<a title="SPORT1 - ' + SPORT1_Geolocation.countryText[domain] + ' - Sport, News, Ergebnisse, Live Ticker" class="link font_12" href="' + SPORT1_Geolocation.url[domain] + '">' + SPORT1_Geolocation.countryText[domain] + '</a>');
        } else {
          array.push('<span class="font_56">' + SPORT1_Geolocation.countryText[domain] + '</span>');
        }
      }
      if (document.getElementById( SPORT1_Geolocation.htmlTargetContainerId ) == null) {
        document.getElementById( SPORT1_Geolocation.htmlContainerId ).innerHTML += '<div class="geotargeting font_12">' + SPORT1_Geolocation.textIntro + " " + array.join(" " + SPORT1_Geolocation.textLinkSeparator + " ") + '</div>';
      }
    } catch ( e ) {
      SPORT1_Geolocation.log('SPORT1_Geolocation.displayBackLink | Error: ' + e);
    }
  }
  /**
   * redirect to given location
   * 
   * @param string  pTarget: the given location
   * @return void      
   */
  this.redirect = function( pTarget ) {
    SPORT1_Geolocation.log('SPORT1_Geolocation.redirect');
    SPORT1_Geolocation.log('SPORT1_Geolocation.redirect | ' + pTarget);
    try {
      window.location.href = pTarget;
    } catch (e) {
      SPORT1_Geolocation.log('SPORT1_Geolocation.redirect | Error: ' + e);
    }
  }
  
  /**
  * returns the current domain from host entry
  * 
  * @return void
  */
  this.getCurrentDomain = function() {
    var d = window.location.host;
    d = d.substr( d.lastIndexOf('.') + 1 );
    if ( !SPORT1_Geolocation.inArray(SPORT1_Geolocation.domainGroupWhiteList , d)) {
      d = 'other';
    }
    SPORT1_Geolocation.log('SPORT1_Geolocation.extractActualDomain | actual domain: ' + d);
    return d;
  }
  
  /**
   * write the cookieData to several Domains
   * 
   * @param string  pValue: the given value
   * @return void         
   */
  this.writeCookieData = function(pName, pValue) {
    SPORT1_Geolocation.log('SPORT1_Geolocation.writeCookieData');
    try {
      var dateObj = new Date();
      var expires = dateObj.getTime() + SPORT1_Geolocation.cookieExpires;
      dateObj.setTime(expires);
      if (SPORT1_Geolocation.cookieDomain != undefined) {
        SPORT1_Geolocation.log('SPORT1_Geolocation.writeCookieData name: ' + pName + ' | value: ' + pValue + ' | domain: ' + SPORT1_Geolocation.cookieDomain + ' | expires: ' + dateObj.toGMTString());
        SPORT1_Geolocation.setCookie(pName, pValue, dateObj, SPORT1_Geolocation.cookiePath, SPORT1_Geolocation.CookieDomain, false);
      }
    } catch (e) {
      SPORT1_Geolocation.log('SPORT1_Geolocation.writeCookieData Error: ' + e);
    }
  }

  /**
   * extraxt the # from url
   * 
   * @return string   
   */  
  this.getUrlData = function(pUrlParam) {
    SPORT1_Geolocation.log('SPORT1_Geolocation.getUrlData');
    try {
      var url = document.location.hash.replace('#','');
      var string = pUrlParam + '=';
      if ( url.lastIndexOf(string) != -1 ) {
        var d = url.substr(url.lastIndexOf(string) + string.length,9);
        if (!SPORT1_Geolocation.inArray( SPORT1_Geolocation.domainGroupWhiteList ,d)) {
          d = "other";
        }
        SPORT1_Geolocation.log('SPORT1_Geolocation.getUrlData | Found UrlData[' + pUrlParam + ']: ' + d);
        return d;
      } else {
        SPORT1_Geolocation.log('SPORT1_Geolocation.getUrlData | Not Found UrlData[' + pUrlParam + ']');
        return;
      }
    } catch ( e ) {
      SPORT1_Geolocation.log('SPORT1_Geolocation.getUrlData Error: ' + e);
      return;
    }
  }

  // Helper Functions
  this.inArray = function( pArray, pValue) {
    try {
      SPORT1_Geolocation.log('SPORT1_Geolocation.inArray pValue: ' + pValue);
      for(var i in pArray) {
      if(pArray[i] == pValue) {
        return true;
      }
      }
      return false;
    } catch (e) {
      SPORT1_Geolocation.log('SPORT1_Geolocation.inArray Error: ' + e);
    }
  }

  /* Event Listener */
  /* Sport1.addEvent( window, 'load', FUNKTION ); */
  this.addEvent = function( obj, evType, func ){
  if (obj.addEventListener){ 
    obj.addEventListener( evType, func, false ); 
    return true; 
  }
  else if ( obj.attachEvent ){ 
    var r = obj.attachEvent( "on" + evType, func ); 
    return r; 
  }
  else { 
    return false; 
  }
  }

  this.setCookie = function( name, value, expires, path, domain, secure ) {
  var cookieString = name+'='+escape(value)
            +((expires)?';expires='+expires.toGMTString():'')
            +((path)?';path='+path:'')
            +((domain)?';domain='+domain:'')
            +((secure)?';secure':'');
  document.cookie = cookieString;
  }

  this.getCookie = function( name ){
  var arg = name+'=';
  var alen = arg.length;
  var clen = document.cookie.length;
  var i=0;
  while( i < clen ){ 
    var j = i + alen;
    if(document.cookie.substring(i,j)==arg){
    return this.getCookieVal(j);
    }
    i = document.cookie.indexOf( ' ', i ) + 1;
    if( i==0 ){
    break;
    }
  }
  return;
  }

  this.getCookieVal = function( offset ){
  var endstr = document.cookie.indexOf( ';', offset );
  if( endstr == -1 ){
    endstr = document.cookie.length;
  }
  return unescape( document.cookie.substring( offset, endstr ) );
  }

  this.getURLParameter = function ( pParamName ) {
  var result = false;
  var searchText = window.location.search.substr(1);

  if (searchText.indexOf(pParamName) >= 0) {
    splitText = searchText.split('&');
    for (var i = 0; i < splitText.length; i++) {
      if (splitText[i].indexOf(pParamName) >= 0) {
        result = splitText[i].substr((pParamName.length + 1));
      }
    }
  }
  return result;
  }

  this.log = function( pWhat ){
  try{
    var FFconsole = false;
    if( (navigator.userAgent.indexOf('Firefox') >= 0 ||
      navigator.userAgent.indexOf('Chrome') >= 0) && 
      SPORT1_Geolocation.getURLParameter( "DEBUG" )
    ){
    FFconsole = true;
    console.log( "SPORT1: " + pWhat );
    }
  }catch( e ){}
  }
}

SPORT1_Geolocation.init();
