/************** tools ********************/
function generateLine()
{
  var password = "";
  var alphaNum = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var length = parseInt(5+Math.random()*4);
  for(var a = 0; a < 16; a++){
      password = password + alphaNum.charAt(parseInt(Math.random()*alphaNum.length));
  }
  return password;
}
function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}
function toHex( str ){
  if( str.indexOf("0x") == 0 ){
    return str.substr(2,str.length);
  }else{
    return str;
  }
}
function flipImage(obj, img){
  obj.src  = img;
}
function trim(sString)
{
  if( !sString ) return sString;

  while (sString.substring(0,1) == ' '){
    sString = sString.substring(1, sString.length);
  }
  while (sString.substring(sString.length-1, sString.length) == ' '){
    sString = sString.substring(0,sString.length-1);
  }
  return sString;
}
function fix4param( param ){
  return  param.replace(/\\\'/g, "'").replace(/"/g, "&quot;").replace(/'/g, "\\\'").replace(/&#039;/g, "\\\'");
}
var Map = new Class({
  initialize:
  function(options){
      this.map = new Object();
  },
  put:
  function( name, obj ){
      eval('this.map.'+name+' = obj');
  },
  get:
  function( name ){
      return eval('this.map.'+name);
  }
});

var MyBrowser = new Class({
  initialize: function(){
    var ua, s, i;
    this.isIE      = false
    this.isNS      = false;
    this.isSafari  = false;
    this.isChrome  = false;
    this.isFirefox = false;
    this.isGecko   = false;
    this.isOther   = false;

    this.version = null;
    ua = navigator.userAgent;
    s = "MSIE";
    if((i = ua.indexOf(s)) >= 0){
      this.isIE = true;
      this.version = parseFloat(ua.substr(i + s.length));
      return;
    }
  
    s = "Chrome/"
    if((i = ua.indexOf(s)) >= 0){
      this.isChrome = true;
      this.version = parseFloat(ua.substr(i + s.length));
      return;
    }
    
    s = "Firefox/";
    if((i = ua.indexOf(s)) >= 0){
      this.isFirefox = true;
      this.version = parseFloat(ua.substr(i + s.length));
      return;
    }

    s = "Netscape6/";
    if((i = ua.indexOf(s)) >= 0){
      this.isNS = true;
      this.version = parseFloat(ua.substr(i + s.length));
      return;
    }

    s = "Safari/";
    if((i = ua.indexOf(s)) >= 0){
      this.isSafari = true;
      s = "Version/";
      i = ua.indexOf(s);
      if( i >= 0 ){
        this.version = parseFloat(ua.substr(i + s.length));
      }
      return;
    }

    // Treat any other "Gecko" browser as NS 6.1.
    s = "Gecko";
    if((i = ua.indexOf(s)) >= 0){
      this.isGecko = true;
      this.version = parseFloat(ua.substr(i + s.length));
      return;
    }
   
    isOther = true;
  },
  getAdjustedCenter: function(){
    var obj = this.getCenter();
    var scroll = $(window).getScroll();
    obj.x = obj.x + scroll.x;
    obj.y = obj.y + scroll.y;
    return obj;
  },
  getCenter: function(){
    var o = $(window).getCoordinates();
    var obj = new Object();
    obj.x = o.width / 2;
    obj.y = o.height / 2;
    return obj;
  }, 
  getWindowDimensions: function(){
     return $(window).getCoordinates();
  },
  getPageDimensions: function(){
     var obj = $(window).getScrollSize();
     obj.height = obj.y;
     obj.width  = obj.x;
     return obj;
   }
});

var browser = new MyBrowser();

function checkUnsupportedBrowser(){  
  var unsupported_check = Cookie.read("unsupported-check");
  if( unsupported_check != null && unsupported_check == "true" ) return;

  var supported = false;
  var msg = null;

  if( browser.isChrome  ) supported = true;
  else if( browser.isIE && browser.version > 6 ){
    supported = true;
  }else if( browser.isIE && browser.version <= 6 ){
    msg = "Internet Explorer 7+ is supported. Please upgrade your browser.";
  }else if( browser.isFirefox && browser.version >= 2 ){
    supported = true;
  }else if( browser.isFirefox && browser.version < 2 ){
    msg = "Firefox 2+ is supported. Please upgrade your browser.";
  }else if( browser.isSafari && browser.version >= 3 ){
    supported = true;
  }else if( browser.isSafari && browser.version < 3 ){
    msg = "Safari 3+ is supported. Please upgrade your browser.";
  }

  if( !supported ){
    open_unsupported( msg );
  }
}

var unsupported_open = false;

function open_unsupported( msg ){
  
  if( msg == null ) msg = "";
  if( unsupported_open ) return;
  unsupported_open = true;
  showMask();

  var width = 500;
  var height = 320;
  var container = document.createElement('div');
  $(container).setAttribute("id", "unsupported_window");
  $(container).setStyle("background-color", "#CCC");
  $(container).setStyle("width", width+"px");
  $(container).setStyle("height", height+"px");
  $(container).setStyle("border", "1px solid #1644c7");
  $(container).setStyle("position", "absolute");
  $(container).setStyle("z-index", "2000");
  var coor = browser.getAdjustedCenter();
  $(container).setStyle("top", coor.y - (height/2) );
  $(container).setStyle("left", coor.x - (width/2) );

  var html = '<table class="iframebar" cellpadding="4" width="100%"><tr>'+
             '<td><b>Flashwidgetz Browser Support</b></td>'+
             '<td align="right">'+
             '<a href="#" class="whitelink" onclick="close_unsupported();return false">Close</a></td>'+
             '</tr></table>';
  html += '<iframe id="loginframe" scrolling="no" frameborder="0" style="background-color:#CCC" '+
          ' width="'+(width-5)+'" height="'+(height-30)+'" src="/iframe/unsupportedbrowser.jsp?msg= '+ encodeURIComponent( msg ) +'"></iframe>';
  $(container).innerHTML = html;
  document.getElementsByTagName("body")[0].appendChild( container );
}

function close_unsupported(){
 if( unsupported_open ){
    hideMask();
    Cookie.write("unsupported-check", true, { domain:'flashwidgetz.com', path:'/', duration:365 } );
    document.getElementsByTagName("body")[0].removeChild( $('unsupported_window') );
    unsupported_open = false;
  }
}


////////////////////

function parseYoutubeVideoResult( videos ){
  var VideoArray = new Array();
  var item;
  for( var a = 0; a < videos.length; a++ ){
    item = new Object();
    item.link = videos[a].link;
    item.title = videos[a].title;
    item.description = videos[a].description;
    item.duration = videos[a]['media:group']['yt:duration'].seconds;

    var duration = parseInt( item.duration );
    var min = Math.floor( duration / 60 );
    var secs = duration % 60;
    if( min < 10 ) min = "0"+min;
    if( secs < 10 ) secs = "0"+secs;
    item.time = min+":"+secs;

    if( videos[a]['yt:noembed'] ) item.embed = false;
    else item.embed = true;

    var thumbnails = videos[a]['media:group']['media:thumbnail'];
    for( var b = 0; b < thumbnails.length; b++ ){
      if( thumbnails[b].url.match(/1.jpg/) ){
        item.thumbnail1 =  thumbnails[b].url;
      }else if( thumbnails[b].url.match(/2jpg/) ){
        item.thumbnail2 =  thumbnails[b].url;
      }
    }
    VideoArray.push( item );
  }
  return VideoArray;
}

function doCommonSearchMediaConsole(){
  var query = trim( $('global_search_query').value );
  if( query == '' || query.length == 0 ) return;
  if( GLOBALSEARCHTYPE == null ) return;
  var searchtype = $('global_search_type').value;
 
  var cookie = new Hash.Cookie('searchoptions', {duration:1, domain: 'flashwidgetz.com', path: '/'} );
  var currentsearchtype = cookie.get('searchtype');

  if( searchtype == 'music' && currentsearchtype == 'video' ){
    cookie.set('searchtype', 'all');
    cookie.set('showvideo', 'false');
  }else if( searchtype == 'video' && currentsearchtype != 'video' ){
    cookie.set('searchtype', 'video');
    cookie.set('showvideo', 'true');
  }

  if( typeof(loadSearchOptions) != 'undefined' ) loadSearchOptions();
  if( $('query') != null && typeof(audiosearch) != 'undefined' && ( searchtype == 'music' ||  searchtype == 'video' ) ){
    $('query').value = query;
    audiosearch();
    if( typeof(showsmallvideo) != 'undefined' ) showsmallvideo();
  }else{
    doCommonSearch();
  }
}

function doCommonSearch( id_query, id_searchtype ){
  if( GLOBALSEARCHTYPE == null ) return;

  var query      = (id_query == null) ? $('global_search_query').value : $( id_query ).value;
  var searchtype = (id_searchtype == null) ? $('global_search_type').value : $( id_searchtype ).value;

  query = trim ( query );
  searchtype = trim( searchtype );

  if( query == '' || query.length == 0 ) return;
  query = query.replace("/", "%252F" );

  var cookie = new Hash.Cookie('searchoptions', {duration:1, domain: 'flashwidgetz.com', path: '/'} );
  if( searchtype == 'artist' ){
    cookie.set('searchtype', 'all');
    cookie.set('showvideo', 'false');
    document.location.href = "/artist/"+ query;
  }else if( searchtype == 'music' ){
    cookie.set('searchtype', 'all');
    cookie.set('showvideo', 'false');
    document.location.href = "/musicsearch/"+ query;
  }else if( searchtype == 'video' ){
    cookie.set('searchtype', 'video');
    cookie.set('showvideo', 'true');
    document.location.href = "/musicsearch/video/"+ query;
  }
}

function setup_mediapopup_playlistid( id, playlistId ){
  $( id ).onclick = function( playlistId ){ 
      window.open ( "/standalone/" + playlistId, "popupwindow", "status=1,width=505,height=679");
      return false;
  }.pass( playlistId );
}

function isEmail(string) {
  if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
    return true;
  else
    return false;
}

function writeToStatusDiv( msg, error ){
  $('statusdiv').innerHTML = msg;
  if( error == true ){
    $('statusdiv').addClass('statusdiv_active_error');    
  }else{
    $('statusdiv').addClass('statusdiv_active_confirm');
  }
}
function clearStatusDiv(){
  $('statusdiv').removeClass('statusdiv_active_error');
  $('statusdiv').removeClass('statusdiv_active_confirm');
  $('statusdiv').innerHTML = '';
}

function initGlobal(){
  if( $('global_email') ){
    $('global_email').addEvent('focus', function(){
      if( this.value == 'Email' ){ this.value = ''; }
    });
    $('global_email').addEvent('blur', function(){ 
      if( this.value == '' ){ this.value = 'Email'; }
    });
  }
  if( $('global_password') ){
    $('global_password').addEvent('focus', passwordfocus );
    $('global_password').addEvent('blur', passwordblur );
  }
  var myMenu = new UvumiDropdown("global-dropdown-menu");
}

function passwordblur(){
  if( this.value == '' ){
    var el = this;
    try {
      this.type = 'text';  
      this.setAttribute( "type", "text" );
    } catch (e) {
      el = document.createElement('input');
      el.setAttribute('type', 'text');
      el.setAttribute('id', this.getAttribute('id') );
      this.parentNode.replaceChild( el, this ); 
      $(el).addEvent('focus', passwordfocus );
      $(el).addEvent('blur', passwordblur );
    }    
    el.value = 'Password';
  }
}

function passwordfocus(){
  if( this.value == 'Password' ){
    var el = this;
    try{
      this.type = "password";
      this.setAttribute( "type", "password" );
    } catch (e) {
      el = document.createElement('input'); 
      el.setAttribute('type', 'password'); 
      el.setAttribute('id', this.getAttribute('id') ); 
      this.parentNode.replaceChild(el, this); 
      $(el).addEvent('focus', passwordfocus ); 
      $(el).addEvent('blur', passwordblur ); 
    }
    el.value = ''; 
    if( el.setSelectionRange && ( browser.isChrome || browser.isSafari ) ) el.setSelectionRange( 0, 0 );
    else { el.focus(); el.select(); }
    return true;
  }
}

String.prototype._$$split = String.prototype._$$split || String.prototype.split;

String.prototype.split = function (s /* separator */, limit) {
    // if separator is not a regex, use the native split method
    if (!(s instanceof RegExp))
        return String.prototype._$$split.apply(this, arguments);

    var flags = (s.global ? "g" : "") + (s.ignoreCase ? "i" : "") + (s.multiline ? "m" : ""),
        s2 = new RegExp("^" + s.source + "$", flags),
        output = [],
        origLastIndex = s.lastIndex,
        lastLastIndex = 0,
        i = 0, match, lastLength;

    /* behavior for limit: if it's...
    - undefined: no limit
    - NaN or zero: return an empty array
    - a positive number: use limit after dropping any decimal
    - a negative number: no limit
    - other: type-convert, then use the above rules
    */
    if (limit === undefined || +limit < 0) {
        limit = false;
    } else {
        limit = Math.floor(+limit);
        if (!limit)
            return [];
    }

    if (s.global)
        s.lastIndex = 0;
    else
        s = new RegExp(s.source, "g" + flags);

    while ((!limit || i++ <= limit) && (match = s.exec(this))) {
        var emptyMatch = !match[0].length;

        // Fix IE's infinite-loop-resistant but incorrect lastIndex
        if (emptyMatch && s.lastIndex > match.index)
            s.lastIndex--;

        if (s.lastIndex > lastLastIndex) {
            // Fix browsers whose exec methods don't consistently return undefined for non-participating capturing groups
            if (match.length > 1) {
                match[0].replace(s2, function () {
                    for (var j = 1; j < arguments.length - 2; j++) {
                        if (arguments[j] === undefined)
                            match[j] = undefined;
                    }
                });
            }

            output = output.concat(this.slice(lastLastIndex, match.index));
            if (1 < match.length && match.index < this.length)
                output = output.concat(match.slice(1));
            lastLength = match[0].length; // only needed if s.lastIndex === this.length
            lastLastIndex = s.lastIndex;
        }

        if (emptyMatch)
            s.lastIndex++; // avoid an infinite loop
    }

    // since this uses test(), output must be generated before restoring lastIndex
    output = lastLastIndex === this.length ?
        (s.test("") && !lastLength ? output : output.concat("")) :
        (limit ? output : output.concat(this.slice(lastLastIndex)));
    s.lastIndex = origLastIndex; // only needed if s.global, else we're working with a copy of the regex
    return output;
};
