
var output = '';
var loop = 3;
var page_loop_count = 0;
var resultset = new Array();
var xy = 0;
var current_stars = -1;
var order_by_date = 0;

function videoControl() {

  videoSearch = new google.search.VideoSearch();
  //videoSearch.setRestriction(GSearch.SAFESEARCH_STRICT);  /// NOT IMPLEMENTED BY GOOGLE FOR VIDEO SEARCH???
  if (order_by_date==1) {
  	videoSearch.setResultOrder(GSearch.ORDER_BY_DATE);
  }
  //videoSearch.setSiteRestriction("youtube.com");   //// NOT IMPLEMENTED BY GOOGLE EITHER!!
  videoSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
  videoSearch.setNoHtmlGeneration();
  videoSearch.setSearchCompleteCallback(this,videoControl.prototype.draw_results, [videoSearch]);

}

function searchterm_click(query,mode) {

  loop = mode;
  page_loop_count = 0;
  resultset = new Array();
  xy = 0;

  document.getElementById('video_subcontent').innerHTML = "<div align='center' style='margin-top:20px' class='h3'><img src='http://images.advfn.com/imagesnew/2/gb/spinner.gif'> " + searching + "</div>";

  if (document.getElementById('video_category_title')) {
    document.getElementById('video_category_title').innerHTML = document.getElementById('search-button').innerHTML + ': "' + query + '"';
  }
  
  new videoControl();
  videoSearch.execute(query);

}

videoControl.prototype.draw_results = function(videoSearch) {

  if (videoSearch.cursor) {
    page_count = videoSearch.cursor.pages.length;
    if (page_count>5) {
      page_count = 5;
    }

    if (page_loop_count < page_count) {

      for (x=0; x<videoSearch.results.length; x++) {
        resultset[xy] = videoSearch.results[x];
        xy++;
      }

      page_loop_count++;
      if (page_loop_count < page_count) {
      	 videoSearch.gotoPage(page_loop_count);
      } else {
        draw_search_results();
      }
    } else {
      draw_search_results();
    }
  } else {
    draw_search_results();
  }

}  

function var_dump(obj) {
     if(typeof obj == "object") {
        return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
     } else {
        return "Type: "+typeof(obj)+"\nValue: "+obj;
     }
}

function draw_search_results() {

  count = 0;

  if (loop==1) {
    var width = '270px';
  } else {
    var width = '187px';
  }

  output = '<table width="100%">';
  output += '<tr><td>';

  if (resultset.length>0) {
    for (i=0; i<resultset.length; i++) {
      result = resultset[i];
      if (result.publisher != 'www.youtube.com') {
         continue;
      }

      if (count==loop) {
        count = 0;
        output += '</td></tr><tr><td>';
      }
      count ++;

      output += '<div style="width:' + width + '; margin-right:4px; float:left; border:1px solid #dedede;">';
      draw_html(result);
      output += '</div>';
    }
  } else {
    output += '<br><h3 align="center">' + no_videos + '</h3>';
  }

  output += '</td></tr>';
  output += '</table>';

  document.getElementById('video_subcontent').innerHTML = output;

}

function run_video_id(video_id,query) {
	var url = 'http://www.youtube.com/v/' + video_id + '&fs=1&source=uds&autoplay=1&enablejsapi=1';
	run_video(url,query);
}

function run_video(video_url,query) {

  current_stars = -1;
  document.getElementById('video_content').style.display = 'none';
  if (query.length<2) {
    query = default_query;
  }
  searchterm_click(query,1);

  document.getElementById('video_carousel').style.display = 'block';
  
  var container = document.getElementById('video_container');
  container.innerHTML = '<div id="video_window_div"></div>';
  container.style.display="block";
  
  load_header(video_url);

  var video = document.getElementById('video_window_div');

  var params = { allowScriptAccess: "always", allowFullScreen: "true" };
  var atts = { id: "video_window" };
  swfobject.embedSWF(video_url + "&playerapiid=video_window&rel=0",
                   "video_window_div", "500", "375", "8", null, null, params, atts);
  
}

function load_header(video_url) {
  var url = '/p.php?pid=videonews_ajax&video_url=' + video_url + '&hash=' + hash + '&action=load_video_header';
  var id = 'video_header';
  new GetXmlHttpObject(url, id, 'first_load',video_url);
}

function load_video(video_url) {
  load_comments(video_url,0);
  load_video_info(video_url);
}

function load_video_info(video_url) {
  var url = '/p.php?pid=videonews_ajax&video_url=' + video_url + '&hash=' + hash + '&action=load_video_info';
  var id = 'video_info';
  new GetXmlHttpObject(url, id);
}

function load_comments(video_url,start) {
  var url = '/p.php?pid=videonews_ajax&video_url=' + video_url + '&hash=' + hash + '&action=load_video_comments&x=' + start;
  var id = 'video_content';
  new GetXmlHttpObject(url, id);
}

function run_user_update(video_id, action, extras) {
  if (extras==undefined || extras==0) {
    extras ='';
  }
  var url = '/p.php?pid=videonews_ajax&video_id=' + video_id + '&hash=' + hash + '&action='+action+'&x='+extras;
  var id = 'user_update';
  new GetXmlHttpObject(url, id, 'alert');
}

function GetXmlHttpObject(url, id, mode, video_url) {
  this.xmlHttp=null;
  try {
    // Firefox, Opera 8.0+, Safari
    this.xmlHttp=new XMLHttpRequest();
  }
  catch (e) {
    // Internet Explorer
    try {
      this.xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      try {
        this.xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e){this.xmlHttp=null;}
    }
  }

  if(this.xmlHttp!=null){
    var c=this;
    this.el=document.getElementById(id);
    this.xmlHttp.open("GET",url,true);

    if (mode=='first_load') {
      this.xmlHttp.onreadystatechange=function(){c.stateChangedFirst(video_url);};
    } else if (mode=='alert') {
      this.xmlHttp.onreadystatechange=function(){c.stateChangedAlert();};
    } else {
      this.xmlHttp.onreadystatechange=function(){c.stateChanged();};
    }
    this.xmlHttp.send(null);
  } else {
    alert('Your browser does not support AJAX!');
  }
}

GetXmlHttpObject.prototype.stateChangedFirst=function (video_url) {
  if (this.xmlHttp.readyState==4) {
    var tid=this.xmlHttp.responseText;
    this.el.innerHTML = tid;
    this.el.style.display = 'block';
    load_video(video_url);
  }
}

GetXmlHttpObject.prototype.stateChanged=function () {
  if (this.xmlHttp.readyState==4) {
    var tid=this.xmlHttp.responseText;
    this.el.innerHTML = tid;
    this.el.style.display = 'block';
  }
}

GetXmlHttpObject.prototype.stateChangedAlert=function () {
  if (this.xmlHttp.readyState==4) {
    var tid=this.xmlHttp.responseText;
    alert(tid);
  }
}

function format_date(published)
{
  var nicerDate = new Date();
  nicerDate.setTime(Date.parse(published));

  if(view=='jp')
  	var dateFormatted =  nicerDate.getFullYear() + '/' + (nicerDate.getMonth()+1) + '/' + nicerDate.getDate() + ', ';
  else
  	var dateFormatted =  nicerDate.getDate() + '/' + (nicerDate.getMonth()+1) + '/' + nicerDate.getFullYear() + ', ';

  dateFormatted += nicerDate.getHours() + ":";
  if (nicerDate.getMinutes()<10) {
    dateFormatted += '0'+nicerDate.getMinutes();
  } else {
    dateFormatted += nicerDate.getMinutes();
  }

  return dateFormatted;

}

function draw_html(result) {

  dateFormatted = format_date(result.published);

  var duration_m = parseInt(result.duration/60);
  var duration_s = (result.duration-(duration_m*60));

  if (duration_s < 10) {
    duration_s = '0' + duration_s;
  }

  var duration = duration_m + ":" + duration_s;

  if (result.titleNoFormatting.length>20) {
    title = result.titleNoFormatting.substr(0,30) + '...';
  } else {
    title = result.titleNoFormatting;
  }
  
  var jumptotag = document.getElementById("search-input").value;

  output += ''
    + '<table cellspacing="0" cellpadding="3" width="100%">'
      + '<tr valign="top"><td align="center" width="65">'
        + '<a href="javascript:run_video(\'' + result.playUrl + '&enablejsapi=1\',\'' + jumptotag + '\')" rel="nofollow">'
          + '<img src="' + result.tbUrl + '" alt="' + result.titleNoFormatting + ' Video" width="80" height="60" ' + '/>'
        + '</a>'
      + '</td>'
      + '<td>'
        + '<div class="video_name">'
          + '<a href="javascript:run_video(\'' + result.playUrl + '&enablejsapi=1\',\'' + jumptotag + '\')" rel="nofollow">' + title + '</a>'
        + '</div>'
        + '<div class="video_author video_dateformat">' + dateFormatted  + '</div>'
        + '<div class="video_duration">' + lang_duration + ': ' + duration + ' ' + mins + '</div>'
      + '</td></tr>'
    + '</table>'

}

function ucwords( str ) {
    str = str.toLowerCase();
    return str.replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
}

function searchtermEnterKey(e,textboxvalue,mode)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13) {
	searchterm_click(textboxvalue,mode);
        return false;
     } else
        return true;
}

function switch_tabs(from,to) {
  document.getElementById(from).className = "carousel_searchterms hidden";
  var from2 = from + 'C';
  document.getElementById(from2).className = "top_tab";
  document.getElementById(to).className = "carousel_searchterms";
  var to2 = to + 'C';
  document.getElementById(to2).className = "top_tab top_tab_highlight";
}

function more_info() {
  document.getElementById('descrip2').style.display = "none";
  document.getElementById('descrip1').style.display = "block";
  document.getElementById('descrip2l').style.display = "none";
  document.getElementById('descrip1l').style.display = "inline";
}

function less_info() {
  document.getElementById('descrip1').style.display = "none";
  document.getElementById('descrip2').style.display = "block";
  document.getElementById('descrip1l').style.display = "none";
  document.getElementById('descrip2l').style.display = "inline";
}

function reverse_link(type) {
  var span1 = document.getElementById(type+'1');
  var span2 = document.getElementById(type+'2');
  if (span1.style.display == 'none') {
    span1.style.display='inline';
    span2.style.display='none';
  } else {
    span1.style.display='none';
    span2.style.display='inline';
  }
}

function stars_update(id,def_stars) {
  if (current_stars==-1) {
    current_stars = def_stars;
  }
  if (id==0) {
    id = current_stars;
  }

  for(i=1;i<=5;i++) {
    var star = document.getElementById('star_rating_'+i);
    if (i<=id) {
      type = '1';
    } else {
      type = '2';
    }
    src = star.src.substr(0,(star.src.length-5)) + type + '.gif';
    star.src = src;
  }
}

function check_form() {
	var title = document.getElementById('video_comment_title');
	var comment = document.getElementById('video_comment_comment');

	if (title.value.length>0 && comment.value.length>0) {
		document.forms[0].btn.value = 'submit_video_comment';
		doSubmit();
	} else {
		return false;
	}
}

