var containerwindowname = "_displaywindow_";
var widgetwindowname    = "_widgetwindow_";

var DisplayWindow = new Class({
  initialize:
  function(options){
      document.write('<div id="'+containerwindowname +'"></div>');
      this.container = $(containerwindowname);
      this.container.setStyle('display', 'none');
      this.isopen = false;
      this.isloaded = false;
      this.flashWidgetMap = new Map();
      var ajax = new Ajax( this.load, ajaxError, this );
      var uri = "/flash/listflashwidget!ajax.action?" + generateLine() + "=0";
      ajax.get( uri, null, false );
  },
  load:
  function( obj, jsont ){
      var thisclass = obj.getParams();
      var json = eval( '(' + jsont + ')' );
      if(json.status != 'failure'){
          for(var a = 0; json.FlashWidgetList != null && a < json.FlashWidgetList.length; a++){
              thisclass.flashWidgetMap.put( "W"+json.FlashWidgetList[a].id,
                                            json.FlashWidgetList[a] );
          }
          thisclass.isloaded = true;
      }else{
          dialogAlert(json.errorMessage);
      }
  },
  view:
  function( id ){
      this.open( id, 'flash' );
      var flashdiv = document.createElement('div');
      flashdiv.setAttribute("id", widgetwindowname);
      flashdiv.style.textAlign = "center";
      this.container.appendChild( flashdiv );
      var widgetcodediv = document.createElement('div');
      widgetcodediv.setAttribute("id", "code"+widgetwindowname);
      flashdiv.appendChild( widgetcodediv );
       
      var style = 'color:#FFF;text-decoration:none;font-size:12pt;font-weight:bold';
      var onclick_share = 'widgetwindow.share(\''+id+'\');return false;';
      var _share = '<a href="#" style="'+style+'" onclick="'+onclick_share+'">Share</a>&nbsp;&nbsp;&nbsp;'+
                   '<a style="'+style+'" href="/widget/'+id+'">Create</a>';
      var sharediv = document.createElement('div');
      sharediv.style.textAlign = "center";
      sharediv.innerHTML = _share;
      this.container.appendChild( sharediv );

      var flashwidget = this.flashWidgetMap.get( "W"+id );
      var flashvars = {};
      var params = { wmode: "transparent", allowScriptAccess:"always", quality:"high" };
      var attributes = { id: flashwidget.name, name: flashwidget.name };
      swfobject.embedSWF( flashwidget.url + "?" + flashwidget.querystring, "code"+widgetwindowname, flashwidget.width, flashwidget.height, "8.0.0", statichost + "/swf/expressInstall.swf", flashvars, params, attributes);


      if( id == 11 ){
         var html = ''+
              '<a target="_blank" alt="myspace music flash player playlist"'+
              'href="/community/showlove.jsp?flashId=FIG3OQUIZP0EQOBQKP">'+
              '<img src="'+statichost+'/images/widgets/post_showlove.gif"></a>'+
              '<br><a target="_blank" alt="myspace music flash player playlist" href="http://www.flashwidgetz.com">'+
              '<img src="'+statichost+'/images/widgets/create_showlove.gif"></a><br><br>';
         var _extradiv = document.createElement('div');
         _extradiv.innerHTML = html;
         $(widgetwindowname).appendChild(_extradiv);
      }

  },
  share:
  function( id ){
    this.open( id, 'share' );

    var s = '<form name="referwidget" onsubmit="referFriend(this);return false;">'+
            '<input type="hidden" name="widgetId" value="' + id + '">'+
            '<span style="font-size:10pt;font-weight:bold;color:#FFF">Tell your friends about this widget</span>'+
            '<p/>'+
            '<div id="refercontainerdiv" style="height:205px;">'+
            '  <div id="referinput">'+
            '    <span style="font-size:10pt;color:#FFF;">Enter your friend(s) email address(es)</span><br>'+
            '    <span style="font-size:8pt;color:#FFF;">seperate email addresses by comma (,)</span><br>'+
            '    <textarea name="emails" style="width:380px;height:50px"></textarea><br>'+
            '    <input type="Submit" value="Submit">'+
            '  </div>'+
            '  <div id="refererror" style="display:none;width:240px"></div>'+
            '  <div id="referconfirm" style="display:none;width:240px"></div>'+
            '</div>'+
            '<p/>'+
            '</form>';

      var textdiv = document.createElement('div');
      this.container.appendChild( textdiv );
      $(textdiv).setStyle('text-align', 'left');
      textdiv.innerHTML = s;

      referwindow = new ReferWindow();
  },
  open:
  function( id, kind ){
      if( $(widgetwindowname) ){
          $(widgetwindowname).innerHTML = "";
      }
      while(this.container.firstChild)
          this.container.removeChild(this.container.firstChild);


      var actions = document.createElement('div');
      var onclick_view = 'widgetwindow.view(\''+id+'\');return false;';
      var onclick_share = 'widgetwindow.share(\''+id+'\');return false;';
      var onclick_close = 'widgetwindow.close();return false;';

      var style = 'color:#FFF;text-decoration:none';
      var s = '<table width="100%"><tr><td align="left">';
      if(kind == 'share'){
   	    s += '  <a href="." style="'+style+'" onclick="'+onclick_view+'">Preview</a>';
      }  

      s+=     '</td><td align="right">'+
              '  <div align="right">'+
              '  <a href="." style="'+style+'" onclick="'+onclick_close+'">Close</a>'+
              '</td></tr></table><br>';
      actions.innerHTML = s;
      this.container.appendChild( actions );
      var width, height;
      if(kind == 'flash'){
          var flashwidget = this.flashWidgetMap.get( "W"+id );
          width = flashwidget.width + 60;
          height = flashwidget.height + 80;
      }else if(kind == 'share'){
          width = 400;
          height = 190;
      }
      if(width < 200) width = 200 + 60;
      if(height < 100) height = 100 + 80;
      if( id == 11 ) height += 40;
      var center = browser.getAdjustedCenter();
      var cy = center.y;
      var cx = center.x;

      var left = cx - (width/2);
      var top = cy - (height/2);
      if(this.isopen == true) {
          var styles = new Fx.Morph( containerwindowname );
          var ctop = parseInt(this.container.getStyle('top'));
          var cleft = parseInt(this.container.getStyle('left'));
          var cwidth = parseInt(this.container.getStyle('width'));
          var cheight = parseInt(this.container.getStyle('height'));
          styles.start({
              'top':[ctop,top],
              'left':[cleft,left],
              'width':[cwidth,width],
              'height':[cheight,height]
          });
          return;
      }
      this.container.setStyle('position', 'absolute');
      this.container.setStyle('background-color', '#222222');
      this.container.setStyle('display', 'inline');
      this.container.setStyle('border', '1px solid #FFF');
      this.container.setStyle('z-index', '100');
      this.container.setStyle('padding', '20px');
      this.container.setStyle('left', left+'px')
      this.container.setStyle('width', width+'px');
      this.container.setStyle('height', height+'px');
      this.container.setStyle('top', '-800px');
      this.container.setStyle('text-align', 'center');
      $(containerwindowname).setStyle('opacity', 1 );   
      $(containerwindowname).setStyle('top', top);
   
      //new Fx.Morph( containerwindowname, { duration: 1500, transition: Fx.Transitions.Elastic.easeOut} ).start({'top':[-1*width, top]});
      //new Fx.Morph( containerwindowname, { duration: 1000, transition: Fx.Transitions.Quart.easeInOut} ).start({'opacity':[.5,.99]});
      this.isopen = true;
  },
  close:
  function(){
      if(this.isopen == false) return;
      var fx = new Fx.Morph( containerwindowname, { duration: 1000, transition: Fx.Transitions.Quart.easeInOut} );
      fx.start( {'opacity':[.95,.2]} );
      var width = parseInt(this.container.getStyle('width'));
      var top = parseInt(this.container.getStyle('top'));
      var me = this;
      new Fx.Morph( containerwindowname, {
              onComplete: function(){
                  $(containerwindowname).setStyle('display', 'none');
                  $(containerwindowname).setStyle('opacity', 1);
                  me.isopen = false;
                  if( $(widgetwindowname) ){
                      $(widgetwindowname).innerHTML = "";
                  }
                  while($(containerwindowname).firstChild){
                      $(containerwindowname).removeChild($(containerwindowname).firstChild);
                  }
              },  
              duration: 1000, transition: Fx.Transitions.Back.easeInOut} ).start({'top':[top,-1*width]});
     }
});

var widgetwindow = new DisplayWindow();
var referwindow;

var ReferWindow = new Class({
        initialize: function(options){
            this.container = document.getElementById('refercontainerdiv');
            this.input = document.getElementById('referinput');
            this.error = document.getElementById('refererror');
            this.confirm = document.getElementById('referconfirm');
            this.current = this.input;
        },
        showerror: function(errorMessage){
            var html = "<span style='color:red;font-weight:bold'>"+ 
                       "Error: " + errorMessage + "</span><br><br>" +
                       "<input type='button' value='"+ getText("widgets_retry")+"' onclick='referwindow.showinput()'>";
            this.error.innerHTML = html;
            this.fadeoutin(this.current, this.error);
        },
        showconfirmation: function(confirmMessage){
            var html = "<span style='color:#0F0;font-weight:bold'>"+ confirmMessage + "</span><p/>"+
               "<input type='button' value='"+getText("widgets_sendtofriends")+"' onclick='referwindow.showinput()'>";
            this.confirm.innerHTML = html;
            this.fadeoutin(this.current, this.confirm);
        },
        showinput: function(){            
            this.fadeoutin(this.current, this.input);
        },
        fadeoutin: function(outdiv, indiv){
            if( this.current == indiv ) return;

            var fx_out = new Fx.Morph( $(outdiv), {duration: 250, transition: Fx.Transitions.linear} );
            var fx_in = new Fx.Morph( $(indiv), {duration: 250, transition: Fx.Transitions.linear} );

            $(outdiv).setStyle('opacity', '1');
            fx_out.start({ opacity:0 }).chain( 
                                          function(){ 
                                              $(outdiv).setStyle('display','none');
                                              $(indiv).setStyle('opacity', 0);
                                              $(indiv).setStyle('display','inline');
                                              fx_in.start({ opacity:1 });
                                          });
            this.current = indiv;
        }
});

function referFriend(form){
    var emails = form.emails.value;
    var widgetId = form.widgetId.value;
    var ajax = new Ajax( referFriendHandler, ajaxError, form );
    var uri = "/flash/referwidget!ajax.action?emails=" + emails + "&widgetId=" + widgetId + "&" + generateLine() + "=0";
    ajax.get( uri, null, false );  
}

function referFriendHandler(obj, jsont ){
    var json = eval( '(' + jsont + ')' );
    if(json.status != 'failure'){
        referwindow.showconfirmation( getText("widgets_emailsuccessful" ) );
        obj.getParams().emails.value = "";
    }else{
        referwindow.showerror( json.errorMessage );
    }
}

Cookie.dispose('flashcookie',  { domain: '.flashwidgetz.com', path: '/'} ); 