
/****************************************************
* Bootloaders
*****************************************************/
var loadinterval = -1;
var FLASHURL = "";
var FLASHWIDTH = 0;
var FLASHHEIGHT = 0;
// var FLASHQS  "";

$(document).addEvent( 'mousemove', function(event) { _mousex = event.page.x; _mousey = event.page.y; } );

function checksessionplaylist(){
  if( $('playlist_container') == null ) return;
  var playlistArray = sessionplaylist_getplaylist();
  if( playlistArray == null || playlistArray.length == 0 || playlistArray[0].songs == null || playlistArray[0].songs.length == 0 ){
    return false;
  }else{
    writeplaylist( playlistArray[0] );
  }
}

function loadPipes(){
  var flashvars = {};
  var params = { wmode: "transparent", allowScriptAccess:"always" };
  attributes = { id: "yahoopipes1", name: "yahoopipes1" }
  swfobject.embedSWF( statichost + "/swf/YahooPipes.swf", "yahoopipes", "1", "1", "9.0.0", null, flashvars, params, attributes);
}

function initsearchoptions(){
  var cookie = new Hash.Cookie('searchoptions_flash');
  var searchtype =  cookie.get('searchtype');

  $$('.search-option').each( function( el ){
    el.addEvent( 'click', function(){
      selectsearchoption( this );
    });
    if( searchtype == 'mp3' && el.get('title') == 'MP3' ){
      selectsearchoption( el );
    }else if( searchtype == 'video' && el.get('title') == 'Video' ){
      selectsearchoption( el );
    }
  });
}

function loadplayer( url, width, height, followup ){
  FLASHURL = url;
  FLASHWIDTH = width;
  FLASHHEIGHT = height;
  var flashvars = {};
  var params = { wmode: "transparent", allowScriptAccess:"always" };
  var attributes = { id: "flashwidget", name: "flashwidget" };
  swfobject.embedSWF( url , "widgetcode", width, height, "8.0.0", null, flashvars, params, attributes);  
  if( followup == null || followup == true ){
    loadinterval = setInterval( "continueloading()", 1000 );
  }
}

function continueloading(){
  if( $('flashwidget') == null ) return;
  try{ $('flashwidget').SetVariable('a', 'a'); }catch(e){ return false; }
  clearInterval( loadinterval );

  initColorChooser();
  pMenu.load();
  (function(){ pMenu.saveplayer(); }).periodical(5000);
}

function clearflashcookie(){
  Cookie.dispose('nflashcookie', { domain: domainName, path: '/'} ); return;
}


/****************************************************
* FlashProcessMenu.js
*****************************************************/
var block_color_load = false;

var FlashProcessMenu = new Class({
  initialize: function(){
    this.currentview = 'player';
    this.mainform = document.createflashinstance;
    this.widgetId = this.mainform.widgetId.value;
    this.instance = false;
    if( this.mainform.instanceId != null ) this.instance = true;

    this.formelements = new Object(); 
    this.formelements.autoplay  = $('_autoplay');
    this.formelements.shuffle   = $('_shuffle');
    this.formelements.showvideo = $('_showvideo');
    this.formelements.showloveheader = $('_showloveheader');
    this.formelements.designerpattern = $('_designerpattern'); 
    this.formelements.playlist  = $('_playlist');
    this.formelements.myspaceusername = $('_myspaceusername');
  }, 
  load: function(){
    this.loadplayer(); 
    this.loadmusic();

    if( this.instance ) return;
    var flashcookie = new Hash.Cookie('nflashcookie', { domain: domainName, path: '/'} );
    var dosave = flashcookie.get( 'dosave' );
    if( dosave == 'true' ){       
      if( this.verifysave() ){
        this.submit();
      }
    }
  },
  click: function( value ){
    if( this.currentview == 'player' ){
      this.saveplayer();
    }
    if( value == 'save' ){
      if( this.verifysave() == false ) return;
      this.showsaveoptions();
    }

    $( this.currentview + 'view' ).setStyle('display', 'none');   
    $( value + 'view' ).setStyle('display', 'block');
    this.currentview = value;
    $$('#configure-tab-table .button').each( function(el){
      el.removeClass('sel');
    });
    $('b_'+value).addClass('sel');
  },
  saveplayer: function(){
    if( this.instance ) return;

    var flashcookie = new Hash.Cookie('nflashcookie', { domain: domainName, path: '/'} );
    flashcookie.set( "widgetId", this.mainform.widgetId.value );
    if( this.mainform.autoplay != null ){  flashcookie.set( "autoplay", this.mainform.autoplay.value ); }
    if( this.mainform.shuffle != null ){ flashcookie.set( "shuffle", this.mainform.shuffle.value ); }
    if( this.mainform.color1 != null ){ flashcookie.set( "color1", this.mainform.color1.value ); }
    if( this.mainform.color2 != null ){ flashcookie.set( "color2", this.mainform.color2.value ); }
    if( this.mainform.color3 != null ){ flashcookie.set( "color3", this.mainform.color3.value ); }
    if( this.mainform.color4 != null ){ flashcookie.set( "color4", this.mainform.color4.value ); }
    if( this.mainform.showloveheader != null ){ flashcookie.set( "showloveheader", this.mainform.showloveheader.value ); }
    if( this.mainform.designerpattern != null ){ flashcookie.set( "designerpattern", this.mainform.designerpattern.value ); }
    if( this.mainform.showvideo != null ){  flashcookie.set( "showvideo", this.mainform.showvideo.value ); }
    if( this.mainform.myspaceusername != null ){ flashcookie.set( "myspaceusername", this.mainform.myspaceusername.value ); }
  },
  savemusic: function(){
    if( this.instance ) return;

    var flashcookie = new Hash.Cookie('nflashcookie', { domain: domainName, path: '/'} );
    flashcookie.set( "widgetId", this.mainform.widgetId.value );
    if( this.mainform.playlist != null ){
      flashcookie.set( "playlist", this.mainform.playlist.value );
      flashcookie.set( "playlistname", this.mainform.playlistname.value );
      flashcookie.set( "playlistnumber", this.mainform.playlistnumber.value );
    }
  },
  loadmusic: function(){
    if( this.instance ){

      if( this.mainform.playlistnumber != null ){
        var list = $('op2_playlistname');
        var item = null;
        for( var a = 0; a < list.length; a++ ){
           if( list[a].value == this.mainform.playlistnumber.value ){
             list[a].selected = true; item = list[a];
           }
        }
        this.mainform.playlistname.value = item.text;       
        loadplaylist( this.mainform.playlistnumber.value );
      }
    }else{
      var flashcookie = new Hash.Cookie('nflashcookie', { domain: domainName, path: '/'} );
      if( flashcookie == null ) return;
      if( flashcookie.get( "widgetId" ) == null || flashcookie.get( "widgetId" ) != this.mainform.widgetId.value ){
        Cookie.dispose('nflashcookie', { domain: domainName, path: '/'} ); return;
      }
      if( this.mainform.playlist != null && flashcookie.get( "playlist" ) != null ){
        this.mainform.playlist.value = flashcookie.get( "playlist" );
      }
      if( this.mainform.playlistname != null && flashcookie.get( "playlistname" ) != null ){
        this.mainform.playlistname.value = flashcookie.get( "playlistname" );
      }
      if( this.mainform.playlistnumber != null && flashcookie.get( "playlistnumber" ) != null ){
        this.mainform.playlistnumber.value = flashcookie.get( "playlistnumber" );
      }
      if( loggedIn ){
        if( flashcookie.get( "playlistnumber" ) == 0 && $('op1_playlistname') != null ){
          $('op1_playlistname').value = flashcookie.get( "playlistname" );
          loadplaylist( flashcookie.get( "playlistnumber" ) );
        }
        else if( flashcookie.get( "playlistnumber" ) > 0 && $('op2_playlistname') != null ){
          $('op1_playlistname').value = "";
          var list = $('op2_playlistname');      
          for( var a = 0; a < list.length; a++ ){
            if( list[a].value == flashcookie.get( "playlistnumber" ) ) list[a].selected = true; 
          }
          loadplaylist( flashcookie.get( "playlistnumber" ) );
        }
      }else{
        if( flashcookie.get( "playlistnumber" ) != null && flashcookie.get( "playlistnumber" ) == 0 ){
          loadplaylist( 0 );
        }else if( flashcookie.get( "playlistnumber" ) != null && flashcookie.get( "playlistnumber" ) > 0 ){
          flashcookie.set( "playlistnumber", null );
          dialogAlert(getText("flash_js_SorryLoggedOut")); return false;
        }
      }
    }
  },
  loadplayer: function(){
    if( this.instance ){
      if( this.mainform.autoplay != null ){
        var list = this.formelements.autoplay.autoplay;
        for( var a = 0; a < list.length; a++ ){
          if( list[a].value == this.mainform.autoplay.value ) list[a].checked = true;
        }
      }
      if( this.mainform.shuffle != null ){
        var list = this.formelements.shuffle.shuffle;
        for( var a = 0; a < list.length; a++ ){
          if( list[a].value == this.mainform.shuffle.value ) list[a].checked = true;
        }
      }
      if( this.mainform.showvideo != null ){
        var list = this.formelements.showvideo.showvideo;
        for( var a = 0; a < list.length; a++ ){
          if( list[a].value == this.mainform.showvideo.value ) list[a].checked = true;
        }
      }
      if( this.mainform.designerpattern != null ){
        var options = this.formelements.designerpattern.designerpattern.options;
        for( var a = 0; a < options.length; a++ ){
          if( options[a].value == this.mainform.designerpattern.value ) options[a].selected = true;
        }
      }
      if( this.mainform.showloveheader != null ){
        this.formelements.showloveheader.header.value = this.mainform.showloveheader.value;
        setShowLoveHeader( this.mainform.showloveheader.value , true );
      }
      if( this.mainform.myspaceusername != null ){
        this.formelements.myspaceusername.myspaceusername.value = this.mainform.myspaceusername.value;
      }
    }else{
      var flashcookie = new Hash.Cookie('nflashcookie', { domain: domainName, path: '/'} );
      if( flashcookie == null ) return;
      if( flashcookie.get( "widgetId" ) == null || flashcookie.get( "widgetId" ) != this.mainform.widgetId.value ){
        Cookie.dispose('nflashcookie', { domain: domainName, path: '/'} ); return;
      }
      if( this.mainform.autoplay != null && flashcookie.get( "autoplay" ) != null ){
        var list = this.formelements.autoplay.autoplay;
        for( var a = 0; a < list.length; a++ ){
          if( list[a].value == flashcookie.get( "autoplay" ) ) list[a].checked = true;
        } 
        this.mainform.autoplay.value = flashcookie.get( "autoplay" );
      }
      if( this.mainform.shuffle != null && flashcookie.get( "shuffle" ) != null ){
        var list = this.formelements.shuffle.shuffle;
        for( var a = 0; a < list.length; a++ ){
          if( list[a].value == flashcookie.get( "shuffle" ) ) list[a].checked = true;
        }
        this.mainform.shuffle.value = flashcookie.get( "shuffle" );
      }
      if( this.mainform.showvideo != null && flashcookie.get( "showvideo") != null ){
        var list = this.formelements.showvideo.showvideo;
        for( var a = 0; a < list.length; a++ ){
          if( list[a].value == flashcookie.get( "showvideo" ) ) list[a].checked = true;
        }
        this.mainform.showvideo.value = flashcookie.get( "showvideo" );
      }
      var color1 = "#FFFFFF", color2 = "#FFFFFF", color3 = "#FFFFFF", color4 = "#FFFFFF";
      if( this.mainform.color1 != null && flashcookie.get( "color1") != null ){
        $('_color1').setStyle('background-color', '#'+toHex( flashcookie.get( "color1") ) );
        color1 = toHex( flashcookie.get( "color1") ); block_color_load = true;
        this.mainform.color1.value = flashcookie.get( "color1");
      }
      if( this.mainform.color2 != null && flashcookie.get( "color2") != null ){
        $('_color2').setStyle('background-color', '#'+toHex( flashcookie.get( "color2") ) );
        color2 = toHex( flashcookie.get( "color2") ); block_color_load = true;
        this.mainform.color2.value = flashcookie.get( "color2");
      }
      if( this.mainform.color3 != null && flashcookie.get( "color3") != null ){
        $('_color3').setStyle('background-color', '#'+toHex( flashcookie.get( "color3") ) );
        color3 = toHex( flashcookie.get( "color3") ); block_color_load = true;
        this.mainform.color3.value = flashcookie.get( "color3");
      }
      if( this.mainform.color4 != null && flashcookie.get( "color4") != null ){
        $('_color4').setStyle('background-color', '#'+toHex( flashcookie.get( "color4") ) );
        color4 = toHex( flashcookie.get( "color4") ); block_color_load = true;
        this.mainform.color4.value = flashcookie.get( "color4");
      }
      setColors( color1, color2, color3, color4 );
      if( this.mainform.designerpattern != null && flashcookie.get( "designerpattern" ) != null ){
        var options = this.formelements.designerpattern.designerpattern.options;
        for( var a = 0; a < options.length; a++ ){
          if( options[a].value == flashcookie.get( "designerpattern" ) ) options[a].selected = true;
        }
        this.mainform.designerpattern.value = flashcookie.get( "designerpattern" );
        setPattern( { value: this.mainform.designerpattern.value } );
      }
      if( this.mainform.showloveheader != null && flashcookie.get( "showloveheader" ) != null ){
        this.mainform.showloveheader.value = flashcookie.get( "showloveheader" );
        this.formelements.showloveheader.header.value = flashcookie.get( "showloveheader" );
        setShowLoveHeader( flashcookie.get( "showloveheader" ), true );
      }
      if( this.mainform.myspaceusername != null && flashcookie.get( "myspaceusername" ) != null ){
        this.mainform.myspaceusername.value = flashcookie.get( "myspaceusername" );
        this.formelements.myspaceusername.myspaceusername.value = flashcookie.get( "myspaceusername" );
      }
    }
  },
  verifysave: function(){ 
    if( this.mainform.myspaceusername != null ){
      var val = trim( this.mainform.myspaceusername.value );
      if( val.length == 0 ){
        dialogAlert(getText("flash_js_MyspaceUsernameCannotBeBlank")); return false;
      }
    }
    if( this.mainform.playlist != null ){
      var playlistname = trim( this.mainform.playlistname.value );
      var playlistnumber = trim( this.mainform.playlistnumber.value );
      if( playlistname.length == 0 || playlistnumber.length == 0 || playlistnumber < 0 ){
         dialogAlert(getText("flash_js_YouMustSelectAPlaylistForWidget")); return false;
      }
      if( !loggedIn && playlistnumber > 0 ){
        dialogAlert(getText("flash_js_SorryLoggedOut")); return false;
      }
    }
    return true;
  }, 
  showsaveoptions: function(){

    var html = '';
    html += '<div style="margin-top:10px;text-align:left;margin-left:20px;border-bottom:1px solid #CCC;color:#555;">'+
            '<b>'+ getText("flash_js_Summary") + '</b></div>';
    html += '<center><table class="widget-summary">';
    if( this.mainform.myspaceusername != null ){
      var value = this.mainform.myspaceusername.value;
      html += '<tr><td class="heading">'+getText("flash_js_MySpaceUsername")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.playlist != null ){
      var value = this.mainform.playlistname.value;
      html += '<tr><td class="heading">'+getText("flash_js_PlaylistName")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.color1 != null ){
      var color = "#" + toHex( this.mainform.color1.value );
      var value = '<table align="center" style="border:1px solid #DDD;width:50px;height:10px;background-color:'+ color + '">'+
                  '<tr><td>&nbsp;</td></tr></table>';
      html += '<tr><td class="heading">'+getText("flash_js_Color1")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.color2 != null ){
      var color = "#" + toHex( this.mainform.color2.value );
      var value = '<table align="center" style="border:1px solid #DDD;width:50px;height:10px;background-color:'+ color + '">'+
                  '<tr><td>&nbsp;</td></tr></table>';
      html += '<tr><td class="heading">'+getText("flash_js_Color2")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.color3 != null ){
      var color = "#" + toHex( this.mainform.color3.value );
      var value = '<table align="center" style="border:1px solid #DDD;width:50px;height:10px;background-color:'+ color + '">'+
                  '<tr><td>&nbsp;</td></tr></table>';
      html += '<tr><td class="heading">'+getText("flash_js_Color3")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.color4 != null ){
      var color = "#" + toHex( this.mainform.color4.value );
      var value = '<table align="center" style="border:1px solid #DDD;width:50px;height:10px;background-color:'+ color + '">'+
                  '<tr><td>&nbsp;</td></tr></table>';
      html += '<tr><td class="heading">'+getText("flash_js_Color4")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.designerpattern != null ){
      var value = '';
      var options = this.formelements.designerpattern.designerpattern.options;
      for( var a = 0; a < options.length; a++ ){
        if( options[a].value == this.mainform.designerpattern.value ) value = options[a].text;
      }
      html += '<tr><td class="heading">'+getText("flash_js_DesignerPattern")+'</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.showloveheader != null ){
      var value = this.mainform.showloveheader.value;
      html += '<tr><td class="heading">'+getText("flash_js_Header")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.autoplay != null ){
      var value = this.mainform.autoplay.value;
      html += '<tr><td class="heading">'+getText("flash_js_Autoplay")+':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.shuffle != null ){
      var value = this.mainform.shuffle.value;
      html += '<tr><td class="heading">'+ getText("flash_js_Shuffle") + ':</td><td class="value">'+value+'</td></tr>';
    }
    if( this.mainform.showvideo != null ){
      var value = this.mainform.showvideo.value;
      html += '<tr><td class="heading">'+ getText("flash_js_ShowVideo") + ':</td><td class="value">'+value+'</td></tr>';
    }
   
    if( this.instance ){
        html += '<tr><td colspan="2" style="padding-left:6px;padding-top:20px;">'+
                '<div class="slim_blue_button" style="width:200px;" onclick="pMenu.submit()">'+
                '  <div class="left"></div><div class="right"></div>'+
                '  <div class="center" style="padding-top:2px">'+getText("flash_js_UpdateWidget")+'</div>'+
                '</div></td></tr>';
    }else{
      if( loggedIn ){      
        html += '<tr><td colspan="2" style="padding-left:6px;padding-top:20px;">'+
                '<div class="slim_blue_button" style="width:200px;" onclick="pMenu.submit()">'+
                '  <div class="left"></div><div class="right"></div>'+
                '  <div class="center" style="padding-top:2px">'+getText("flash_js_SaveAndCreateWidget")+'</div>'+
                '</div></td></tr>';
      }else{
        html += '<tr><td colspan="2" style="padding-left:6px;padding-top:20px;">'+
                '<div class="slim_blue_button" style="width:200px;" onclick="pMenu.login_save()">'+
                '  <div class="left"></div><div class="right"></div>'+
                '  <div class="center" style="padding-top:2px">'+ getText("flash_js_LoginAndCreateWidget") + '</div>'+
                '</div></td></tr>';
        html += '<tr><td colspan="2" style="padding-left:6px;padding-top:20px;">'+
                '<div class="slim_blue_button" style="width:200px;" onclick="pMenu.signup_save()">'+
                '  <div class="left"></div><div class="right"></div>'+
                '  <div class="center" style="padding-top:2px">'+ getText("flash_js_SignupAndCreateWidget") + '</div>'+
                '</div></td></tr>';
      }
    }

    html += '</table></center>';
    $('saveview').innerHTML = html;
  },
  login_save : function(){
    var flashcookie = new Hash.Cookie('nflashcookie', { domain: domainName, path: '/'} );
    flashcookie.set( 'dosave', 'true' );
    window.location.href = "/loginpage.jsp?referer=/widget/" + this.widgetId;
  }, 
  signup_save : function(){
    var flashcookie = new Hash.Cookie('nflashcookie', { domain: domainName, path: '/'} );
    flashcookie.set( 'dosave', 'true' );
    window.location.href = "/signup.jsp?referer=/widget/" + this.widgetId;    
  }, 
  submit : function(){
    this.mainform.submit();
  }
});

/****************************************************
* Playlist Interface
*****************************************************/

var sortajax = null;

function showplaylistchoice(){
  pMenu.savemusic();
  $('playlist-option').setStyle('display', 'block');
  $('playlist-search').setStyle('display', 'none');
  $('import-playlist').setStyle('display', 'none');
  $('add-song').setStyle('display', 'none');
}

function showimportplaylist(){
  pMenu.savemusic();
  $('playlist-option').setStyle('display', 'none');
  $('playlist-search').setStyle('display', 'none');
  $('import-playlist').setStyle('display', 'block');
  $('add-song').setStyle('display', 'none');
}

function showplaylistSearch(){
  pMenu.savemusic();
  $('playlist-option').setStyle('display', 'none');
  $('playlist-search').setStyle('display', 'block');
  $('import-playlist').setStyle('display', 'none');
  $('add-song').setStyle('display', 'none');
}

function showaddsongmanually(){
  pMenu.savemusic();
  $('playlist-option').setStyle('display', 'none');
  $('playlist-search').setStyle('display', 'none');
  $('import-playlist').setStyle('display', 'none');
  $('add-song').setStyle('display', 'block');
}

function writeplaylist( playlist ){
  if( document.createflashinstance.playlistname == null ) return;

  if( playlist == null || playlist.playlist_number == 0 ){
    $('playlist_songtitle').innerHTML = document.createflashinstance.playlistname.value + " ["+ getText("flash_js_NotSavedYet") + "]";
  }else $('playlist_songtitle').innerHTML = getText("flash_js_Playlist") + ": "  + playlist.name;

  sendplaylist2widget( playlist );

  var html = '';
  for( var a = 0; playlist != null && playlist.songs != null && a < playlist.songs.length; a++ ){
    var deletelink = "delSong('"+ playlist.playlist_number+"', '"+ playlist.songs[a].id + "');return false";
    html += '<div id="' + a + '" class="song">' + (a+1) + '. ' + playlist.songs[a].title  + '<br>' +
            ' <div style="text-align:right;font-size:8pt">'+
            ' <a class="palebluelink" href="#" onclick="' + deletelink + '">'+getText("flash_js_Delete")+'</a></div>'+
            '</div>';
  }
  if( playlist == null || playlist.songs == null ){
    html += '<div style="padding:3px"><center>'+getText("flash_js_NoSongsInThisPlaylist")+'</center></div>';
  }
  $('playlist_container').innerHTML = html;
  makeSortable( playlist.playlist_number );
}

function makeSortable( playlistNumber ){
  var mySort = new Sortables( $("playlist_container"),
  {
     constrain: true,
     clone: true,
     revert: true,
     onComplete: function(){
       var result = ""+mySort.serialize();
       var array = result.split(",");
       var order = '';
       var inorder = true;
       for(var a = 0; a < array.length; a++){
         order += array[a].replace(/^s+/, '').replace(/s+$/, '');
         if(a != array.length-1) order += '.';
         if( a < array.length-1 && parseInt(array[a]) > parseInt(array[a+1]) ) inorder = false;
       }
       var index = 0;
       mySort.serialize(function(element){
         element.id = index;
         index++;
       });
       if( inorder == true ) return;
       if( playlistNumber == 0 ){
         sessionplaylist_reorder( order );
         loadplaylist(0);
       }else{
         var reloadfunc = function(num){ loadplaylist(num) }.pass( playlistNumber );
         if( sortajax ) sortajax.abort();
         sortajax = new Ajax( reloadfunc, ajaxError );
         var uri = "/media/reorderplaylist!ajax.action?playlistNumber="+playlistNumber+
                   "&order="+encodeURIComponent(order)+"&gen="+ generateLine();
         sortajax.get( uri, null, false );
       }
     }
  });
}


/****************************************************
* Playlist Options
*****************************************************/

function createnewplaylistOption(){
  if( loggedIn == false ){
    var playlistName = trim( $('op1_playlistname').value );
    if( playlistName.length == 0 ){
      dialogAlert( getText("flash_js_PleaseSelectNameForPlaylist") );
    }else{            
      document.createflashinstance.playlistnumber.value = 0;
      document.createflashinstance.playlistname.value = playlistName;
      var playlistArray = sessionplaylist_getplaylist();
      if( playlistArray == null ) writeplaylist( null );
      else writeplaylist( playlistArray[0] );
      showplaylistSearch();
    }
  }else{
    createnewplaylist();
  }
}

function useexistingplaylistOption(){
  if( $('op2_playlistname') == null ) return;
  var playlistnumber = $('op2_playlistname').options[ $('op2_playlistname').selectedIndex ].value;
  var playlistname = $('op2_playlistname').options[ $('op2_playlistname').selectedIndex ].text;
  document.createflashinstance.playlistnumber.value = playlistnumber;
  document.createflashinstance.playlistname.value = playlistname;
  loadplaylist( playlistnumber );
  showplaylistSearch();
}

function useimportplaylistOption(){
  if( $('op3_playlistname') == null ) return;
  var playlistname = trim( $('op3_playlistname').value );
  var playlistnumber = -1;
  if( playlistname == null || playlistname.length == 0 ){
    dialogAlert( getText("flash_js_PleaseSelectNameForPlaylist") ); return;
  }
  document.createflashinstance.playlistnumber.value = playlistnumber;
  document.createflashinstance.playlistname.value = playlistname;
  showimportplaylist();
}

/****************************************************
* Playlist Actions
*****************************************************/

var getplaylistajax = null;

function createnewplaylist(){
  var playlistName = trim( $('op1_playlistname').value );
  if( playlistName.length == 0 ){
    dialogAlert( getText("flash_js_PleaseSelectNameForPlaylist") );
  }else{
    var playlistArray = sessionplaylist_getplaylist();
    if( playlistArray == null || playlistArray.length == 0 || playlistArray[0].songs == null || playlistArray[0].songs.length == 0 ){
      var ajax = new Ajax( createnewplaylistHandler, ajaxError );
      var uri = "/media/createplaylist!ajax.action?playlistname=" + encodeURIComponent(playlistName);
      ajax.get( uri, null, false );
    }else{
      var ajax = new Ajax( createnewplaylistHandler, ajaxError );
      var uri = "/media/savesessionplaylist!ajax.action?playlistname=" + encodeURIComponent(playlistName);
      ajax.get( uri, null, false );
    }
  }
}

function createnewplaylistHandler( obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status == 'success'){
    document.createflashinstance.playlistnumber.value = json.Playlist[0].playlist_number;
    document.createflashinstance.playlistname.value = json.Playlist[0].name;
    writeplaylist( json.Playlist[0] );
    showplaylistSearch();
  }else{
    dialogAlert(json.errorMessage);
  }
}

function importplaylist(){
  var playlistName = document.createflashinstance.playlistname.value;
  var code = $('importplaylistform').code.value;

  if( playlistName.length < 1 ){
    dialogAlert( getText("flash_js_PleaseEnterNameForPlaylist") );
    return;
  }
  if( code.length < 1 ){
    dialogAlert( getText("flash_js_CodeFieldCannotBeBlank") );
    return;
  }

  var ajax = new Ajax( importplaylistHandler, importplaylistError );
  var uri = "/media/importplaylist!ajax.action";
  var data  = new Object();
  data.playlistName = playlistName;
  data.code         = code;
  data.cc           = "false";
  $('loadingexternalplaylist').setStyle('display', 'block');
  $('externalplaylistbuttons').setStyle('display', 'none');
  ajax.post( uri, data, false );
}

function importplaylistError(){
  $('loadingexternalplaylist').setStyle('display', 'none');
  $('externalplaylistbuttons').setStyle('display', 'block');
  ajaxError();
}

function importplaylistHandler( obj, jsont ){
  var json = eval( '(' + jsont + ')' );

  $('loadingexternalplaylist').setStyle('display', 'none');
  $('externalplaylistbuttons').setStyle('display', 'block');
  if(json.status == 'success'){
    var playlist       = json.Playlist[0];
    var playlistNumber = playlist.playlist_number;
    var playlistName   = playlist.name;

    $('importplaylistform').code.value = "";
    document.createflashinstance.playlistnumber.value = playlistNumber;
    document.createflashinstance.playlistname.value   = playlistName;
    showplaylistSearch();
    loadplaylist( playlistNumber );
    dialogAlertTimeout( getText("flash_js_ImportSuccessful"), 3000);
  }else{
    dialogAlert(json.errorMessage, 3000);
  }
}

function loadplaylist( playlistNumber ){
  if( document.createflashinstance.playlistname == null ) return;

  if( playlistNumber == 0 ){
    var playlistArray = sessionplaylist_getplaylist();
    if( playlistArray != null && playlistArray.length != 0 ) writeplaylist( playlistArray[0] );
  }else{
    if( getplaylistajax ) getplaylistajax.abort();
    getplaylistajax = new Ajax( loadplaylistHandler, ajaxError );
    var uri = "/media/listplaylist!ajax.action?gen="+generateLine()+"&playlistNumber=" + encodeURIComponent(playlistNumber);
    getplaylistajax.get( uri, null, false );
  }
}

function loadplaylistHandler( obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status == 'success'){
    writeplaylist( json.Playlist[0] );
  }else{
    dialogAlert(json.errorMessage);
  }
}

/****************************************************
* Search Music
*****************************************************/
var searchajax = null;

function selectsearchoption( el ){
  $$('.search-option').each( function( el ){
    el.removeClass('search-option-sel');
  });
  el.addClass('search-option-sel');

  var cookie = new Hash.Cookie('searchoptions_flash');
  if( el.get('title') == 'All' ) cookie.set('searchtype', 'all');
  if( el.get('title') == 'MP3' ) cookie.set('searchtype', 'mp3');
  if( el.get('title') == 'Video' ) cookie.set('searchtype', 'video');
}

function setvideosearchtype(){
  $$('.search-option').each( function( el ){
    el.removeClass('search-option-sel');
    if( el.get('title') == 'Video' ) el.addClass('search-option-sel');
  });
  var cookie = new Hash.Cookie('searchoptions_flash');
  cookie.set('searchtype', 'video');
}

function searchMusic(){
  $('search-loader').setStyle('display', 'block');
  $('search-results').setStyle('opacity', 0.2 );

  var cookie = new Hash.Cookie('searchoptions_flash');
  var searchtype =  cookie.get('searchtype');
  var query = $('search-query').value;
  if( searchtype == null || searchtype != 'video' ){
    if( searchajax ) searchajax.abort();
    searchajax = new Ajax( searchMusicHandler, searchMusicError, query );
    var uri = "/media/search!ajax.action?gen="+generateLine()+"&query=" + encodeURIComponent(query) + "&st=" + searchtype;
    searchajax.get( uri, null, false );
  }else{
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    var yahoopipes = (isIE) ? window["yahoopipes1"] : document["yahoopipes1"];
    if( typeof(yahoopipes) == 'undefined' || typeof(yahoopipes.getPipe) == 'undefined' ){
      dialogAlertTimeout( getText("flash_js_PageStillLoading"), '2000' );
      return;
    }
    var uri = "http://pipes.yahooapis.com/pipes/pipe.run?_id=jpG_8KB_3RGNGO1Epl8axw&_render=json&max-results=50&query="+ encodeURIComponent(query);
    var callback = "searchVideoHandler";
    yahoopipes.getPipe( uri, callback );
  }
}

function searchMusicError(){
  $('search-loader').setStyle('display', 'none');
  $('search-results').setStyle('opacity', 1 );
  ajaxError();
}


function searchVideoHandler( jsont, code ){
  $('search-loader').setStyle('display', 'none');
  $('search-results').setStyle('opacity', 1 );
  new Fx.Scroll( 'search-results' ).start( 0, 0 );
  if( code == "true" ){
    var json = eval( '(' + jsont + ')' );
    var videos = json.value.items;
    var VideoArray = parseYoutubeVideoResult( videos );
    var artist = '', name = '', seperator = '';
    var html = '';
    if( VideoArray == null || VideoArray.length == 0 ){
      html += '<div style="color:#888;padding:5px;">'+getText("flash_js_NoSearchResults")+'</div>';
    }
    for( var a = 0; VideoArray != null && a < VideoArray.length; a++ ){
      var title = VideoArray[a].title;
      var link  = VideoArray[a].link;
      var img   = VideoArray[a].thumbnail1;
      artist = title;
      name   = '';
      seperator = '';
      if( title.indexOf("-") != -1 ){
        artist = trim( title.substr(0, title.indexOf("-") ) );
        seperator = " - ";
        name = trim( title.substr( title.indexOf("-")+1, title.length ) );
      }
      var fixed_title = fix4param( title );
      var fixed_url   = fix4param( link );
      var playclick = "testSong("+ a + ", '"+ fixed_url+"', '"+ fixed_title + "', this );return false";
      var addsongclick = "addSong('"+ fixed_url+"', '"+ fixed_title + "');return false";
      var infoclick = "showSongInfo('"+ fixed_url+"', '"+ fixed_title + "');return false";
      var itunes = "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/search?WOURLEncoding=ISO8859_1&lang=1&output=lm&country=US&term=\"" +
                   encodeURIComponent(artist) + "+-+" + encodeURIComponent(name) + "\"";        
      html += '<div style="padding-top:3px;padding-bottom:3px;border-bottom:1px solid #EEE">';
      html += '<table width="100%"><tr>';
      html += ' <td style="text-align:center;vertical-align:middle;width:70px;">';
      html += '   <a href="#" onclick="' + playclick + '">';
      html += '   <img src="' + statichost+ '/images/createwidget/play_button.gif">';
      html += '   </a>&nbsp;';
      html += '   <a href="#" onclick="'+ addsongclick + '">';
      html += '   <img src="' + statichost+ '/images/createwidget/add_button.gif">';
      html += '   </a>';
      html += ' </td> ';
      html += ' <td style="text-align:center;vertical-align:middle;width:80px">';
      html += '  <div id="viewer' + a + '"><img width="80" src="'+ img + '"></div>';
      html += ' </td> ';
      html += ' <td style="text-align:left;vertical-align:top;font-size:8pt;padding-left:3px;"> ';
      html += '   <span>' + artist + seperator + name + '</span><br>';
      html += '   <div style="margin-top:6px;color:#AAA;">';
      html += '     <a class="lightbluelink" target="_blank" href="http://offers.thumbplay.com/offers/Open_Artist_6843/atb3?'+
              'thpartist='+encodeURIComponent(artist)+'&thptitle='+encodeURIComponent(name)+'&thpcampid=widget-search">';
      html += '     Get Ringtone</a> | ';
      html += '     <a class="lightbluelink" target="_blank" href="#">'+getText("flash_js_Share")+'</a> | ';
      html += '     <a class="lightbluelink" target="_blank" href=\''+ itunes + '\'>'+getText("flash_js_iTunes")+'</a> ';
      html += '   </div>';
      html += ' </td> ';
      html += '</tr></table>';
      html += '<div style="margin-left:8px" id="controller' + a + '"></div>';
      html += '</div>';
    }
    $('search-results').innerHTML = html;
  }else{
    dialogAlert( getText("flash_js_ErrorRetreivingSearchResults") );
  }
}

function searchMusicHandler( obj, jsont ){
  $('search-loader').setStyle('display', 'none');
  $('search-results').setStyle('opacity', 1 );
  new Fx.Scroll( 'search-results' ).start( 0, 0 );
  var json = eval( '(' + jsont + ')' );
  if(json.status != 'failure'){
    var html = '', title = '', artist = '', seperator = '', name = '';
    var results = json.results;
    if( results == null || results.length == 0 ){
      html += '<div style="color:#888;padding:5px;">'+getText("flash_js_NoSearchResults")+'</div>';
    }
    for( var a = 0; results != null && a < results.length; a++ ){
      title = results[a].title;
      artist = title;
      name   = '';
      seperator = '';
      if( title.indexOf("-") != -1 ){
        artist = trim( title.substr(0, title.indexOf("-") ) );
        seperator = " - ";
        name = trim( title.substr( title.indexOf("-")+1, title.length ) );
      }
      var fixed_title = fix4param( title );
      var fixed_url   = fix4param( results[a].url );
      var playclick = "testSong("+ a + ", '"+ fixed_url+"', '"+ fixed_title + "', this );return false";
      var addsongclick = "addSong('"+ fixed_url+"', '"+ fixed_title + "');return false";
      var infoclick = "showSongInfo('"+ fixed_url+"', '"+ fixed_title + "');return false";
      var itunes = "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/search?WOURLEncoding=ISO8859_1&lang=1&output=lm&country=US&term=\"" +
                   encodeURIComponent(artist) + "+-+" + encodeURIComponent(name) + "\"";
      html += '<div style="padding-top:3px;padding-bottom:3px;border-bottom:1px solid #EEE">';
      html += '<table width="100%"><tr>';
      html += ' <td style="text-align:center;vertical-align:middle;width:70px;">';
      html += '   <a href="#" onclick="' + playclick + '">';
      html += '   <img src="' + statichost+ '/images/createwidget/play_button.gif">';
      html += '   </a>&nbsp;';
      html += '   <a href="#" onclick="'+ addsongclick + '">';
      html += '   <img src="' + statichost+ '/images/createwidget/add_button.gif">';
      html += '   </a>';
      html += ' </td> ';
      html += ' <td style="text-align:left;vertical-align:top;font-size:8pt"> ';
      html += '   <span>' + artist + seperator + name + '</span><br>';
      html += '   <div style="margin-top:6px;color:#AAA;">';
      html += '     <a class="lightbluelink" target="_blank" href="http://offers.thumbplay.com/offers/Open_Artist_6843/atb3?'+
              'thpartist='+encodeURIComponent(artist)+'&thptitle='+encodeURIComponent(name)+'&thpcampid=widget-search">';
      html += '     Get Ringtone</a> | ';
      html += '     <a class="lightbluelink" target="_blank" href="#">'+getText("flash_js_Share")+'</a> | ';
      html += '     <a class="lightbluelink" target="_blank" href=\''+ itunes + '\'>'+getText("flash_js_iTunes")+'</a> ';
      html += '   </div>';
      html += ' </td> ';
      html += '</tr></table>';
      html += '<div style="margin-left:8px" id="viewer' + a + '"></div>';
      html += '<div style="margin-left:8px" id="controller' + a + '"></div>';
      html += '</div>';
    }
    $('search-results').innerHTML = html;
  }else{
    dialogAlert(json.errorMessage);
  }
}

/****************************************************
* Media Actions
*****************************************************/
var LAST_ID = -1;
var LC = generateLine();
var CONTROLLER_WIDTH = 400;
var LAST_VIEWER_HTML = "";

function addsongmanually(){
  var title = trim( $('addsongform').title.value );
  var url   = trim( $('addsongform').url.value );
  $('add-song-loader').setStyle('display', 'block');
  $('add-song-buttons').setStyle('display', 'none');
  var playlistnumber = document.createflashinstance.playlistnumber.value;
  if( playlistnumber == 0 ){
    if( sessionplaylist_add( url, title ) ){
       dialogAlertTimeout( getText("flash_js_SongsAddedSuccessfully"), 3000);
       $('addsongform').title.value = "";
       $('addsongform').url.value   = "";
       loadplaylist( playlistnumber );
    }
  }else{
    var ajax = new Ajax( addsongmanuallyHandler, addsongmanuallyError, playlistnumber );
    var uri = "/media/addplaylistmedia!ajax.action?gen="+generateLine()+"&playlistNumber="+playlistnumber+
              "&title="+encodeURIComponent(title)+"&url="+encodeURIComponent(url);
    ajax.get( uri, null, false );
  }
}

function addsongmanuallyError(){
  $('add-song-loader').setStyle('display', 'none');
  $('add-song-buttons').setStyle('display', 'block');
}

function addsongmanuallyHandler( obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  $('add-song-loader').setStyle('display', 'none');
  $('add-song-buttons').setStyle('display', 'block');
  if(json.status == 'success'){
    $('addsongform').title.value = "";
    $('addsongform').url.value   = "";
    loadplaylist( obj.getParams() );
  }else{
    dialogAlert(json.errorMessage);
  }
}

function addSong( url, title ){
  var playlistNumber = 0;
  if( loggedIn == false ) playlistNumber = 0;
  else playlistNumber = document.createflashinstance.playlistnumber.value;
  var title = encodeURIComponent( title );
  var url = encodeURIComponent( url );
  if( playlistNumber == 0 ){
    if( sessionplaylist_add( url, title ) ){
       dialogAlertTimeout(getText("flash_js_SongsAddedSuccessfully"), 3000);
       loadplaylist( playlistNumber );
    }
  }else{
    var ajax = new Ajax( addSongHandler, ajaxError, playlistNumber );
    var uri = "/media/addplaylistmedia!ajax.action?gen="+generateLine()+"&playlistNumber="+playlistNumber+"&title="+title+"&url="+url;
    ajax.get( uri, null, false );
  }
}

function addSongHandler(  obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status == 'success'){
    loadplaylist( obj.getParams() );
    dialogAlertTimeout(getText("flash_js_SongsAddedSuccessfully"), 3000);
  }else{
    dialogAlertTimeout(json.errorMessage, 3000);
  }
}

function delSong( playlistNumber, songId ){
  var args = new Object();
  args.playlistNumber = playlistNumber;
  args.songId = songId;
  confirmSubmit(null, delSongConfirmHandler, args );
  return false;
}

function delSongConfirmHandler( value, args ){
  if( value == true ){
    if( args.playlistNumber == 0 ){
      if( sessionplaylist_delete( args.songId ) == true ){
        dialogAlertTimeout(getText("flash_js_SongsDeletedSuccessfully"), 3000);
        loadplaylist( 0 );
      }else{
        dialogAlert( getText("flash_js_ErrorDeletingSong") );
      }
    }else{
      var ajax = new Ajax( delSongHandler, ajaxError, args.playlistNumber );
      var uri = "/media/deleteplaylistmedia!ajax.action?confirm=true&playlistNumber="+args.playlistNumber+"&songId="+args.songId+"&gen="+generateLine();
      ajax.get( uri, null, false );
    }
  }
}

function delSongHandler( obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status != 'success'){
    dialogAlert(json.errorMessage);
  }else{
    dialogAlertTimeout(getText("flash_js_SongsDeletedSuccessfully"), 3000);
    loadplaylist( obj.getParams() );
  }
}

function testSong( ID, url, title ){
  var videoswf = '';
  if( url.indexOf('youtube.com') != -1 ){
    videoswf = '<embed src="' + statichost + '/swf/Viewer.swf?lc=' + LC + '" quality="high" bgcolor="#000000" '+
               '        width="80" height="70" name="Viewer" align="middle" allowScriptAccess="always" '+
               '        allowFullScreen="false" type="application/x-shockwave-flash" '+
               '        pluginspage="http://www.macromedia.com/go/getflashplayer" />';
  }
  if( LAST_ID != -1 ){
     $('controller'+LAST_ID).innerHTML = "";
     $('viewer'+LAST_ID).innerHTML = LAST_VIEWER_HTML;
  }
  LAST_VIEWER_HTML = $('viewer'+ID).innerHTML;
  LAST_ID = ID;
  var controllerswf = '<embed src="' + statichost + '/swf/Controller.swf?url='+ encodeURIComponent( url ) +'&lc=' + LC + '" ' +
                      '        quality="high" wmode="transparent" bgcolor="#000000" '+
                      '        width="' + CONTROLLER_WIDTH + '" height="15" name="Controller" align="middle" allowScriptAccess="always" '+
                      '        allowFullScreen="false" type="application/x-shockwave-flash" '+
                      '        pluginspage="http://www.macromedia.com/go/getflashplayer" />';
  $('controller'+ID).innerHTML = controllerswf;
  $('viewer'+ID).innerHTML = videoswf;
}



/****************************************************
* Color Config
*****************************************************/
var _colorfield = "";

CLCPHandler = function(_hex) {
  block_color_load = false;
  var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["flashwidget"]:document["flashwidget"];
  flash.SetVariable( _colorfield, '0x'+_hex );
  if( flash.updatecolors ) flash.updatecolors();
}

function initColorChooser(){
  var clcpdiv = document.createElement('div');
  clcpdiv.setAttribute('id', 'CLCP');
  clcpdiv.setAttribute('class', 'CLCP');
  clcpdiv.setAttribute('className', 'CLCP');
  document.getElementsByTagName("body")[0].appendChild( clcpdiv );
  _CLCPdisplay = "none";       // Values: "none", "block". Default "none"
  _CLCPisDraggable = true;     // Values: true, false. Default true
  _CLCPposition = "absolute";  // Values: "absolute", "relative". Default "absolute"
  _CLCPinitHex = "0039B3";     // Values: Any valid hex value. Default "ffffff"
  CLCPinitPicker();
}


/****************************************************
* Flash Setting Setters
*****************************************************/
var send2playlistInterval = -1;
var EPLAYLIST = null;

function sendplaylist2widget( playlist ){
  if( playlist == null ) return;
  EPLAYLIST = playlist;
  var json = JSON.encode( playlist );
  var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["flashwidget"]:document["flashwidget"];
  if( flash != null && flash.loadplaylist ){
    clearInterval( send2playlistInterval );
    flash.SetVariable( "eplaylist", json );
    flash.loadplaylist();
  }else if( send2playlistInterval == -1 ){
    send2playlistInterval = setInterval( "iSendplaylist2widget()", 1000 );
  }
}

function iSendplaylist2widget(){
  sendplaylist2widget( EPLAYLIST );
}



function setColors( color1, color2, color3, color4, prefix ){
  if( prefix ) block_color_load = false;

  var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["flashwidget"]:document["flashwidget"];
  if( color1 ){
    flash.SetVariable( "color1", "0x"+color1 );
  }
  if( color2 ){
    flash.SetVariable( "color2", "0x"+color2 );
  }
  if( color3 ){
    flash.SetVariable( "color3", "0x"+color3 );
  }
  if( color4 ){
    flash.SetVariable( "color4", "0x"+color4 );
  }
  if( flash.updatecolors ) flash.updatecolors();
}

function setPattern( patterninput ){
  var value = patterninput.value;
  document.createflashinstance.designerpattern.value = value;
  var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["flashwidget"]:document["flashwidget"];
  flash.SetVariable( "designerpattern", value );
  if( flash.updatedesignerpattern ) flash.updatedesignerpattern();
}

function setShowVideo( value ){
  document.createflashinstance.showvideo.value = value;
}
function setAutoPlay( value ){
  document.createflashinstance.autoplay.value = value;
}

function setShuffle( value ){
  document.createflashinstance.shuffle.value = value;
}

function setShowLoveHeader( value, input ){
  document.createflashinstance.showloveheader.value = value;
  var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["flashwidget"]:document["flashwidget"];

  flash.SetVariable( "header", value );
  if( flash.updateheader ) flash.updateheader();
  if( input == true ){
    document._showloveheader.default1.checked = false;
  }

}

function setMySpaceUsername(){
  document.createflashinstance.myspaceusername.value = document.myspaceusernameform.myspaceusername.value;
}

function previewMySpaceUsername(){
  setMySpaceUsername();
  var query = '&autoplay=false';
  var myspaceusername = document.myspaceusernameform.myspaceusername.value;
  query += '&myspaceusername='+encodeURIComponent( myspaceusername );
  if( document.createflashinstance.color1 && document.createflashinstance.color1.value.length > 0 )
    query += '&color1='+document.createflashinstance.color1.value;
  if( document.createflashinstance.color2 && document.createflashinstance.color2.value.length > 0 )
    query += '&color2='+document.createflashinstance.color2.value;
  if( document.createflashinstance.color3 && document.createflashinstance.color3.value.length > 0 )
    query += '&color3='+document.createflashinstance.color3.value;
  if( document.createflashinstance.color4 && document.createflashinstance.color4.value.length > 0 )
    query += '&color4='+document.createflashinstance.color4.value;

  var flashvars = {};
  var params = { wmode: "transparent", allowScriptAccess:"always" };
  var attributes = { id: "flashwidget", name: "flashwidget" };
  swfobject.embedSWF( FLASHURL + query, "flashwidget", FLASHWIDTH, FLASHHEIGHT, "8.0.0", null, flashvars, params, attributes);
}


/****************************************************
* Results from Flash Widget Setting Setters
*****************************************************/

function flashcolors( jsont ){

  if( block_color_load ) return;

  var json = eval( '(' + jsont + ')' );
  if( json.color1 && $('_color1') != null ){
    $('_color1').setStyle('background-color', '#'+toHex(json.color1) );
    document.createflashinstance.color1.value = json.color1;
  }
  if( json.color2 && $('_color2') ){
    $('_color2').setStyle('background-color', '#'+toHex(json.color2) );
    document.createflashinstance.color2.value = json.color2;
  }
  if( json.color3 && $('_color3') ){
    $('_color3').setStyle('background-color', '#'+toHex(json.color3) );
    document.createflashinstance.color3.value = json.color3;
  }
  if( json.color4 && $('_color4') ){
    $('_color4').setStyle('background-color', '#'+toHex(json.color4) );
    document.createflashinstance.color4.value = json.color4;
  }
}

function flashdesignerpattern( jsont ){
  var json = eval( '(' + jsont + ')' );
  if( json.designerpattern && $('designerpattern') ){
    if( json.designerpattern == 'NaN' ) json.designerpattern = "";
    $('designerpattern').value = json.designerpattern;
     document.createflashinstance.designerpattern.value = json.designerpattern;
  }
}

function flashheader( jsont ){
  var json = eval( '(' + jsont + ')' );
  if( json.header ){
    if( document.createflashinstance.showloveheader ){
      document.createflashinstance.showloveheader.value = json.header;
    }
  }
}



/**********************************************
* WildFire Menu
**********************************************/
var WidgetShare = new Class({
  initialize: function(div, textarea){
    this.displayname = div;
    this.textarea = $(textarea);
    this.width = 580;
    this.height = 300;
    this.pconf = new Object();
    this.pconf.bookmarkURL = "http://www.flashwidgetz.com";
    this.pconf.widgetTitle = "Flashwidgetz";
    this.pconf.includeShareButton = "false";
    this.pconf.defaultContent = textarea;
    this.wfcode = '' +
                  '<body corner-roundness="8;8;8;8"><background frame-color="Transparent" gradient-color-begin="#353535" '+
                  'gradient-color-end="#606060" corner-roundness="8;8;8;8"></background><controls size="11" bold="true">'+
                  '<snbuttons iconsOnly="false" type="textUnder" frame-color="#6D0000" background-color="#FFFFFF" '+
                  'over-background-color="#FFFFFF" color="#CACACA" corner-roundness="0;8;8;8" gradient-color-begin="#8A8A8A" '+
                  'gradient-color-end="#000000" font="Arial" size="11" bold="false" over-gradient-color-begin="#AAAAAA" '+
                  'over-gradient-color-end="#000000" over-color="#F4F4F4" down-color="#000000"><more frame-color="Transparent">'+
                  '</more></snbuttons><textboxes frame-color="#000000" color="#AAAAAA" corner-roundness="0;0;0;0" '+
                  'gradient-color-begin="#202020" gradient-color-end="#0B0B0B" font="Arial" bold="false"><codeboxes '+
                  'color="#EAEAEA" frame-color="#8A8A8A" gradient-color-begin="#000000" font="Arial" bold="false"></codeboxes>'+
                  '<inputs frame-color="#6D0000"></inputs><dropdowns frame-color="#6D0000" handle-gradient-color-begin="#B60000" '+
                  'handle-gradient-color-end="#6D0000" handle-over-gradient-color-begin="#FF0000" handle-over-gradient-color-end="#DA0000" '+
                  'handle-down-gradient-color-begin="#FF0000" handle-down-gradient-color-end="#6D0000" background-color="#6D0000" '+
                  'gradient-color-begin="#000000" font="Arial" bold="false"></dropdowns></textboxes><buttons frame-color="#FF0000" '+
                  'gradient-color-begin="#FF2424" gradient-color-end="#6D0000" color="#F4F4F4" corner-roundness="0;8;8;8" '+
                  'font="Arial" size="10" bold="false" down-frame-color="#000000" over-gradient-color-begin="#DA0000" '+
                  'down-gradient-color-begin="#910000" over-gradient-color-end="#DA0000" down-gradient-color-end="#FF0000" '+
                  'over-color="#F4F4F4"><post-buttons gradient-color-begin="#FF4949" gradient-color-end="#6D0000">'+
                  '</post-buttons></buttons><listboxes corner-roundness="5;5;5;5"></listboxes><servicemarker '+
                  'gradient-color-begin="#DA0000" gradient-color-end="#DA0000"></servicemarker></controls><texts color="#FFFFFF" '+
                  'font="Arial" size="10"><privacy color="#959595" size="11"></privacy><headers size="14" bold="true">'+
                  '</headers><labels size="11" bold="true"></labels><messages color="#D5D5D5" frame-thickness="0" '+
                  'corner-roundness="0;0;0;0" gradient-color-begin="#B60000" gradient-color-end="#000000" size="11" bold="true">'+
                  '</messages><links color="#DFDFDF" underline="false" size="11" bold="true" over-color="#FFFFFF"></links></texts></body>';      
  },
  showspecialpostonly : function( width, height ){
    if( width != null ) this.width = width;
    if( height != null ) this.height = height;
    this.wfcode = '' +
                  '<body><background frame-color="#BFBFBF" background-color="#FFFFFF" gradient-color-begin="#ffffff" '+ 
                  'gradient-color-end="#F4F4F4" corner-roundness="4;4;4;4"></background><controls color="#202020" corner-roundness="4;4;4;4" '+
                  'gradient-color-begin="#EAEAEA" gradient-color-end="#F4F4F4" bold="false"><snbuttons iconsOnly="false" type="textUnder" '+
                  'frame-color="#D5D5D5" over-frame-color="#60BFFF" color="#808080" gradient-color-begin="#FFFFFF" gradient-color-end="d4d6d7" '+
                  'size="10" bold="false" down-frame-color="#60BFFF" down-gradient-color-begin="#6DDADA" over-gradient-color-end="#6DDADA" '+
                  'down-gradient-color-end="#F4F4F4" over-color="#52A4DA" down-color="#52A4DA" over-bold="false"><more frame-color="#A4DBFF" '+
                  'over-frame-color="#A4DBFF" gradient-color-begin="#F4F4F4" gradient-color-end="#BBE4FF" over-gradient-color-begin="#A4DBFF" '+
                  'over-gradient-color-end="#F4F4F4"></more><previous frame-color="#BBE4FF" over-frame-color="#A4DBFF" '+
                  'gradient-color-begin="#FFFFFF" gradient-color-end="#A4DBFF" over-gradient-color-begin="#A4DBFF" '+
                  'over-gradient-color-end="#F4F4F4"></previous></snbuttons><textboxes frame-color="#CACACA" color="#757575" '+
                  'gradient-color-begin="#ffffff" bold="false"><codeboxes color="#757575" frame-color="#DFDFDF" background-color="#FFFFFF" '+
                  'gradient-color-begin="#ffffff" gradient-color-end="#FFFFFF" size="10"></codeboxes><inputs frame-color="#CACACA" '+
                  'color="#757575" gradient-color-begin="#F4F4F4" gradient-color-end="#ffffff"></inputs><dropdowns list-item-over-color="#52A4DA" '+
                  'frame-color="#CACACA"></dropdowns></textboxes><buttons frame-color="#CACACA" gradient-color-begin="#F4F4F4" '+
                  'gradient-color-end="#CACACA" color="#000000" bold="false" over-frame-color="#60BFFF" over-gradient-color-begin="#BBE4FF" '+
                  'down-gradient-color-begin="#BBE4FF" over-gradient-color-end="#FFFFFF" down-gradient-color-end="#ffffff"><post-buttons '+
                  'frame-color="#CACACA" gradient-color-end="#CACACA"></post-buttons></buttons><listboxes frame-color="#CACACA" '+
                  'corner-roundness="4;4;4;4" gradient-color-begin="#F4F4F4" gradient-color-end="#FFFFFF"></listboxes><checkboxes '+
                  'checkmark-color="#00B600" frame-color="#D5D5D5" corner-roundness="3;3;3;3" gradient-color-begin="#F4F4F4" '+
                  'gradient-color-end="#FFFFFF"></checkboxes><servicemarker gradient-color-begin="#ffffff" gradient-color-end="#D5D5D5">'+
                  '</servicemarker><tooltips color="#6D5128" gradient-color-begin="#FFFFFF" gradient-color-end="#FFE4BB" size="10" '+
                  'frame-color="#FFDBA4"></tooltips></controls><texts color="#202020"><headers color="#202020"></headers><messages color="#202020">'+
                  '</messages><links color="#52A4DA" underline="false" over-color="#353535" down-color="#353535" down-bold="false"></links></texts></body>';

    this.pconf.UIConfig = '<config><display showEmail="true" useTransitions="true" showBookmark="true" codeBoxHeight="auto" showCodeBox="true" '+
                          'showCloseButton="false" networksToHide="livedoor, myspace, friendster, facebook, orkut, bebo, tagged, blogger, hi5, '+
                          'livespaces, piczo, freewebs, livejournal, blackplanet, myyearbook, vox, typepad, xanga, multiply, igoogle, netvibes, '+
                          'pageflakes, migente, yahoo, ameba" networksWithCodeBox="" networksToShow="*"></display>' + this.wfcode + '</config>';

    Wildfire.initPost('134221', this.displayname, this.width, this.height, this.pconf);
  },
  showall: function(){
    this.pconf.UIConfig = '<config><display showDesktop="false" showEmail="true" showPost="true" useTransitions="true" '+
                          'postToSidebarChecked="true" showBookmark="true" codeBoxHeight="auto" showCodeBox="true" '+
                          'showCloseButton="false" bulletinChecked="true" networksWithCodeBox="*"></display>'+
                          this.wfcode + '</config>';
    Wildfire.initPost('134221', this.displayname, this.width, this.height, this.pconf );
  },
  showmyspace: function(){
    this.pconf.UIConfig = '<config><display showDesktop="false" showEmail="true" showPost="true" useTransitions="true" '+
                          'postToSidebarChecked="true" showBookmark="true" codeBoxHeight="auto" showCodeBox="true" '+
                          'showCloseButton="false" bulletinChecked="true" networksWithCodeBox="*" networksToShow="myspace"></display>'+
                          this.wfcode + '</config>';
    Wildfire.initPost('134221', this.displayname, this.width, this.height, this.pconf );
  },
  showfriendster: function(){
    this.pconf.UIConfig = '<config><display showDesktop="false" showEmail="true" showPost="true" useTransitions="true" '+
                          'postToSidebarChecked="true" showBookmark="true" codeBoxHeight="auto" showCodeBox="true" '+
                          'showCloseButton="false" bulletinChecked="true" networksWithCodeBox="*" networksToShow="friendster"></display>'+
                          this.wfcode + '</config>';
    Wildfire.initPost('134221', this.displayname, this.width, this.height, this.pconf );
  },
  showfacebook: function(){
    this.pconf.UIConfig = '<config><display showDesktop="false" showEmail="true" showPost="true" useTransitions="true" '+
                          'postToSidebarChecked="true" showBookmark="true" codeBoxHeight="auto" showCodeBox="true" '+
                          'showCloseButton="false" bulletinChecked="true" networksWithCodeBox="*" networksToShow="facebook"></display>'+
                          this.wfcode + '</config>';
    Wildfire.initPost('134221', this.displayname, this.width, this.height, this.pconf );
  }
});

function showSelection(){
  $('divWildfirePost').setStyle('display', 'none');
  $('shareSelection').setStyle('display', 'block');
}

function showAll(){
  $('sharetitle').innerHTML = getText("flash_js_SelectWhereToPostWidget");
  $('divWildfirePost').setStyle('display', 'block');
  $('shareSelection').setStyle('display', 'none');
  widgetshare.showall();
}
function showFacebook(){
  $('sharetitle').innerHTML = getText("flash_js_AutomaticallyPostToFacebook");
  $('divWildfirePost').setStyle('display', 'block');
  $('shareSelection').setStyle('display', 'none');
  widgetshare.showfacebook();
}
function showMyspace(){
  $('sharetitle').innerHTML = getText("flash_js_AutomaticallyPostToMySpace");
  $('divWildfirePost').setStyle('display', 'block');
  $('shareSelection').setStyle('display', 'none');
  widgetshare.showmyspace();
}
function showFriendster(){
  $('sharetitle').innerHTML = getText("flash_js_AutomaticallyPostToFriendster");
  $('divWildfirePost').setStyle('display', 'block');
  $('shareSelection').setStyle('display', 'none');
  widgetshare.showfriendster();
}
function showGaia(){
  $('sharetitle').innerHTML = getText("flash_js_PostToGAIA");
  $('divWildfirePost').innerHTML = getText("flash_js_GAIAInstructions") +"<p/></p>"+
                                   '<input type="text" style="width:400px;height:22px;" value="'+$('swfcode').innerHTML+'">';
  $('divWildfirePost').setStyle('display', 'block');
  $('shareSelection').setStyle('display', 'none');
}

/**********************************************
* Flash Comment Section
**********************************************/

function deleteComment( id ){
  document.deletecomment.commentId.value = id;
  confirmSubmit( document.deletecomment, null, null, getText("flash_js_AreYouSureDeleteComment") );
}

function postComment( form ){
  var c = trim( form.comment.value );
  if( c.length == 0 ){
    dialogAlertTimeout( getText("flash_js_CommentFieldCannotBeBlank"), 2000 );
    return false;
  }
  form.submit();
  return false;
}

/**********************************************
* Flash Rank
**********************************************/
function rankFlashWidget( rank, id, params ){
  var json = eval( '(' + params + ')' );
  var ajax = new Ajax( null, ajaxError );
  var uri = "/flash/rankflashwidget!ajax.action?widgetId="+json.id+"&rank="+rank;
  ajax.get( uri, null, false );
  dialogAlertTimeout(getText("flash_js_ThanksForRankingWidget"), 2000 );
}

/**********************************************
* Flash Code Posting
**********************************************/
function showInstructions( col, instructions ){
  $$('#site_body_instructions .instr').each( function(el){ el.setStyle('display', 'none'); } );
  $$('#site_list .choice').each( function(el){ el.removeClass('sel'); } );
  $( instructions + "_instructions" ).setStyle('display', 'block');
  $(col).addClass('sel');
  if( instructions == 'other' ) widgetshare.showall();
  if( instructions == 'friendster' ) hideFriendsterManualPost()
}
function showFriendsterManualPost(){
  $('friendster_auto').setStyle('display', 'none');
  $('friendster_manual').setStyle('display', 'block');
  widgetsharePost.showspecialpostonly( 400, 200 );
}
function hideFriendsterManualPost(){
  $('friendster_auto').setStyle('display', 'block');
  $('friendster_manual').setStyle('display', 'none');
}

