YAHOO.namespace("com.speedbit");

// BEGIN ListItem SUBCLASS //
YAHOO.widget.ListItem = function(el, userConfig) {
  if (arguments.length > 0) {YAHOO.widget.ListItem.superclass.constructor.call(this, el, userConfig);}
}

// Inherit from YAHOO.widget.Module
YAHOO.extend(YAHOO.widget.ListItem, YAHOO.widget.Module);

YAHOO.widget.ListItem.viewClass = ['li_v', 'li_d', 'li_t']

// Initialize ListItem
YAHOO.widget.ListItem.prototype.init = function(el, userConfig) {
  // initialize superclass
  YAHOO.widget.ListItem.superclass.init.call(this, el);
  this.beforeInitEvent.fire(YAHOO.widget.ListItem);
  if (userConfig) {this.cfg.applyConfig(userConfig, true);}

  // parse the data passed from the server  
  this.parseData();

  // subscribe to render event
  this.renderEvent.subscribe(function() {
    var html = this.getHTML();
    this.setBody(html);
    
    this.element.removeAttribute('style');
    
    if (this.element.className)
      this.element.className = YAHOO.widget.ListItem.viewClass[this.currentView];
    
  }, this, true);
  // fire the init event ... we are ready
  this.initEvent.fire(YAHOO.widget.ListItem);
};

// Set up the ListItem's properties
YAHOO.widget.ListItem.prototype.initDefaultConfig = function() {
  YAHOO.widget.ListItem.superclass.initDefaultConfig.call(this);
  this.cfg.addProperty("viewType",{ handler:this.configViewType, suppressEvent:true });
};

// Handler executed when the "id" property is modified
YAHOO.widget.ListItem.prototype.configViewType = function(type, args, obj) {
  this.currentView=args;
};

YAHOO.widget.ListItem.prototype.parseData = function() {
  var root = YAHOO.util.Dom.get(this.id);
  if (root==null || root==undefined)
    root = YAHOO.util.Dom.get("lstviewer");
  // get all data elements
  var val, id, item, items= YAHOO.util.Dom.getElementsByClassName('data',null,root);
  
  for (var i=0,n=items.length;i<n;i++) {
    item = items[i];
    id = this.getNameFromId(item.getAttribute('id'));
    if (id==null) continue; // can't happen but...
    if (id == 'tag' || id == 'cat') {
      // get array of data
      val = this.getDataArray(item);
      for (var j=0,nn=val.length;j<nn;j++) val[j]=this.fix(val[j]);
    } else {
      if (!item.firstChild) // if no value
        val='';
      else
        val = item.firstChild.nodeValue;
    }
    val = this.fix(val);
    try {
      eval('this.'+id+'=\''+val+'\'');
    } catch(e) {
      //alert(e);
    }
  }
};

YAHOO.widget.ListItem.prototype.getHTML = function() {
  var title = this.title;
  var shortTitle = this.shortTitle;
  var shortdesc  = this.shortDesc;
  var body;
  
  if (this.currentView == 0) {
    body =
      '<div class="info">'+
        '<div class="title"><a target=\"video\" href="'+this.url+'" class="titlelink">'+title+'</a></div>'+
        '<div class="desc">'+this.description+'</div>'+
        '<div class="duration"><strong>Duration:</strong> '+this.duration+'</div>' +
        '<div class="published"><strong>Published:</strong> '+this.published.substring(0,this.published.indexOf('T'))+'</div>' +
        '<div class="duration"><strong>Popularity:</strong> '+this.popularity+'</div>' +
        '<div class="site">'+this.site+'</div>'+
      '</div>';
  } else if (this.currentView == 1) {
    body =
      '<div class="imgBox">'+
        '<div class="imgWrapper" id="wrapper_'+this.id+'">'+
          '<a target=\"video\" href="'+this.url+'">'+
            '<img onerror="this.onerror=null;this.src=\'/Images/na.gif\'" src="'+this.img+'" class="img" title="'+title+'" />'+
          '</a>'+
        '</div>'+
      '</div>'+
      '<div class="info">'+
        '<div class="title"><a target=\"video\" href="'+this.url+'" class="titlelink">'+title+'</a></div>'+
        '<div class="desc">'+this.dvshortDesc+'</div>' +
        '<div class="duration">'+this.duration+'</div>' +
        '<div class="published">'+this.published.substring(0,this.published.indexOf('T'))+'</div>' +
        '<div class="site">'+this.site+'</div>'+
      '</div><div class="clearall"></div>';
  } else {
    body =
      '<div class="imgBox">'+
        '<div class="imgWrapper" id="wrapper_'+this.id+'">'+
          '<a target=\"video\" href="'+this.url+'">'+
            '<img onerror="this.onerror=null;this.src=\'/Images/na.gif\'" src="'+this.img+'" class="img" title="'+title+'" />'+
          '</a>'+
        '</div>'+
      '</div>'+
      '<div class="info">'+
        '<div class="title"><a target=\"video\" href="'+this.url+'" class="titlelink">'+shortTitle+'</a></div>'+
        '<div class="site">'+this.site+'</div>'+
      '</div><div class="clearall"></div>';
  }
  return body;
};

YAHOO.widget.ListItem.prototype.fix = function(x) {
  if (typeof x == "string") {
    return x.replace(/\'/g, "\\'");
  }
  return x;
};

YAHOO.widget.ListItem.prototype.getDataArray = function(elem) {
  var ret=new Array(), items = elem.getElementsByTagName('span');
  
  for (var i=0,n=items.length;i<n;i++) {
    ret[i] = items[i].firstChild.nodeValue;
  }
  return ret;
};
YAHOO.widget.ListItem.prototype.getNameFromId = function(name) {
  var pos = name.indexOf('_');
  if (pos == -1) return null;
  return name.substring(0, pos);
};

// END ListItem SUBCLASS







// BEGIN ListItemViewer SUBCLASS //
YAHOO.widget.ListItemViewer = function(el, userConfig) {
  if (arguments.length > 0) {YAHOO.widget.ListItemViewer.superclass.constructor.call(this, el, userConfig);}
}
// Inherit from YAHOO.widget.Module
YAHOO.extend(YAHOO.widget.ListItemViewer, YAHOO.widget.Module);

// Define the CSS class for the ListItemViewer
YAHOO.widget.ListItemViewer.CSS_LISTITEMVIEWER = "lstviewer";
YAHOO.widget.ListItemViewer.DEF_VIEW_TYPE = 1;

// Initialize ListItemViewer
YAHOO.widget.ListItemViewer.prototype.init = function(el, userConfig) {
  var oThis = this;
  // init superclass
  YAHOO.widget.ListItemViewer.superclass.init.call(this, el);
  
  this.beforeInitEvent.fire(YAHOO.widget.ListItemViewer);
  YAHOO.util.Dom.addClass(this.innerElement, YAHOO.widget.ListItemViewer.CSS_LISTITEMVIEWER);
  if (userConfig) {this.cfg.applyConfig(userConfig, true);}
  
  var currentpath = ( document.URL.indexOf('?') != -1 ) ? document.URL.substring(0,document.URL.indexOf('?') - 1) : document.URL;
  
  if ( this.GetCookie ('viewtype_' + currentpath)==undefined || this.GetCookie ('viewtype_' + currentpath) == null )
  {
    this.viewSelector = new YAHOO.com.speedbit.ViewSelector('view-selector', oThis, userConfig["defaultView"]);
  }
  else
  {
    this.viewSelector = new YAHOO.com.speedbit.ViewSelector('view-selector', oThis, this.GetCookie ('viewtype_' + currentpath));
  }
  
  this.items = new Array();
  
  this.collectItems();
  
  this.renderEvent.subscribe(function() {
    if (this.element.className)
      this.element.className = 'lstviewer';
      
    if(this.items.length == 0) {
      this.body.innerHTML = "No results found...";
    }
  }, this, true);

  this.initEvent.fire(YAHOO.widget.ListItemViewer);
};

// Set up the ListItemViewer's properties
YAHOO.widget.ListItemViewer.prototype.initDefaultConfig = function() {
  YAHOO.widget.ListItemViewer.superclass.initDefaultConfig.call(this);
  this.cfg.addProperty("defaultView",{ handler:this.configDefaultView, suppressEvent:true });
};

// Handler executed when the "id" property is modified
YAHOO.widget.ListItemViewer.prototype.configDefaultView = function(type, args, obj) {
  this.defaultView=args;
};


YAHOO.widget.ListItemViewer.prototype.sliderLeft = function(e) {
  this.viewSelector.sliderLeft(e);
};

YAHOO.widget.ListItemViewer.prototype.sliderRight = function(e) {
  this.viewSelector.sliderRight(e);
};

YAHOO.widget.ListItemViewer.prototype.sliderChanged = function(newVal) {
  var root = YAHOO.util.Dom.get(this.id);
  if (root==null || root==undefined)
    root = YAHOO.util.Dom.get("lstviewer");
  var item;
  
  var currentpath = ( document.URL.indexOf('?') != -1 ) ? document.URL.substring(0,document.URL.indexOf('?') - 1) : document.URL;
  this.SetCookie('viewtype_' + currentpath, newVal, 300, '/', '', '' );
  if (root != null && root != undefined)
    root.style.display = "none";
  
  for (var i=0,n=this.items.length;i<n;i++) {
    item = this.items[i];
    item.configViewType(1, newVal, this);
    item.render();
  }
  
  if (root != null && root != undefined)
    root.style.display = "block";
};

YAHOO.widget.ListItemViewer.prototype.collectItems = function() {
  //var root = document.getElementById(this.id);
  var root = document.getElementById("lstviewer");
  // get all data elements
  var id, item, items= YAHOO.util.Dom.getElementsByClassName('listitem','div',root);
  
  for (var i=0,n=items.length;i<n;i++) {
    item = items[i];
    id = item.getAttribute('id');
    this.items[i] = new YAHOO.widget.ListItem(id, {viewType : this.viewSelector.getCurrentView()});
    item.removeAttribute('style');
    this.items[i].render();
  }
  
  if (root != null && root != undefined)
    root.style.display = "block";
};

// this function gets the cookie, if it exists
  YAHOO.widget.ListItemViewer.prototype.GetCookie = function ( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
      return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
  };

  YAHOO.widget.ListItemViewer.prototype.SetCookie = function ( name, value, expires, path, domain, secure ) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    // if the expires variable is set, make the correct expires time,
    // the current script below will set it for x number of days,
    // to make it for hours, delete * 24, for minutes, delete * 60 * 24
    if ( expires ) {expires = expires * 1000 * 60 * 60 * 24;}
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name + "=" +escape( value ) +
      ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
      ( ( path ) ? ";path=" + path : "" ) +
      ( ( domain ) ? ";domain=" + domain : "" ) +
      ( ( secure ) ? ";secure" : "" );
  };
  
  // this deletes the cookie when called
  YAHOO.widget.ListItemViewer.prototype.DeleteCookie = function ( name, path, domain ) {
    if ( this.GetCookie( name ) ) {
      document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") +
      ( ( domain ) ? ";domain=" + domain : "" ) +
      ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
  };
// END ListItemViewer SUBCLASS //


/**
* @class 
* The ViewSelector class manages a view selection
* @param {object|string} selectorElementID The element ID (id name or id object) of the DIV that will become a selector
* @param {object} cfg The configuration object literal containing the configuration that should be set for this module.
* @constructor
*/
YAHOO.com.speedbit.ViewSelector = function(selectorElementID, owner, defaultView) {
    this.init(selectorElementID, owner, defaultView);
};


YAHOO.com.speedbit.ViewSelector.prototype = {
  viewTypes : ['List View', 'Details View', 'Thumbnails View'],
  defaultView : 2,
  currentView : 2,
  sliderSteps : 24,
  leftSelector: null,
  rightSelector: null,
  slider : null,
  owner : null,

  init: function(selectorElementID, owner, defaultView) {

    var oThis = this;
    
    this.owner = owner;
    
    if (defaultView != "undefined") {
      this.defaultView = defaultView;
      this.currentView = defaultView;
    }

    // CSS style classes
    this.selectorElementID = selectorElementID;
    this.selectorElem = YAHOO.util.Dom.get(selectorElementID);

    // Create the config object
    this.cfg = new YAHOO.util.Config(this);

    this.slider =  YAHOO.widget.Slider.getHorizSlider("sliderbg", "sliderthumb", 0, 48, this.sliderSteps);

    this.slider.setValue(this.defaultView * this.sliderSteps);
    
    this.slider.subscribe("slideEnd", function() {
       oThis.setSliderPos(oThis.slider.getValue());
       oThis.show();
    });
  },
  
  show : function() {
    this.selectorElem.style.visibility='visible';
  },
  
  hide : function() {
    this.selectorElem.style.visibility='hidden';
  },
  
  getCurrentView : function() {
    return this.currentView;
  },

  setSliderPos : function(val) {
    if (this.currentView == val) return;
    
    if (val==0) {
      this.currentView = 0;
    } else if (val==24) {
      this.currentView = 1;
    } else
      this.currentView = 2;
     
    YAHOO.util.Dom.get('sliderbg').title = this.viewTypes[this.currentView];
    // notify parent on change
    this.owner.sliderChanged(this.currentView);
  },
  
  sliderLeft : function(el) {
    if (this.currentView > 0) {
      this.slider.setValue(this.slider.getValue()-24);
    } 
  },
  
  sliderRight : function(el) {
    if (this.currentView < 2) {
      this.slider.setValue(this.slider.getValue()+24);
    } 
  }
};
