/*
 * Author; Gal Nitzan, gnitzan@speedbit.com
 * Date: 01/01/2007
 * 
 * Video thumbnails viewer
 */


var ThumbViewer = {
  DEBUG : false,
  DEFAULT_AJAX_SERVER_URL : "http://nutchws1.speedbit.com:8080/opensearch",
  DEFAULT_QUERY : "tags:fun",
  DEFAULT_PAGER_FONT_MAX : 20,
  DEFAULT_PAGER_FONT_MIN : 13,
  DEFAULT_IMG_PER_ROW_MAX : 6,
  DEFAULT_IMG_PER_ROW : 5,
  DEFAULT_IMG_ROWS : 8,
  DEFAULT_STAGE_DELAY : 200, // delay 200 ms
  DEFAULT_EXPAND_TIMEOUT : 20, // 20 ms
  DEFAULT_EXPAND_HORIZ_PERCENT : 30,
  DEFAULT_EXPAND_VERT_PERCENT : 20,
  stageDelay : null,
  expandTimeout : null,
  ajaxServerUrl : null,
  initialized : false,
  currentQuery : null,
  imgPerRowMax : null,
  imgRowsMax : null,
  imgPerRow : null,
  totalHits : 0,
  curPage : 1,
  slider : null,
  imagesDiv : null,
  showCaption : true,
  divBorder : 0,
  divMargin : 0,
  divPadding : 0,
  boxBorder : 0,
  boxMargin : 0,
  boxPadding : 0,
  pagerFontMax : null,
  pagerFontMin : null,
  pagerFontCurrent : 0,
  debugDiv : null,
  expandHorizP : null,
  expandVertP : null,
  showNumbers : true,
  styleParsed : false,

  // Initialize all values to default. Run only once.
  Init : function() {
    if (this.initialized) return;
    if (this.expandHorizP==null) this.SetExpandHorizPercent(this.DEFAULT_EXPAND_HORIZ_PERCENT);
    if (this.expandVertP==null) this.SetExpandVertPercent(this.DEFAULT_EXPAND_VERT_PERCENT);
    if (this.pagerFontMin==null) this.SetPagerFontMin(this.DEFAULT_PAGER_FONT_MIN);
    if (this.pagerFontMax==null) this.SetPagerFontMax(this.DEFAULT_PAGER_FONT_MAX);
    if (this.ajaxServerUrl==null) this.SetAjaxServerUrl(this.DEFAULT_AJAX_SERVER_URL);
    if (this.imgPerRowMax==null) this.SetImgPerRowMax(this.DEFAULT_IMG_PER_ROW_MAX);
    if (this.imgRowsMax==null) this.SetImgRows(this.DEFAULT_IMG_ROWS);
    if (this.stageDelay==null) this.SetStageDelay(this.DEFAULT_STAGE_DELAY);
    if (this.expandTimeout==null) this.SetExpandTimeout(this.DEFAULT_EXPAND_TIMEOUT);

    // define a DOMParser object if doesn't exists on IE
    if (typeof DOMParser == "undefined") {
       DOMParser = function () {}

       DOMParser.prototype.parseFromString = function (str, contentType) {
          if (typeof ActiveXObject != "undefined") {
             var d = new ActiveXObject("MSXML.DomDocument");
             d.loadXML(str);
             return d;
          } else if (typeof XMLHttpRequest != "undefined") {
             var req = new XMLHttpRequest;
             req.open("GET", "data:" + (contentType || "application/xml") +
                             ";charset=utf-8," + encodeURIComponent(str), false);
             if (req.overrideMimeType) {
                req.overrideMimeType(contentType);
             }
             req.send(null);
             return req.responseXML;
          }
       }
    }

    // now try to see if we saved the number of images per row in the cookies.
    // if we did set it to current else, use the default
    this.imgPerRow = this.GetCookie( 'imagesPerRow' );
    if ( this.imgPerRow==undefined || this.imgPerRow == null ) {
      this.SetImgPerRow(this.DEFAULT_IMG_PER_ROW);
    }
    if (this.imgPerRow > this.imgPerRowMax) {
      this.DeleteCookie( 'imagesPerRow' );
      this.imgPerRow = this.imgPerRowMax;
    }
    //this.GetImagesDivParams();
    //this.InitializeSlider();
    //this.SetSliderText();

    var myGlobalHandlers = {
      onCreate: function(){Element.show('downloading');},
      onComplete: function(){if(Ajax.activeRequestCount == 0){Element.hide('downloading');}}
    };
  
    //Ajax.Responders.register(myGlobalHandlers);

    this.initialized = true;
  },

  SendQuery : function(query, dup) {
    this.SendAjaxRequest(query,0,dup,this.imgPerRow*this.imgRowsMax);
  },

  SetSliderText : function () {
    var text = this.imgPerRow;
    var elem = $('imgperrow'); elem.innerHTML = ''; elem.innerHTML = text;

    if(this.imgPerRow == 1) {
      elem=$('imgless');
      elem.style.color="gray";
      elem.style.cursor="default";
    } else {
      elem=$('imgless');
      elem.style.color="white";
      elem.style.cursor="cursor:hand;cursor:pointer;";
    }

    if(this.imgPerRow == this.imgPerRowMax) {
      elem=$('imgmore');
      elem.style.color="gray";
      elem.style.cursor="default";
    } else {
      elem=$('imgmore');
      elem.style.color="white";
      elem.style.cursor="cursor:hand;cursor:pointer;";
    }

  },

  LessImagesOnRow : function (obj) {
    if(this.imgPerRow <= 1) return;
    ThumbViewer.ScaleIt(parseInt(this.imgPerRow-1));
  },

  MoreImagesOnRow : function (obj) {
    if (this.imgPerRow >= this.imgPerRowMax) return;
    ThumbViewer.ScaleIt(parseInt(this.imgPerRow+1));
  },

  InitializeSlider : function() {
    var sliderVals = new Array();
    for (var i = 0; i < this.imgPerRowMax; i++){sliderVals[i]=i+1;}
    this.slider = new Control.Slider('handle1','track1',
      {range:$R(1,this.imgPerRowMax),values:sliderVals,sliderValue:this.imgPerRow});

    this.slider.setValue(this.imgPerRow);

    this.slider.options.onSlide = function(value){
      ThumbViewer.ScaleIt(value);
    }
    this.slider.options.onChange = function(value){
      ThumbViewer.ScaleIt(value);
    }
  },

  SetImgRows : function(val) {this.imgRowsMax = val;},
  SetImgPerRow : function(val) {this.imgPerRow = val;},
  SetImgPerRowMax : function(val) {this.imgPerRowMax = val;},
  SetPagerFontMin : function(val) {this.pagerFontMin = val;},
  SetPagerFontMax : function(val) {this.pagerFontMax = val;},
  SetAjaxServerUrl : function(url) {this.ajaxServerUrl = url;},
  SetExpandTimeout : function(val) {this.expandTimeout = val;},
  SetStageDelay : function(val) {this.stageDelay=val;},
  SetExpandHorizPercent : function(val) {this.expandHorizP=val;},
  SetExpandVertPercent : function(val) {this.expandVertP=val;},
  SetShowNumbers : function(val) {this.showNumbers=val;},
  
  // this function gets the cookie, if it exists
  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 ) );
  },

  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
  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";
    }
  },

  // parse the xml received from server
  ParseResponse : function (response) {
    var item, items, img, a, div, src;
    // use eval to parse Solr's JSON response
    var rsp = eval("("+response+")");
    
    if (this.imagesDiv == null) this.imagesDiv = $("images-div");
  
    this.imagesDiv.innerHTML='';
  
    var divWidth = this.GetScaleImgDivWidth();
  
    // Get the total results
    this.totalHits = rsp.response.numFound;
  
    items = rsp.response.docs;
  
    // Loop over the items
    for (var i = 0 ; i < items.length ; i++) {
      div = document.createElement('div');
      div.id = 'div-'+i;
      div.className = "scale-image";
      div.setAttribute('onmouseover',"ThumbViewer.SetBorderOn(this);");
      div.setAttribute('onmouseout',"ThumbViewer.SetBorderOff(this);");
      div.style.width = divWidth+"px";
  
      this.imagesDiv.appendChild(div);
  
      a = document.createElement('a');
      a.href='#';
      div.appendChild(a);
      img = document.createElement('img');
      a.appendChild(img);
  
      img.title='';
      img.setAttribute("site",'');
      img.setAttribute("views",'');
      img.setAttribute("lnk",'');
      img.setAttribute("duration",'');
      img.id='img'+i;
      img.src=siteHomePath+'/images/na.gif';
      img.style.width='100%';
      img.style.height='100%';
      img.style.border='0px';
      img.setAttribute('onerror',"this.onerror=null;this.src=siteHomePath+'/images/na.gif'");
  
      item = items[i];
      img.title=item.title;
      img.setAttribute("lnk",item.url);
      img.setAttribute("site",item.site);
      img.setAttribute("views",item.popularity);
      img.setAttribute("duration",item.duration);
      src = item.image0;
      if (src != undefined) {img.src = src;}
    }
  
    if (BrowserDetect.browser == 'Explorer') {
      var ht = this.imagesDiv.innerHTML;
      this.imagesDiv.innerHTML = '';
      this.imagesDiv.innerHTML = ht;
    }
  },

  OpenBox : function (divObj) {
  this.ShowStats('OpenBox');
    this.ExpandTimer.CurLevel(1);
    this.ExpandTimer.Start('box');
  },

  CloseBox : function (divObj) {
    this.ShowStats('CloseBox');
    this.ToggleVisibility(divObj,"hidden");
    this.ExpandTimer.CurLevel(2);
    this.ExpandTimer.Stop(true);
    divObj.style.width = "0px";
    divObj.style.height = "0px";
    divObj.innerHTML = "";
  },

  ToggleVisibility : function (obj, state) {obj.style.visibility=state;},

  GetScaleImgDivWidth : function () {
    if (this.imagesDiv==undefined || this.imagesDiv==null) this.imagesDiv = $("images-div");
  
    var w = this.imagesDiv.clientWidth;
    var extra = this.divBorder+this.divMargin+this.divPadding;
  
    var ww = w - (extra*this.imgPerRow);
    var divWidth = (ww / this.imgPerRow).toFixed();
    var add;
    if ((divWidth - (ww / this.imgPerRow)) >= 0)
      divWidth -= 1;
    //alert("w: "+w+"  ww:"+ww+"  divWidth:"+divWidth+"  extra:"+extra);
    return divWidth;//remove padding and border
  },

  ScaleIt : function (v) {
    // delete the cookie if exists and save the value in a new cookie
    ThumbViewer.DeleteCookie('imagesPerRow', '/', '');

	if (v > this.imgPerRowMax) {
		v = this.imgPerRowMax;
	}

    ThumbViewer.SetCookie('imagesPerRow', v, 300, '/', '', '' );
    ThumbViewer.SetImgPerRow(v);
    ThumbViewer.SetSliderText();
  
    if (ThumbViewer.imagesDiv == null) ThumbViewer.imagesDiv = $("images-div");
  
    var divWidth = this.GetScaleImgDivWidth();
  
    var scalePhotos = document.getElementsByClassName('scale-image');
    for (i=0; i < scalePhotos.length; i++) {
      var img = $('img'+i);
      scalePhotos[i].style.width = divWidth+'px';
      scalePhotos[i].style.height = (((divWidth/3)*2).toFixed())+'px';
      img.height=(((divWidth/3)*2).toFixed());
    }
    ThumbViewer.ShowNumbers();
  },

  ShowNumbers : function () {
    if (!this.showNumbers) return;
    // show numbers only on first page
    if (this.curPage != 1) return;
    if (this.currentQuery.indexOf('ctype:video')==-1) return;
    
    var inputs = document.getElementsByClassName('scale-image');
    
    for(var i = 0; i < inputs.length; i++) {
      var obj = $('oimg'+i);
      if (obj != undefined && obj != null) inputs[i].removeChild(obj);
  
      obj = $('onum'+i);
      if (obj != undefined && obj != null) inputs[i].removeChild(obj);
  
      var p = this.GetElemPos(inputs[i]);
  
      var oImg = document.createElement("img");
      oImg.id = 'oimg'+i;
      oImg.style.position = 'absolute';
      oImg.src = siteHomePath+'/Images/Nums/'+(i+1)+'.gif';
      oImg.style.top = (p.y + 5) + "px";
      oImg.style.left= (p.x + 7) + "px";
      inputs[i].appendChild(oImg);
    }
  },

  OnPagerElemOver : function (obj) {
    this.pagerFontCurrent = obj.style.fontSize;obj.style.fontSize = this.pagerFontMax + "px";
  },

  OnPagerElemOut : function (obj){
    if (this.pagerFontCurrent == undefined || this.pagerFontCurrent==null || this.pagerFontCurrent=='')
      obj.style.fontSize = this.pagerFontMin + "px";
    else
      obj.style.fontSize = this.pagerFontCurrent;
  },

  SetBorderOn : function (divObj) {
    var id = divObj.getAttribute('id');
    if (id == undefined) return;
    id = id.substr("div-".length, id.length);

    divObj.style.border = '2px solid white';

    var html='', img = $('img'+id);
    if (img == undefined) return;

    var t = img.title;
    var l = img.getAttribute('lnk');
    var d = img.getAttribute('duration');
    var s = img.getAttribute('site');
    var v = img.getAttribute('views');
    var p = this.GetElemPos(img);

    var block = $("box");
    block.innerHTML = '';

    block.style.width = divObj.style.width;
    block.style.height = divObj.style.height;
    block.style.left = (p.x)+'px';
    block.style.top  = (p.y)+'px';

    // reset obj innerHTML before resetting
    html = "<a href=\"" + l +"\" onclick=\"ThumbViewer.OpenVideoInWindow(this);" +
        "javascript:urchinTracker('/clicks/" + s + "');return false;\" "
        +">" +
      "<img id=\"box-img\" src=\"" + img.src + "\" style=\"width:100%;border:0px;\" " +
      "title=\"" + t + "\" " +
      "duration=\"" + d + "\" " +
      "views=\"" + v + "\" " +
      "site=\"" + s + "\" " +
      " /></a>";

    block.innerHTML = html;
    var myimg = $('box-img');
    block.style.height = (myimg.clientHeight+this.boxBorder+this.boxMargin+this.boxPadding)+"px";
    this.ToggleVisibility(block,'visible');
  },

  // Send a request for to the server
  SendAjaxRequest : function (query,start,hitsPerDup,hitsPerPage) {
	//Element.show('downloading');
    this.ToggleVisibility($('downloading'),'visible');
    // if we haven't initialized yet.
    if (!this.initialized) { alert("Not initialized ERROR!"); return; }
    
    query = query.replace("?","").replace("&","").replace("ctype:video", "");
    
    // save query for further clicks
    this.currentQuery = query;
    // create the query string
    var reqString = "p=solr/select/&wt=json&q=ctype:video "+query+
      ";published desc&fl=title,published,site,url,image0,duration,popularity&rows="+
      hitsPerPage;
    // if we are retrieving next pages... add the start param
    if (start != 0) reqString += "&start="+start;
    // create ajax request using Prototype...
    //alert(reqString);
    var req = new Ajax.Request(
      this.ajaxServerUrl,
      {
        method: 'get',
        parameters: reqString,
        onComplete: ThumbViewer.HandleAjaxResponse
      });
    try {
      if(query==undefined || query=="") query="default";
      urchinTracker("/video/search/" + query );
    } catch(e) {}
  },

  // callback for ajax response
  HandleAjaxResponse : function(response) {
    // create a DOM object from the response string
    //var xmlObj = (new DOMParser()).parseFromString(request.responseText, "text/xml");
    // update the view
    ThumbViewer.UpdateView(response.responseText);
    //Element.hide('downloading');
    ThumbViewer.ToggleVisibility($('downloading'),'hidden');
  },

  // find the actual element position on screen
  GetElemPos : function (element)  {
    var parent = element, p = new Array();
    p.x = parent.offsetLeft;p.y = parent.offsetTop;
    while (parent.offsetParent) {
      parent = parent.offsetParent;p.x += parent.offsetLeft;p.y += parent.offsetTop;
    }
    return p;
  },

  // find all the stylesheets and style elements of this html page
  GetStyleSheets : function () {
    if( document.styleSheets && ( window.ScriptEngine || navigator.taintEnabled )) {
      return document.styleSheets;
    }
    // return empty array if dom not supported
    if( !document.getElementsByTagName ) { return []; }
    for( var x = 0, Lt = document.getElementsByTagName('link'), os = []; Lt[x]; x++ ) {
      var rel = Lt[x].rel ? Lt[x].rel : Lt[x].getAttribute ? Lt[x].getAttribute('rel') : '';
      if( typeof( rel ) == 'string' && rel.toLowerCase().indexOf('style') + 1 ) { os[os.length] = Lt[x]; }
    }
    for( var x = 0, St = document.getElementsByTagName('style'); St[x]; x++ ) { os[os.length] = St[x]; }

    return os;
  },

  // update view. xmlObj is an xml object
  UpdateView : function (response) {
	ThumbViewer.GetImagesDivParams();
    ThumbViewer.SetSliderText();
    ThumbViewer.ParseResponse(response);
    ThumbViewer.ScaleIt(ThumbViewer.imgPerRow);
    ThumbViewer.RenderPager();
    ThumbViewer.ShowNumbers();
    if(this.totalHits == "0")
    {
        ThumbViewer.ToggleVisibility($('pages-div'),'hidden');
        ThumbViewer.ToggleVisibility($('imgless'),'hidden');
        ThumbViewer.ToggleVisibility($('imgmore'),'hidden');
        ThumbViewer.ToggleVisibility($('imgperrow'),'hidden');
        $('slider-txt').innerText = "No results found. Try another search phrase.";
    }
    else
    {
        ThumbViewer.ToggleVisibility($('pages-div'),'visible');
        ThumbViewer.ToggleVisibility($('imgless'),'visible');
        ThumbViewer.ToggleVisibility($('imgmore'),'visible');
        ThumbViewer.ToggleVisibility($('imgperrow'),'visible');
        $('slider-txt').innerText = "Images per row:  ";
    }
  },

  // get relevant CSS values from the stylesheets
  GetImagesDivParams : function() {
    if (this.styleParsed) return;
    var sts = this.GetStyleSheets();
  
    for (var x = 0; x < sts.length; x++) {
      var rules;
      if( sts[x].cssRules ) {
        rules = sts[x].cssRules;
      } else rules = sts[x].rules;
      for (var j = 0; j < rules.length; j++) {
        var rule = rules[j];
        if ('.scale-image'==rule.selectorText) {
          // found our class, now get the values we need
          var t = rule.style.border;
          if (t!=undefined && t!=null && t!="") {
            t=this.ParseCSSVal(t);
            this.divBorder = (parseInt(t) * 2);
          }
          t = rule.style.margin;
          if (t!=undefined && t!=null && t!="") {
            t=this.ParseCSSVal(t);
            this.divMargin = (parseInt(t) * 2);
          }
          t = rule.style.padding;
          if (t!=undefined && t!=null && t!="") {
            t=this.ParseCSSVal(t);
            this.divPadding = (parseInt(t) * 2);
          }
        } else if ('.box'==rule.selectorText) {
          // found our class, now get the values we need
          var t = rule.style.border;
          if (t!=undefined && t!=null && t!="") {
            t=this.ParseCSSVal(t);
            this.boxBorder = (parseInt(t) * 2);
          }
          t = rule.style.margin;
          if (t!=undefined && t!=null && t!="") {
            t=this.ParseCSSVal(t);
            this.boxMargin = (parseInt(t) * 2);
          }
          t = rule.style.padding;
          if (t!=undefined && t!=null && t!="") {
            t=this.ParseCSSVal(t);
            this.boxPadding = (parseInt(t) * 2);
          }
        }
      }
    }
  },

  // a debug method. It will add a div at the end of the html page
  // and will log what you want in it.
  // change this.DEBUG to true to enable.
  ShowStats : function (str) {
    if (!this.DEBUG) return;
    if (this.debugDiv==undefined){
      this.debugDiv = document.createElement('div');
      this.debugDiv.style.width='400px';
      this.debugDiv.style.height='300px';
      this.debugDiv.style.overflow='scroll';
      this.debugDiv.style.border='1px solid blue';
      this.debugDiv.setAttribute('id','debugDiv');
      document.body.appendChild(this.debugDiv);
    }
    var txt = this.debugDiv.innerHTML;
    txt += '<br />' + str.escapeHTML();
    this.debugDiv.innerHTML = '';
    this.debugDiv.innerHTML = txt;
  },

  // add the video info to the popup div
  AddDivInfo : function () {
    var block = $("box");
    var old = $("div-info");
    if (old != undefined && old != null) block.removeChild(old);
 
    var img = $('box-img');
    if(img !=undefined && img!=null) {
      var t = img.getAttribute('title');
      var d = img.getAttribute('duration');
      var s = img.getAttribute('site');
      var v = img.getAttribute('views');
    }
 
    var div = document.createElement('div');
    div.setAttribute('class','info');
    div.setAttribute('id','div-info');
    var html="<table id=\"tbl\" style=\"width:auto;\">";
 
    if (t != undefined && t != null && t != '') {
      html += "<tr><td nowrap><span class=\"info-title\">";
      if (this.showCaption) {html += "<b>Title:&nbsp;</b>";}
      html += t.substr(0,12);
      if(t.length>16)html+='...';
      html += "</span></td></tr>";
    }
  
    if (d != undefined && d != null && d != '') {
      html += "<tr><td nowrap><span class=\"info-duration\">";
      if (this.showCaption) {html += "<b>Duration:&nbsp;</b>";}
      html += d;
      html += "</span></td></tr>";
    }
  
    if (v != undefined && v != null && v != '') {
      v = addCommas(v);
      html += "<tr><td nowrap><span class=\"info-views\">";
      if (this.showCaption) {html += "<b>Views:&nbsp;</b>";}
      html += v;
      html += "</span></td></tr>";
    }
  
    if (s != undefined && s != null && s != '') {
      html += "<tr><td nowrap><span class=\"info-site\">";
      if (this.showCaption) {html += "<b>Site:&nbsp;</b>";}
      html += s.replace('www.','');
      html += "</span></td></tr>";
    }
    html += "</table>"

    div.innerHTML = html;
    block.appendChild(div);
 
    var tbl = $('tbl');
    var tow = tbl.offsetWidth;
    var doh = div.offsetHeight;
    block.removeChild(div);
 
    // the info text div is larger than our box so recalculate all
    if (block.clientWidth < tow) {block.style.width = tow+'px';}
    block.style.height = (block.clientHeight+doh)+"px";
    block.appendChild(div);
  },

  // parse a CSS entry
  ParseCSSVal : function (val) {
    var myRE = /([0-9]{1,})px/
    a = myRE.exec(val);
    return a[1];
  },

  // callback. will be called when a page number
  // is clicked in the pager object.
  PageIndexClicked : function (pg) {
    if (pg=="next") {
      this.curPage+=1;
    } else if (pg=="previous") {
      this.curPage-=1;
    } else {
      this.curPage = pg;
    }
    var imgPerPage = this.imgPerRow*this.imgRowsMax;
    var start = imgPerPage * (this.curPage-1);
    this.SendAjaxRequest(this.currentQuery,start,0,imgPerPage);
  },

  // render the pager object
  RenderPager : function (){
	var showPages = 4;
    var delta = 3;
    var vis = false;
  
    var html='<table valign="top" cellpadding="0" cellspacing="0" style="height:100%;"><tr>';
    // if first page turn off previous button
	
    if (this.curPage<=1) {
      html+='<td><span class="previous-page-off" >&laquo;&nbsp;</span></td>';
    } else {
      html+='<td><span class="previous-page-on" onmouseover=\"ThumbViewer.OnPagerElemOver(this);\" onmouseout=\"ThumbViewer.OnPagerElemOut(this);\" onclick="ThumbViewer.PageIndexClicked(\'previous\');" >&laquo;&nbsp;</span></td>';
    }
  
    var pagesDiv = $('pages-div');
    if (pagesDiv==undefined || pagesDiv==null) return;
  
    var imgPerPage = this.imgPerRow*this.imgRowsMax;
    //if (this.totalHits < imgPerPage) return;
	if (this.totalHits < imgPerPage) {
		var midHTML='';
		midHTML += "<td><div onmouseover=\"ThumbViewer.OnPagerElemOver(this);\" onmouseout=\"ThumbViewer.OnPagerElemOut(this);\" class=\"select-page-off\"><b>1</b>&nbsp;</div></td>"
		totalPages = 1;
	} else {
		var totalPages = (this.totalHits / imgPerPage).toFixed();
	   	if (totalPages < (this.totalHits / this.imgPerPage)) totalPages+=1;
		totalPages = Math.min(totalPages,99);
  
		var startPage = ((this.curPage-delta) >= 1) ? (this.curPage-delta) : 1;
	    var endPage = Math.min((startPage+showPages),(this.curPage+(delta*2)));

	    endPage = Math.min(endPage, totalPages);
		var midHTML='';
	      for (var i=startPage; i<=endPage ;i++) {
		  if (vis==false && i==1)  vis=true;
  
	      if ( i==this.curPage ) {
		    midHTML += "<td><div onmouseover=\"ThumbViewer.OnPagerElemOver(this);\" onmouseout=\"ThumbViewer.OnPagerElemOut(this);\" class=\"select-page-off\"><b>"+i+"</b>&nbsp;</div></td>"
	      } else {
		    midHTML += "<td><div class=\"select-page-on\" onmouseover=\"ThumbViewer.OnPagerElemOver(this);\" onmouseout=\"ThumbViewer.OnPagerElemOut(this);\" onclick=\"ThumbViewer.PageIndexClicked("+i+");\">"+i+"&nbsp;</div></td>"
		  }
		} // for

	    if(!vis) {
		  html+='<td><span class="previous-page-on" onmouseover=\"ThumbViewer.OnPagerElemOver(this);\" onmouseout=\"ThumbViewer.OnPagerElemOut(this);\" onclick="ThumbViewer.PageIndexClicked(1);" >1</span></td>';
		  html+='<td><div class="select-page-dots">&nbsp;..&nbsp;</div><td>';
		}
	}
    html += midHTML;
	   if (this.curPage<totalPages) {
		if(totalPages>'5') {  
	       html+='<td><div class="select-page-dots">&nbsp;..&nbsp;</div><td>';
           html+='<td><div class="next-page-on" onmouseover="ThumbViewer.OnPagerElemOver(this);" onmouseout="ThumbViewer.OnPagerElemOut(this);" onClick="ThumbViewer.PageIndexClicked('+totalPages+');">'+totalPages+'</div></td>';
		}
      html+='<td><span class="next-page-on" onmouseover="ThumbViewer.OnPagerElemOver(this);" onmouseout="ThumbViewer.OnPagerElemOut(this);" onclick="ThumbViewer.PageIndexClicked(\'next\');">&nbsp;&raquo;</span></td>';
    } else {
      html+='<td><span class="next-page-off">&nbsp;&raquo;</span></td>';
    }
  
    html += '</tr><table>'
  
    pagesDiv.innerHTML = html;
  },

  SetBorderOff : function (divObj) {divObj.style.border = '2px solid gray';},

  ExpandTimer : {
    timerID : 0,
    timeOut : 20,
    stageDelay : null,
    curLevel : 1,
    curW : null,
    curH : null,
    maxW : null,
    maxH : null,
    curposX : null,
    curposY : null,
    posX : null,
    posY : null,
  
    CurLevel: function(level) {
      this.curLevel = level;
    },
  
    UpdateTimer: function(objID) {
      if(this.timerID) { clearTimeout(this.timerID); }
  
      var block = $(objID);
      
      while(true) {  
        if(this.curposX > this.posX) {
          this.curposX -= 1;
          block.style.left = this.curposX+'px';
        }
        if(this.curposY > this.posY) {
          this.curposY -= 1;
          block.style.top = this.curposY+'px';
        }
        if(this.curW < this.maxW) {
          block.style.width = this.curW+'px';
          this.curW += 2;
        }
        if(this.curH < this.maxH) {
          block.style.height = this.curH+'px';
          this.curH += 1;
        }
        if (this.curW >= this.maxW && this.curH >= this.maxH && this.curposX <= this.posX && this.curposY <= this.posY) {
          this.Stop();
          return;
        }
      }
      //this.timerID = setTimeout('ThumbViewer.ExpandTimer.UpdateTimer("'+objID+'")', this.timeOut);
    },
  
    Start: function(objID) {
      var block = $(objID);
      this.curW = block.clientWidth;
      this.curH = block.clientHeight;
      this.maxW = (block.clientWidth + ((block.clientWidth*ThumbViewer.expandHorizP)/100)).toFixed();
      this.maxH = (block.clientHeight + ((block.clientHeight*ThumbViewer.expandVertP)/100)).toFixed();
      if(this.timerID) {clearTimeout(this.timerID);this.timerID  = 0;}
      this.timeout = ThumbViewer.expandTimeout;
      this.stageDelay = ThumbViewer.stageDelay;
  
      var ph = block.style.left;
      this.curposX = ph.substring(0,ph.indexOf('px'));
      ph = block.style.top;
      this.curposY = ph.substring(0,ph.indexOf('px'));
      this.posX = ((this.curposX - ((this.maxW - this.curW) / 2)).toFixed());
      this.posY = (this.curposY - ((this.maxH - this.curH) / 2)).toFixed();
  
      if (this.posX < 0) this.posX = 0;
      if (this.posY < 0) this.posY = 0;
  
      this.timerID = setTimeout('ThumbViewer.ExpandTimer.UpdateTimer("'+objID+'")', this.timeOut);
    },
  
    Stop: function(killTimer) {
      if(this.timerID) {clearTimeout(this.timerID);this.timerID  = 0;}
      this.curW = null;
      this.curH = null;
      this.maxW = null;
      this.maxH = null;
      this.curposX = null;
      this.curposY = null;
      this.posX = null;
      this.posY = null;
      if (killTimer!=undefined && killTimer!=null && killTimer==true) return;
      /*
      if (this.curLevel==1) {
        this.curLevel=2;
        this.timerID = setTimeout('ThumbViewer.ExpandTimer.Start("box")', this.stageDelay);
        return;
      }*/
      ThumbViewer.AddDivInfo();
    }
  },
  OpenVideoInWindow : function(url) {
    mywin = window.open(url, 'video'); 
    mywin.focus();
  }
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

// parse the query string and return params
// as array
function GetQueryParams() {
  var index = document.URL.indexOf('?');
  var params = new Array();
  if ( index != -1 ) {
    var nameValuePairs=document.URL.substring(index+1,document.URL.length).split('&');
    for ( var i=0; i<nameValuePairs.length; i++ ) {
      var nameVal = nameValuePairs[i].split('=');
      if (params[nameVal[0]] == null) {
        //param doesn't exist so create a new array
        params[nameVal[0]] = [nameVal[1]];
      }else{
        //param already exists so add to the array
        params[nameVal[0]].push(nameVal[1]);
      }
    }
  }
  return params;
}

var siteHomePath = '';

if (document.URL.indexOf('localhost')!= -1) {
  siteHomePath= "/FRWebSite2";
}

// initialize ThumbViewer class
ThumbViewer.SetAjaxServerUrl(siteHomePath+'/video/NewSearchProxy.aspx');
ThumbViewer.SetStageDelay(1);
ThumbViewer.SetExpandTimeout(5);
ThumbViewer.SetExpandHorizPercent(80);
ThumbViewer.SetExpandVertPercent(70);
ThumbViewer.Init();
