/* requires the Yahoo! User Interface Library */
/*
  modules:
  1. WebPlayerButton - includes the play button for the webplayer
  2. ShowElements - displays hidden elements
  3. JAMBA.prelisten - prelistening of ringtones
  4. popuplink - this object detects links marked with class="popuplink"
  5. json.js
  6. window.onload - by Dean Edwards/Matthias Miller/John Resig
*/

/*
 * this script is searching for all elements with class name 'hide'
 * and set the style attribute 'visibility' to 'visible'.
*/

/* add the playbutton for the webplayer */
var runningplayerid = 0;
var wpwin = null;
function startPlayer(_t,docId,memberId){
  try {
    wpwin.setPlayList(_t,docId);
  }
  catch(e)
  {
    wpwin = window.open("/jcommunity-web/webPlayerSetData.go?t="+_t+"&docId=" + docId +"&member_id="+memberId,"jc20webPlayer","width=750,height=700,resizable");
  }
  wpwin.focus();
}

var ShowElements = {
  init: function()
  {
    var el = YAHOO.util.Dom.getElementsByClassName('hide');
    YAHOO.util.Dom.batch(el, this.show);
  },
  show: function(el)
  {
    YAHOO.util.Dom.removeClass(el, "hide");
  }
};

/* prelistening for ringtones */
var JAMBA = YAHOO;
  JAMBA.prelisten = function() {
  var $D = YAHOO.util.Dom;
  var $E = YAHOO.util.Event;
  var $C = YAHOO.util.Connect;
  var $ = $D.get;
  /* prelistening button */
  //var _BT_LISTEN  = "./img/icon_speaker.gif";
  var _BT_LISTEN  = "./img/icon_pre.gif";
  /* loading button */
  var _BT_LOADING = "./img/button_loading.gif";
  /* stop button */
  var _BT_STOP    = "./img/button_stop.gif";
  /* display the loading button in milli seconds */
  var _LOADING_DELAY = 1000;
  //var _PRELISTEN_TO = 15000;
  var _PRELISTEN_TO = 50000;
  return {
  	init : function() {
      /* get all prelistening buttons and set an onclick event */
      var playButtons = $D.getElementsByClassName('rPrelisten','a');
      this.addClickListener(playButtons);
  	},
    
    addClickListener: function(playButtons)
    {
      var len = playButtons.length;
      var listeners = "";
      for(i = 0; i< len; i++)
      {
        listeners = $E.getListeners(playButtons[i]);
        if (!listeners)
        {
          $E.addListener( playButtons[i], 'click', this.playSong);
        }
      }
  	},
    
    getFullPath: function(img)
    {
      var fullLoadingImgPath = "";
      if ( img && img != "undefinied" && img.getAttribute("src") != "" )
      {
        fullLoadingImgPath = img.getAttribute('src');
        fullLoadingImgPath = fullLoadingImgPath.substring( fullLoadingImgPath.indexOf("/s/"), fullLoadingImgPath.length );
      }
      return fullLoadingImgPath;
    },
    
    /* onclick event function playSongs  */
    playSong: function(e)
    {
      $E.stopEvent(e);
      var el = $E.getTarget(e);
      
      var fullLoadingImgPath = JAMBA.prelisten.getFullPath( JAMBA.prelisten.cachedImg );
      if ( $D.inDocument('rPlayer') || fullLoadingImgPath == _BT_LOADING )
      {
        /* alert("JAMBA.prelisten.cachedImg.getAttribute('src'): " + JAMBA.prelisten.cachedImg.getAttribute('src')); */
        JAMBA.prelisten.stopPlaying();
        var cachedEl = JAMBA.prelisten.el;
        var cachedImg = JAMBA.prelisten.cachedImg;
        cachedImg.src = _BT_LISTEN;
        
        /* remove the setListenButton() timeout */
        window.clearTimeout(JAMBA.prelisten.setTO);
        $E.removeListener( cachedEl, 'click', JAMBA.prelisten.stop);
        $E.addListener( cachedEl, 'click', JAMBA.prelisten.playSong);
      }
      
      /* get the a element */
      while ( el.nodeName.toLowerCase() != "a" && el.nodeName.toLowerCase() != "body" )
      {
        el = el.parentNode;
      }
      JAMBA.prelisten.el = el;
      
      /* remove the onclick event from the clicked element */
      $E.removeListener( el, 'click', JAMBA.prelisten.playSong);
      /* ad the new onclick event listener */
      $E.addListener( el, 'click', JAMBA.prelisten.stop);
      
      var body = document.getElementsByTagName('body')[0];
      /*
      check if already a rPlayer-div is available in this page, if so -> stop the music, 
      delete the box and change the event listener
      */
      
      
      var img = el.firstChild;
      /* get the image element */
      while ( img.nodeName.toLowerCase() != "img" )
      {
        img = img.nextSibling;
      }
      
      /* remove the onclick event */
      $E.removeListener( el, 'click', JAMBA.prelisten.playSong);
      /* display the loading button */
      JAMBA.prelisten.setLoadingButton(img);
      
      var buildHtml =
      {
        success: function(dom)
        {
	var playerHTMLmp3 = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="1" height="1" id="prelistenflash" align="middle">' +
			'<param name="allowScriptAccess" value="sameDomain" />' +
			'<param name="movie" value="./img/prelisten.swf" />' +
			'<param name="loop" value="false" />' +
			'<param name="menu" value="false" />' +
			'<param name="AutoStart" value="true" />' +
			'<param name="quality" value="low" />' +
			'<param name="flashvars" value="key=test&file=@@REP-file@@"/>' +
			'<embed src="./img/prelisten.swf" flashvars="key=test&file=@@REP-file@@" loop="false" menu="false" quality="low" wmode="transparent" width="1" height="1" name="prelisten" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />' +
			'</object>';
	  var playerHTMLmid = '<embed name="prelisten" id="prelistenflash" src="/previewdata.do?f=@@REP-file@@&k=test&rand=undefined" hidden=true loop=true autostart=true>';
	  var playerHTMLmidabslink = '<embed name="prelisten" id="prelistenflash" src="@@REP-file@@" hidden=true loop=true autostart=true>';
	  var playerHTMLmidabslink = '<OBJECT ID="prelistenflash" WIDTH=0 HEIGHT=0 classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" CODEBASE="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject"><PARAM NAME="FileName" VALUE="@@REP-file@@"><param name="uiMode" value="mini"><param name="Volume" value="-15"><Embed type="application/x-mplayer2" pluginspage="http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=Media&sba=Plugin&" src="@@REP-file@@" ShowControls=0 ShowDisplay=0 ShowStatusBar=0 width=0 height=0></embed></OBJECT>';

          var prelistenData = dom.responseText;
//	  var re = new RegExp(/mid$/);
//	  var m = re.exec(prelistenData);
//          if (m == null) {
//    		var playerHTML = playerHTMLmp3;
//	  } else {
//    		var playerHTML = playerHTMLmid;
//          }
	  var re = new RegExp(/^http/);
	  var m = re.exec(prelistenData);
          if (m == null) {
    		var playerHTML = playerHTMLmid;
	  } else {
    		var playerHTML = playerHTMLmidabslink;
          }
         // var body = document.getElementsByTagName('div')[0];
      	  var body = document.getElementById('playerbox'+el.rel);
	  runningplayerid = el.rel;
//	  var prelistenBox = document.getElementById("rPlayer");
          var prelistenBox = document.createElement("div");
          prelistenBox.id = "rPlayer";
          prelistenBox.position = 'absolute';
          prelistenBox.Xposition = 'absolute';
          body.appendChild(prelistenBox);
          var myHtml = playerHTML.replace(/\@\@REP-file\@\@/, prelistenData);
          var myHtml2 = myHtml.replace(/\@\@REP-file\@\@/, prelistenData);
          prelistenBox.innerHTML = myHtml2;
//alert(myHtml2);
          JAMBA.prelisten.setStopButton();
        },
        
        failure: function()
        {
          var fullLoadingImgPath = JAMBA.prelisten.getFullPath( JAMBA.prelisten.cachedImg );
          if ( fullLoadingImgPath == _BT_LOADING )
          {
            JAMBA.prelisten.stopPlaying();
            var cachedEl = JAMBA.prelisten.el;
            var cachedImg = JAMBA.prelisten.cachedImg;
            cachedImg.src = _BT_LISTEN;
            /* remove the setListenButton() timeout */
            window.clearTimeout(JAMBA.prelisten.setTO);
            $E.removeListener( cachedEl, 'click', JAMBA.prelisten.stop);
            $E.addListener( cachedEl, 'click', JAMBA.prelisten.playSong);
          }
        }
      }
      
      var prelUrl = "?action=prelisten&itemid="+el.rel;
      $C.initHeader("X-Requested-With", "XMLHttpRequest");
      var connectionObject = $C.asyncRequest('GET', prelUrl, buildHtml);
    },
    
    /* set the loading button */
    setLoadingButton: function(img)
    {
      /* cache the img element */
      JAMBA.prelisten.cachedImg = img;
      /* set the img src-attribute with the new image */
      img.src = _BT_LOADING;
      /* set a timeout, after the timeout the setStopButton() funtion will be called */
    },
    
    /* set the stop button */
    setStopButton: function()
    {
      /* get the cached img element */
      var img = JAMBA.prelisten.cachedImg;
      var el = JAMBA.prelisten.el;
      /* set the img src-attribute with the new image */
      img.src = _BT_STOP;
      JAMBA.prelisten.setTO = window.setTimeout("JAMBA.prelisten.setListenButton()", _PRELISTEN_TO);
    },
    setListenButton: function()
    {
      var img = JAMBA.prelisten.cachedImg;
      var el = JAMBA.prelisten.el;
      img.src = _BT_LISTEN;
      var cachedEl = JAMBA.prelisten.el;
      $E.removeListener( cachedEl, 'click', JAMBA.prelisten.stop);
      $E.addListener( cachedEl, 'click', JAMBA.prelisten.playSong);
      JAMBA.prelisten.stopPlaying();
    },
    
    /* get the clicked element and replace the onclick event listener */
    stop: function(e)
    {
      $E.stopEvent(e);
      var el = $E.getTarget(e);
      while ( el.nodeName.toLowerCase() != "a" && el.nodeName.toLowerCase() != "body" )
      {
        el = el.parentNode;
      }
      var img = el.firstChild;
      while ( img.nodeName.toLowerCase() != "img" )
      {
        img = img.nextSibling;
      }
      
      /* remove the setListenButton() timeout */
      window.clearTimeout(JAMBA.prelisten.setTO);
      
      /* remove the stop onclick event listener and a new onclick listener for playSong */
      $E.removeListener( el, 'click', JAMBA.prelisten.stop);
      $E.addListener( el, 'click', JAMBA.prelisten.playSong);
      
      /* call the stopPlaying function */
      JAMBA.prelisten.stopPlaying();
      /* set the prelistening button */
      img.src = _BT_LISTEN;
    },
    
    /* stopped the playing music */
    stopPlaying: function( )
    {
      var body = document.getElementById('playerbox'+runningplayerid);
//      var body = document.getElementsByTagName('div')[0];
      if ( $D.inDocument('rPlayer') )
      {
        var prelistenBox = $('rPlayer');
//	var prelistenBox = document.getElementById("rPlayer");
        var prelistenFlash = $('prelistenflash');
//	prelistenBox.innerHTML = '';
        prelistenBox.removeChild(prelistenFlash);
        body.removeChild(prelistenBox);
      }
    }

  };
}();
/* end prelistening for ringtones */

/* the object popupLink handles all popup links of the page */

var popupLink = {

addEvent: function(elm, evType, fn, useCapture)
{
  if (elm.addEventListener)
  {
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent)
  {
    var r = elm.attachEvent('on' + evType, fn);
  } else
  {
    elm['on' + evType] = fn;
  }
},

winPopup: function(popupUrl, wName, popupPar)
{
  if ( popupUrl != '' && wName != '' )
  {
    try
    {
      window.open(popupUrl, '' + wName + '', '' + popupPar + '');
      return true;
    } catch(e)
    {
      window.open(popupUrl, 'popupWin', '' + popupPar + '');
      return true;
    }
  } else
  {
    window.open(popupUrl);
    return true;
  }
  return false;
},

handleLink: function(e) 
{
  /* hack for beta.jamba.de - no prelistening! */
  /* return false; */
  
  var el;
  el = window.event && window.event.srcElement ? window.event.srcElement : e && e.target ? e.target : false;
  if (!el)
    return;
  
  while(el != document.body && el.nodeName.toLowerCase() != 'a' )
    el = el.parentNode;
  
  if(el.nodeName.toLowerCase() != 'a')
    return null;
  
  isPopup = false;
  
  if (el.target && el.target != '' && el.href)
  {
    var wName = el.target.indexOf("_") != -1 ? el.target.substring(0, el.target.indexOf("_")) : "popupWin";
    var pWidth = el.target.indexOf("_") != -1 && el.target.indexOf("x") != -1 ? el.target.substring(el.target.indexOf("_")+1, el.target.indexOf("x")) : "600";
    var pHeight = el.target.indexOf("x") != -1 ? el.target.substring(el.target.indexOf("x")+1, el.target.length) : "400";
    
    var popupPar = 'width=' + pWidth + ',height=' + pHeight + ',top=0,left=0,resizable=no,scrollbars=yes,menubar=no,toolbar=no,status=no,location=no';
    
    if ( popupLink.winPopup(el.href, wName, popupPar) )
    {
      isPopup = true;
    }

  } else if (el.href)
  {
    if ( popupLink.winPopup(el.href, '', '') )
    {
      isPopup = true;
    }
  }
  if ( isPopup )
  {
    if (window.event)
    {
      window.event.cancleBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.stopPropagation && e.preventDefault)
    {
      e.stopPropagation();
      e.preventDefault();
    }
  }
},

cancelClickSafari: function()
{
  return false;
},

init: function()
{
  if (!document.getElementsByTagName)
    return;
  var all_popuplinks = document.getElementsByTagName('a');
  for (var i = 0; i < all_popuplinks.length; i++)
  {
    var plink = all_popuplinks[i];
    // set an aventListener only if the css class name 'popuplink' will be found
    if ( plink.className && (' ' + plink.className + ' ').indexOf(' popuplink ') != -1 )
    {
      popupLink.addEvent(plink, 'click', popupLink.handleLink, false);
      plink.onclick = popupLink.cancelClickSafari;
      if ( !plink.title && plink.firstChild && plink.firstChild.nodeValue )
        plink.title = plink.firstChild.nodeValue;
    }
  }
}

};
/* end popuplink */



/* window.onload */
// Dean Edwards/Matthias Miller/John Resig
function init() {
    // quit if this function has already been called
    if (arguments.callee.done) return;

    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;

    // kill the timer
    if (_timer) {
        clearInterval(_timer);
        _timer = null;
    }

    try {
      MusicMgr.playing.init();
    } catch(e){}
    try {
      JAMBA.search.init();
    } catch(e){}
    try {
      JAMBA.prelisten.init();
    } catch(e){}
	  try {
      JAMBA.inputFocus.init();
    } catch(e){}
    try {
      ShowElements.init();
    } catch(e){}
    try {
      MoreMgr.options.init();
    } catch(e){}
    try {
      WebPlayButton.init();
    } catch(e){}
    try {
      popupLink.init();
    } catch(e){}
    try {
      JAMBA.postmsisdnandtext.init();
    } catch(e){}
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, null);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = init;
/* end window.onload */
