// Create our global namespace
var PS = {

  /**
   * PS.set(namespace[, keys])
   * Sets a namespace (and its keys) into the global PS namespace.
   * 
   * @param {String} namespace: The namespace
   * @param {Object} [optional] keys: An object of keys to set in namespace
   */
  set: function(namespace, keys) {
    if (!PS[namespace]) {
      PS[namespace] = keys;
    } else {
      for (var key in keys) {
        PS[namespace][key] = keys[key];
      }
    }
  },

  /**
   * PS.get(namespace[, key])
   * Returns a namespace, or a key from a namespace, from the global PS namespace.
   * 
   * @param {String} namespace: The namespace to retrieve
   * @param {String} [optional] key: The key to retrieve from namespace
   */
  get: function(namespace, key) {
    if (PS[namespace]) {
      return !key ? PS[namespace] : PS[namespace][key];
    }
  }

};

PS.Ads = {
  wallpaper: false
};

// Utility functions
PS.util = {

  /*
   * The cookie functions (working just like the ones from PHP).
   */
  getCookie: function(name) {
    var start = document.cookie.indexOf(name + '='), len = start + name.length + 1;
  
    if ((!start && (name != document.cookie.substring(0, name.length))) || (start == -1)) {
      return null;
    }
  
    var end = document.cookie.indexOf(';', len);
    if (end == -1) {
      end = document.cookie.length;
    }
  
    return unescape(document.cookie.substring(len, end));    
  },
  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 expiresDate = new Date(today.getTime() + expires);
  
    document.cookie = name + '=' + escape(value) +
      (expires ? ';expires='+expiresDate.toGMTString() : '') +
      (path ? ';path=' + path : '') +
      (domain ? ';domain=' + domain : '') +
      (secure ? ';secure' : '');
  },
  deleteCookie: function(name, path, domain) {
    if (PS.util.getCookie(name)) {
      document.cookie = name + '=' +
        (path ? ';path=' + path : '') +
        (domain ? ';domain=' + domain : '') +
        ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
    }
  }

};

if (typeof Prototype !== 'undefined') {

  PS.Popup = Class.create({
    initialize: function(anchor, name, url, params) {
      this.name = name.capitalize();
      this.url = url;
      this.params = params.join(',');
      anchor.observe('click', this.openPopup.bind(this));
    },
    openPopup: function(e) {
      e.stop();
      window.open(this.url, this.name, this.params);
    }
  });

  /**
   * Prototype Marquee Class
   * Based on the implementation of Eric Anderson
   * http://gist.github.com/548690
   */
  PS.Marquee = Class.create({
    initialize: function(element, options) {
      this.element = $(element);
      this.paused = false;
  
      // If everything fits don't bother with all this mess
      if (this.element.scrollWidth == this.element.clientWidth) {
        return;
      }
  
      // Defaults to scrolling through all content in 40 seconds.
      // There is a limit to how fast we can go since we move by a pixel
      // at a time (for smooth scrolling) and most browsers can only call
      // our callback so fast even if we tell it to go faster.
      this.options = {
        duration: 40,
        separator: ''
      };
  
      Object.extend(this.options, options || {});
  
      // Store the original content for later reset through stop method
      this.originalContent = this.element.clone(true);
  
      // Append the separator
      this.element.innerHTML += this.options.separator;
  
      // Create wrapping container to scroll the marquee in. Move
      // some of the relevant marquee styles to this wrapper.
      this.container = this.element.wrap('div');
      this.container.setStyle({
        width: this.element.clientWidth+'px',
        height: this.element.clientHeight+'px',
        overflow: 'hidden'
      });
  
      // Keep in mind how big it was so we know when to reset
      this.originalWidth = this.element.scrollWidth;
  
      // Make it look like it is wrapping around by duping content
      this.element.innerHTML += this.element.innerHTML;
  
      // Record the movement necessary before we reset to the start
      this.resetWidth = this.element.scrollWidth - this.originalWidth;
  
      // Size restrictions/clipping moved to wrapper, remove from element
      this.element.setStyle({
        width: this.element.scrollWidth+'px',
        height: this.element.scrollHeight+'px',
        overflow: 'auto'
      });
  
      // Calculate how often to move and setup timer
      var frequency = this.options.duration / this.element.getWidth();
      frequency = (100 * frequency).round() / 100;
  
      this.pe = new PeriodicalExecuter(this.move.bind(this), frequency);
  
      // Setup events to pause animation if moused over
      this.pauseHandler = this.element.on('mouseover', this.pause.bind(this));
      this.playHandler = this.element.on('mouseout', this.play.bind(this));
    },

    move: function() {
      if (this.paused) {
        // Don't scroll if paused
        return;
      }
  
      // If we have scrolled all content reset back to the start
      if (this.container.scrollLeft == this.resetWidth) {
        this.container.scrollLeft = 0;
      }
  
      // Scroll just by a pixel
      this.container.scrollLeft += 1;
    },
  
    pause: function() { this.paused = true; },
    play: function() { this.paused = false; },
  
    stop: function() {
      // If the marquee (aka PeriodicalExecuter) was applied, stop it
      // plus all event handlers, and restore the original content.
      if (this.pe) {
        [this.pe, this.pauseHandler, this.playHandler].invoke('stop');
        this.container.replace(this.originalContent);
      }
    }
  });

  /**
   * Class to fetch phonostars Twitter timeline.
   * @param {Object|String} twtUpdateList: The DOM list to update
   * @param {String} callback: The Twitter callback function
   */
  PS.TwtTimeline = Class.create({
    
    initialize: function(twtUpdateList, callback) {
      this.twtUpdateList = twtUpdateList;
      this.script = new Element('script', { src: 'http://twitter.com/statuses/user_timeline/16925417.json?callback=' + callback });
    },
    
    fetch: function() {
      document.body.appendChild(this.script);
    },
  
    callback: function(response) {
      $(this.script).remove();
  
      var li = new Template('<li><span>#{formattedStatus}</span> <a style="font-size:85%" href="#{statusUrl}">#{relativeTime}</a></li>');
  
      function relativize(timeValue) {
        var values     = timeValue.split(' '),
            parsedDate = Date.parse(values[1] + ' ' + values[2] + ', ' + values[5] + ' ' + values[3]),
            relativeTo = new Date(),
            delta      = parseInt((relativeTo.getTime() - parsedDate) / 1000),
            relative   = '';

        delta = delta + (relativeTo.getTimezoneOffset() * 60);
  
        if (delta < 5) {
          relative = 'vor weniger als 5 Sekunden';
        } else if (delta < 30) {
          relative = 'vor einer halben Minute';
        } else if (delta < 60) {
          relative = 'vor weniger als 1 Minute';
        } else if (delta < 120) {
          relative = 'vor 1 Minute';
        } else if (delta < (45*60)) {
          relative = 'vor ' + (parseInt(delta / 60)).toString() + ' Minuten';
        } else if (delta < (2*90*60)) {
          relative = 'vor ungef&auml;hr 1 Stunde';
        } else if (delta < (24*60*60)) {
          relative = 'vor ungef&auml;hr ' + (parseInt(delta / 3600)).toString() + ' Stunden';
        } else {
          if (delta < (48*60*60)) {
            relative = 'gestern';
          } else {
            relative = 'vor ' + (parseInt(delta / 86400)).toString() + ' Tagen';
          }
        }
        
        return relative;
      }
      
      // formats links and at symbols and returns the formatted text
      function format(text) {
        return text
          .replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;\'">\:\s\<\>\)\]\!])/gi, function(m) {
              return '<a href="' + m + '">' + (m.length > 25 ? m.substr(0, 24) + '...' : m) + '</a>';
          })
          .replace(/\B@([_a-z0-9]+)/gi, '@<a href="http://twitter.com/$1">$1</a>');
      }
  
      response.each(function(tweet, index) {
        if (index > 3) {
          return;
        }
  
        $(this.twtUpdateList).insert(li.evaluate({
          formattedStatus: format(tweet.text),
          statusUrl: 'http://twitter.com/' + tweet.user.screen_name + '/status/' + tweet.id_str,
          relativeTime: relativize(tweet.created_at)
        }));
      }, this);
    }
  
  });
  

  // SharePopup stuff.
  PS.set('Page', {
    SharePopup: Class.create(PS.Popup, {
      initialize: function($super, anchor, name, url, params) {
        this.url_template = new Template(url);
        this.url = this.url_template.evaluate({
          url: location.href,
          encoded_url: encodeURIComponent(location.href),
          encoded_title: encodeURIComponent(document.title)
        });
        this.params = 'toolbar=no' + params.join(',');
        $super(anchor, name, this.url, params);
      }
    }),
    SharePopups: {
      facebook: {
        url_template_string: 'http://www.facebook.com/sharer.php?u=#{encoded_url}&t=#{encoded_title}',
        parameters: ['width=626', 'height=436']
      },
      delicious: {
        url_template_string: 'http://delicious.com/save?v=5&noui&jump=close&url=#{encoded_url}&title=#{encoded_title}',
        parameters: ['width=550', 'height=550']
      },
      misterwong: {
        url_template_string: 'http://www.mister-wong.de/index.php?action=addurl&bm_url=#{encoded_url}&bm_description=#{encoded_title}',
        parameters: ['width=800', 'height=750', 'scrollbars=yes']
      },
      linkarena: {
        url_template_string: 'http://linkarena.com/bookmarks/addlink/?url=#{url}',
        parameters: ['width=800', 'height=750', 'scrollbars=yes']
      },
      alltagz: {
        url_template_string: 'http://www.alltagz.de/bookmarks/?action=add&popup=1&address=#{encoded_url}&title=#{encoded_title}&description=#{encoded_title}',
        parameters: ['width=730', 'height=465', 'scrollbars=yes']
      },
      folkd: {
        url_template_string: 'http://www.folkd.com/submit/page/#{url}',
        parameters: ['width=800', 'height=600', 'scrollbars=yes']
      },
      twitter: {
        url_template_string: 'http://twitter.com/share?url=#{encoded_url}&via=phonostar',
        parameters: ['width=550', 'height=400', 'scrollbars=yes']
      },
      vznetzwerke: {
        url_template_string: 'http://www.studivz.net/Suggest/Selection/?u=#{encoded_url}&desc=#{encoded_title}&prov=phonostar.de',
        parameters: ['width=800', 'height=600', 'scrollbars=yes']
      }
    }
  });

  //TODO: move this to a proper space, perhaps.
  document.on('dom:loaded', function() {

    var skyscraper = $('skyscraper');
    if (!PS.Ads.wallpaper && skyscraper) {
      skyscraper.addClassName('fixed');
    }
    
    // Social teaser
    $$('.teaser.social').invoke('on', 'click', 'a[data-social-element]', function (e, el) {
    
      // get class name for social element
      var socialClassName = el.readAttribute('data-social-element'),
      
      // get footer link href + text
      link = {
        href: el.readAttribute('data-social-link'),
        text: el.readAttribute('data-social-link-text')
      },
  
      contentElement = this.down('.content .' + socialClassName),
      footerLink = this.down('.footer .middle a');
      
      // activate the social to be shown, deactivate all adjacent socials
      contentElement.addClassName('active')
        .adjacent('.social').invoke('removeClassName', 'active');

      // set nav active state
      this.down('.header ul').className = el.up().className;
      
      // Update footer link
      footerLink.href = link.href;
      footerLink.innerHTML = link.text;

      // prevent default
      e.stop();
    
    });
    
    // Share popups
    if (PS.Page.SharePopup && PS.Page.SharePopups) {
      $$('.share_link').findAll(function(elem) {
        //only available share popups
        return PS.Page.SharePopups[$w(elem.className)[1]];
      }).each(function(elem) {
        //(key)popup to open
        var popup = $w(elem.className)[1];
        new PS.Page.SharePopup(elem, popup, PS.Page.SharePopups[popup].url_template_string, PS.Page.SharePopups[popup].parameters);
      });
    }
    
  });

}



//TODO: check and rewrite the code below this line and expand it into a proper namespace

var ArraySubgenre = [];
var ArraySubgenreId = [];

//footer blaettern
function set_page_SuchboxBottom(wert, anz) {
  if (Prototype.Browser.IE) {
    $("Suchbox").DirektZuSeite.value=wert;
  	$("Suchbox").submit();
  } else {
    $("DirektZuSeite").innerHTML = "";
    for (j=1; j<=anz;j++) {
      if (j == wert) {
        $("DirektZuSeite").options[$("DirektZuSeite").options.length] = new Option(j,j);
        $("DirektZuSeite").options[$("DirektZuSeite").options.length-1].selected = true;
      } else
        $("DirektZuSeite").options[$("DirektZuSeite").options.length] = new Option(j,j);
    }
    $("Suchbox").submit();
  }
}

function ResetPages() {
  $("FormOff").value = "on";
  if (Prototype.Browser.IE) {
    $("Suchbox").DirektZuSeite.value=1;
  	$("Suchbox").submit();
  } else {
    $("DirektZuSeite").innerHTML = "";
    for (j=1; j<=anz;j++) {
      if (j == 1) {
        $("DirektZuSeite").options[$("DirektZuSeite").options.length] = new Option(j,j);
        $("DirektZuSeite").options[$("DirektZuSeite").options.length-1].selected = true;
      } else
        $("DirektZuSeite").options[$("DirektZuSeite").options.length] = new Option(j,j);
    }
    $("Suchbox").submit();
  }
}

function SucheNachStichwort(Stichwort) {
	$("TagCloudSuche").Stichwort.value=Stichwort;
	$("TagCloudSuche").submit();	
}

function redirectDEHome() {
	location.href = 'http://www.phonostar.de';		
}

function redirectCOMHome() {
	location.href = 'http://www.phonostar.com';			
}

function redirectListenLink(listenLink, lang) {
	var timeout = 5000;
	location.href = listenLink;
	if (lang == 0) {
		setTimeout(redirectDEHome, timeout);
	} else {
		setTimeout(redirectCOMHome, timeout);
	}
}

//IE Hovering:
function SubmitHover(that) {
  var browser = navigator.appVersion;
  if (-1 != browser.search(/MSIE 6.0+/)) {
    if (that.style.backgroundPosition != '50% bottom') {
      that.style.backgroundPosition = 'bottom';
    } else {
      that.style.backgroundPosition = 'top';
    }
  }
}

function ArraySubgenreAnlegen(Index) {
  if (!ArraySubgenre[Index]) {
    ArraySubgenre.push([]);
  }
}
function ArraySubgenreIdAnlegen(Index) {
  if (!ArraySubgenreId[Index]) {
    ArraySubgenreId.push([]);
  }
}
function ArraySubgenreFuellen(Index, Wert){
  if (!ArraySubgenre[Index]) {
    ArraySubgenre.push([]);
  }
  ArraySubgenre[Index].push(Wert);
}
function ArraySubgenreIdFuellen(Index,Wert) {
  if (!ArraySubgenreId[Index]) {
    ArraySubgenreId.push([]); 
  }
  ArraySubgenreId[Index].push(Wert);
}

function OnChangeGenre(Index) {
  if (0 == Index) {
    $("Subkategorie").disabled = true;
    $("Subkategorie").innerHTML = "";
    $("Subkategorie").options[$("Subkategorie").options.length] = new Option("Alle",Index);
  } else {
    $("Subkategorie").disabled = false;
    $("Subkategorie").innerHTML = "";
    $("Subkategorie").options[$("Subkategorie").options.length] = new Option("Alle",0);
    for (j = 0; j < ArraySubgenre[Index - 1].length; j++) {
      $("Subkategorie").options[$("Subkategorie").options.length] = new Option(ArraySubgenre[Index - 1][j], ArraySubgenreId[Index - 1][j]);
    }
  }
}

// Music-Shop
function query1(q) {
  var query = 'http://partners.webmasterplan.com/click.asp?ref=187531&site=1382&type=text&tnb=23&prd=yes&srchdesc=Y&itf=0&category0=&minprice=&maxprice=&query=' + q;
  window.open(query, 'Shop');
}
function query2(q) {
  var query = 'http://www.amazon.de/exec/obidos/external-search/028-4916816-8246143?keyword="+ q+"&index=blended&tag=wwwphonostade-21&tag-id=wwwphonostade-21&Los.x=15&Los.y=10';
  window.open(query, 'Shop');
}

// Bookmark:
function toggleBookmark() {
  var el = $('bookmark');
  Effect.toggle(el, 'appear', {duration: 0.3});
}

// Funktion für die Suche:
function toggleSearch() {
	var searchfield = $('SuchboxFilter'), button = $('ButtonFilter'), formState = $('FormOff');
	
  if (searchfield.style.display != 'none') {
		Effect.toggle(searchfield, 'blind', {duration: 0.8});
    button.className = 'FilterAus';
    formState.value  = 'on';
	} else {
    Effect.toggle(searchfield, 'appear', {duration: 0.5});
    button.className = '';
    formState.value  = '';
	}
}

// DisableBox
function DisableBox(IDname) {
  if ($(IDname)) {
    if ($(IDname + 'name')) {
      if ($(IDname).checked) {
        new Effect.Highlight($(IDname + 'name'), {
            duration: 0.2,
            startcolor: '#eeeeee',
            endcolor: '#f8f8f8',
            restorecolor: '#f8f8f8'
        });
        $(IDname + 'name').setStyle({
            border: '1px solid #666'
        });
        $(IDname + 'name').disabled = false;
        $(IDname + 'name').focus();
      } else {
        $(IDname + 'name').setStyle({
            backgroundColor: '#eee',
            border: '1px solid #ccc'
        });
        $(IDname + 'name').disabled = true;
      }
    }
  }
}
