var IE6 = (navigator.userAgent.indexOf("MSIE 6")>=0) ? true : false;

jQuery().ready(function()
{
  // slide down the additional header elements on language and login mouseover
  var headerOpenedBy;
  jQuery('.li-login a').click(function() {
    if(jQuery('.zl').is(":visible") && headerOpenedBy == this) { jQuery('.zl').slideUp(400); }
    else { jQuery('.zl').slideDown(400); headerOpenedBy = this; }
    jQuery(this).toggleClass('current');
    jQuery('.llogin').show();
    jQuery('.znav').hide();
    if(!IE6) jQuery('#passwd').prev('label').css({'opacity':'1'});
    return false;
  });
  jQuery('.li-lang a').click(function() {
    if(jQuery('.zl').is(":visible") && headerOpenedBy == this) { jQuery('.zl').slideUp(400); }
    else { jQuery('.zl').slideDown(400); headerOpenedBy = this; }
    jQuery(this).parent().find('li').removeClass('current');
    jQuery(this).toggleClass('current');
    jQuery('.llogin').hide();
    jQuery('.znav').show();
    return false;
  });
  jQuery('.li-login a').toggle(function(){}, function () {
    window.setTimeout(function() {
      jQuery('.lpw').css({'left': '660px','opacity':'0'});
      jQuery('.llog').css({'left': '0px','opacity':'1'});
    }, 400);
  });
  // header mouseout
  jQuery("#header").hoverIntent({ sensitivity:3, interval:200, over:function(){}, timeout:500, out:slideUpHeader });
  function slideUpHeader() { 
    jQuery('.zl').slideUp(400);
    jQuery('.li-login a').removeClass('current');
    jQuery('.li-lang a').removeClass('current');
    window.setTimeout(function() {
      jQuery('.lpw').css({'left': '660px','opacity':'0'});
      jQuery('.llog').css({'left': '0px','opacity':'1'});
    }, 400);
  }

  // password lost form handling
  jQuery('.vergessen').click(function() {
    jQuery('.llog').animate({'left': "-330px",'opacity':'0'}, 450, 'swing');
    jQuery('.llog').removeClass('selected');
    jQuery('.lpw').show().css({'left':'660px', 'opacity':'0'});
    jQuery('.lpw').animate({'left': "330px",'opacity':'1'}, 450, 'swing');
    window.setTimeout(function() {
      jQuery('#passwd').prev('label').css({'opacity':'0'});
    }, 200);
    return false;
  });

  if(!IE6){
  // remove password in-field label on focus or click
  jQuery('#passwd').prev('label').show().click(function() {
    jQuery('#passwd').focus().select();
    jQuery(this).hide();
  });
  jQuery('#passwd', this).focus(function() { 
    jQuery('#passwd').prev('label').hide(); 
  });
  }
  // header form fields default values handing
  jQuery('.llogin .text').click( function() {
    if(this.value == this.defaultValue) this.value = '';
   if(!IE6) if(this.id == 'passwd') jQuery(this).prev('label').hide();
  });
  jQuery('.llogin .text').blur(function() {
    if(this.value == '') {
      this.value = this.defaultValue;
     if(!IE6) if(this.id == 'passwd') jQuery(this).prev('label').show();
    }
  });


  jQuery('.icontent ol li').each(function(i, e) {
    jQuery(e).css('color', '#cccccc')
    jQuery(e).contents().wrap('<span></span>')
  })

  jQuery('#getpermalink').click(function() {
    jQuery(this).focus().select();
  });

});

/**
 * handles audioplayer embedding in preview mode
 * and all ajax calls
 * @return Void
 * 
 */  
VpsSamplePreview = function()
{
  var self = this;
  var data = '';
  var backup = '';
  var dataSelector = '';
  var hoverSelector = '';
  var parentSelector = '';

  this.init = function()
  {
    jQuery(self.hoverSelector).hover(
      // handle mouseover
      function() {
        // save content which will be replace by flash player
        self.backup = jQuery(this).find(self.parentSelector).html();
        // get sample data, convert string to json object
        self.data = eval("(" + jQuery(this).find(self.dataSelector).html() + ')');
        // construct objects for swfobject and embed flash player
        var vars = {  source: self.data.file, link: self.data.url, color: self.data.color, radius: "55", innerRadius: "27", 
            rollOverMode: "true", autoPlay: "true", autoRewind: "false", loop: "false" };
        var pars = { bgcolor: "#FFFFFF", wmode: "transparent", allowscriptaccess: "always" };
        var attr = { id: "flashplayer", name: "flashplayer" };
        // stop a big player running
        if(document.getElementById('big-flash-player')) document.getElementById('big-flash-player').pauseSample();
        swfobject.embedSWF("../swf/vpsaspplayer.swf", self.data.repid, "100%", "100%", "9", false, vars, pars, attr);
        // attach mouseout handler for flash container
        jQuery('#flashplayer').mouseout(function() { self.reset(jQuery(this).parent(self.parentSelector)) });
      },
      // handle mouseout
      function() { self.reset(jQuery(this).find(self.parentSelector)); }
    );

  }

  this.reset = function(selector)
  {
    jQuery(selector).parent().find(".favlink").hide();
    swfobject.removeSWF('flashplayer');
    jQuery(selector).html(self.backup); 
  }
}


/**
 * handles all sample search related js
 * maily setting filters, updating the url 
 * and all ajax calls
 * @return Void
 * 
 */  
VpsSampleSearch = function() 
{
  var self = this;
  this.params = { };
  this.url = "";
  this.mode = "sample";
  this.keyword = "";
  this.out = { };

  this.getParams = function()
  {
      return self.out;
  }
  // initialize, collect params, set event handler
  this.init = function(selector, param) 
  {
    self.params[param] = [];
    jQuery(selector).each(function(item) {
      this.param = param;
      this.value = jQuery(this).attr('href');
    });
    var out = {};    
    for (var i in self.params) if(self.params[i].length) out[i] = self.params[i].join("_"); 
    jQuery("#namesearch").setOptions({extraParams: out}).flushCache();

    jQuery(selector).click(function(item) 
    {
      // add/remove param to/from params array by clicked link 
      var arr = self.params[this.param];
      var pos = jQuery.inArray(this.value, arr);
      if(pos == -1) arr.push(this.value); 
      else arr.splice(pos, 1);
      // format output, concat param values by underscrore
      var out = {};
      for (var i in self.params) if(self.params[i].length) out[i] = self.params[i].join("_"); 
      // set address value with query params
      jQuery.address.value('/?' + jQuery.param(out));
      self.out = out;

      if(self.mode == 'speaker') {
        jQuery("#namesearch").setOptions({extraParams: out}).flushCache();
      }
      return false;
    });
  }

  // uddate link styles
  this.update = function()
  {
    // reset params and unset current class for all links
    for (var i in self.params) self.params[i] = [];
    jQuery('#filters li a').removeClass('current');
    // set current class for links from query string and save params
    jQuery.map(jQuery.address.parameterNames(), function(name, i) {
      var values = jQuery.address.parameter(name).split('_');
      self.params[name] = values;
      for (var j in values) jQuery('#'+name+'-filter li a[href='+values[j]+']').addClass('current');
    });
  }

  // perform ajax request
  this.search = function()
  {
    var query = '';
    if(self.mode == 'speaker') {
      var out = {};    
      for (var i in self.params) if(self.params[i].length) out[i] = self.params[i].join("_"); 
      jQuery("#namesearch").setOptions({extraParams: out}).flushCache();
      query = self.url+'?'+jQuery.address.queryString();
      if(self.keyword.length){
        query = query + '&keyword=' + self.keyword;
      }
    } else {
      query = self.url+'?'+jQuery.address.queryString();
    }

    jQuery.ajax({
      url: query,
      success: function (data, textStatus) { jQuery('#sample-update').html(data); self.update(); },
      beforeSend: function (XMLHttpRequest) {  },
      complete: function (XMLHttpRequest, textStatus) { }
    });
  }

}


/**
 * handles all watchlist related js
 * ajax calls, toolstips, button updates
 * @return Void
 * 
 */
VpsSampleWatchlist = function() 
{
  var self = this;
  this.addText = "";
  this.removeText = "";
  this.url = "";
  this.isWatchlist = false;

  this.init = function(selector) {
    jQuery('.fl .favlink').hide();
    jQuery('.fl').hover(
      function() { jQuery(this).parent().find(".favlink").show(); },
      function() { jQuery(this).parent().find(".favlink").hide(); }
    );
    jQuery(".favlink").each(function(item) {
      this.samplehash = jQuery(this).attr('name');
      this.remove = jQuery(this).hasClass('remove');
      var title = this.remove ? self.removeText : self.addText;
      jQuery(this).attr('title', title);
      // on detail page upate watchlist link on big sample
      if(jQuery(this).attr('id') == "detail-favlink") jQuery("#detail-favlink").html(title);
    });
    jQuery(".favlink").click(function() {
      self.search(this);
      return false;
    });
    jQuery(".fl .favlink").tooltip({tip:'#tooltip', effect:'slide', offset:[0, 3], predelay:200, relative:true});
  }

  this.search = function(link) {
    var action = link.remove ? 'remove' : 'add';
    jQuery.ajax({
      url: self.url+"/"+action+"/hash/"+link.samplehash,
      success: function (data, textStatus) { self.update(link, data); },
      beforeSend: function (XMLHttpRequest) { },
      complete: function (XMLHttpRequest, textStatus) { }
    });
  }

  this.update = function(link, count) {
    var helptext = (link.remove) ? self.addText : self.removeText;
    jQuery('span.list-count').html(count);
    jQuery(link).toggleClass('remove', !link.remove);
    // handle favlinks in boxes
    if(jQuery(link).data('tooltip')) {
      jQuery(link).data('tooltip').hide();
      jQuery(link).data('title', helptext);
      // on detail page handle favlink in big preview too
      if(jQuery(link).attr('href') == jQuery('#detail-favlink').attr('href')) {
        jQuery('#detail-favlink').html(helptext);
        jQuery('#detail-favlink').toggleClass('remove', !link.remove);
      }
    } 
    // handle favlink selected sample at detail page
    else jQuery(link).html(helptext);


    // toggle remove boolean
    link.remove = !link.remove;
    // we're at watchlist page, remove complete box
    if(self.isWatchlist) jQuery('#box-'+link.samplehash).fadeOut();
  }
}




/**
 *
 *  Base64 encode / decode
 *  http://www.webtoolkit.info/
 *
 */

var Base64 = {

  // private property
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

  // public method for encoding
  encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      output = output +
      this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
      this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
  },

  // public method for decoding
  decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

      enc1 = this._keyStr.indexOf(input.charAt(i++));
      enc2 = this._keyStr.indexOf(input.charAt(i++));
      enc3 = this._keyStr.indexOf(input.charAt(i++));
      enc4 = this._keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }

    }

    output = Base64._utf8_decode(output);

    return output;

  },

  // private method for UTF-8 encoding
  _utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  },

  // private method for UTF-8 decoding
  _utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

      c = utftext.charCodeAt(i);

      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }

    }

    return string;
  }

}



