var page = 0;
var rssDoc = null;
var links = new Array();
var cnt = 0;
var update = false;
var tick = 1;
var progress_event = null;
var items_in_page = 2;

function initpage() {

  var nocache = new Date().getTime();
  var linkpath = 'rss/links.xml?nocache='+nocache;
  var taglist = new Array('uniq', 'domain', 'path', 'title');
  var xml = new xmlRequest(xmlhandle, menu_disp, taglist, null);
  xml.open('GET', linkpath);
  xml.header("Cache-Control", "no-store, no-cache, must-revalidate");
  xml.header("Pragma", "no-cache");
  xml.header("Connection", "close");
  xml.send(null);

  updaterss('google_weather', 'www.google.co.kr', '/ig/api?weather=Seoul&ie=utf-8&oe=utf-8&hl=ko',false);
  var weather = new xmlRequest(google_weather_api_handle, weather_disp, null, null);
  weather.open('GET', 'rss/google_weather_latest.xml');
  weather.header("Cache-Control", "no-store, no-cache, must-revalidate");
  weather.header("Pragma", "no-cache");
  weather.header("Connection", "close");
  weather.send(null);

  loadrss('googlekey_weather');
}

function gilai_disp(rss) {

  (rss == null) ? (rss = rssDoc) : (rssDoc = rss);
  var i = 0;
  var d = new Date(rss.lastModified);
  if(/valid/.test(d) || /N/.test(d)) {
    lastModified = rss.lastModified;
  }
  else {
    lastModified = d.toLocaleString();
  }

  if(rss.title == '') {
    rss.title = '....';
  }

  if(/google/.test(rss.link)) {
    rss.description = '';
  }

  if(page < 0) { page = 0 }
  if(page > (rss.data.length/items_in_page)-1) { page = (rss.data.length/items_in_page)-1 }

  var info_box = '';
  var list_box = '';
  var img_link = '';
  var thumb_link= '';
  var page_box = '';

  list_box = "<div id='list'>";
  for(i=page*items_in_page; 
      i<rss.data.length && i<(page*items_in_page)+items_in_page; i++) {

      img_link = '';
      if(rss.data[i]['img'] != '') {
	  img_link = "<a href='" + rss.data[i]['img'] + "' target='_blank'>" + rss.data[i]['img'] + "</a>";
      }
      else if(rss.data[i]['enclosure'] != '') {
	  if(rss.data[i]['enclosure'].type == 'audio/mpeg') {
	      if(navigator.appName == 'Microsoft Internet Explorer') {
		  img_link = "<embed src='" + rss.data[i]['enclosure'].url + "' height='27' autostart='0'></embed>";
	      }else {
		  img_link = "<embed type='application/x-shockwave-flash' src='http://www.google.com/reader/ui/3247397568-audio-player.swf?audioUrl="+rss.data[i]['enclosure'].url+"' width='400' height='27' allowscriptaccess='never' quality='best' bgcolor='#ffffff' wmode='window' flashvars='playerMode=embedded'/>" + "<br><a href='"+rss.data[i]['enclosure'].url+"'>"+rss.data[i]['enclosure'].url+"</a>";
	      }
	  }
      }

      if(rss.data[i]['media:thumbnail'] != '') {

	//rss.data[i]['media:content'].url = encodeURI(rss.data[i]['media:content'].url);
	  thumb_link = "<a href='#' onclick=\"window.open('" + rss.data[i]['media:content'].url + "', 'imageWin', 'width="+rss.data[i]['media:content'].width+",height="+rss.data[i]['media:content'].height+"')\">" + "<img src='" + rss.data[i]['media:thumbnail'].url + "' width='" + rss.data[i]['media:thumbnail'].width + "' height='" + rss.data[i]['media:thumbnail'].height + "' border='0' align='left' hspace='10' title='" + rss.data[i]['media:title'] + "'></img>" + "</a>";
      }else {
	  thumb_link = '';
      }

      if(/google/.test(rss.data[i].link)) {
	  if((re = /^http.*url=(http.*)&usg=.*/.exec(rss.data[i].link)) != null) {
	      //rss.data[i].link = re[1];
	  }
      }

      if(rss.data[i]['title'] != undefined) {
	rss.data[i]['title'] = rss.data[i]['title'].substring(0, 60);
      }
      
      list_box += "<div id='item'><p id='ptitle'><a id='plink"+i+"' href='"+rss.data[i]['link'] + "' target='_blank'><span id='ptitle"+i+"'>" + rss.data[i]['title'] + "</span></a><img id='ptrans"+i+"' src='images/trans.gif' alt='번역하기' title='번역하기' width='15px' onclick='translate_language("+i+")'></p><p id='pdesc'><span id='pdesc"+i+"'>" + thumb_link + rss.data[i]['description'] + "</span> "+ rss.data[i]['pubDate'] + "<img src='images/dot.gif' onclick='scrap("+i+")'><br>"+img_link+"</p></div>"; 
  }
  
  list_box += "<span id='kma_weather'></span></div>";
  page_box += "<div id='page'><p><a href='#' onclick='page=" + (page-1) + "; gilai_disp(null); return 0;'><b>" + '<<<' + "</b></a>&nbsp;&nbsp;&nbsp;";
  
  for(i=0; i < (tpage = rss.data.length / items_in_page) && i < 20; i++) {
      page_box += "<a href='#' onclick='page=" + i + "; gilai_disp(null); return 0;'>" + (i+1) + "</a>&nbsp;&nbsp;&nbsp;";
  }
  
  page_box += "<a href='#' onclick='page=" + (page+1) + "; gilai_disp(null); return 0;'><b>" + '>>>' + "</b></a>&nbsp;&nbsp;&nbsp;</div>";
  
  info_box = "<div id='info'><a href='" + rss.link + "' target='_blank'><span id='rsstitle'>" + rss.title + "</span></a><br>" + lastModified + "</div>";
  
  $("#content").html(info_box + list_box  + page_box);
}


function menu_disp(xml) {

  document.getElementById('menu').innerHTML = '';

  for(var i=0; i < xml.data.length; i++) {

      $("#menu").append("<a title='update' href=javascript:updaterss(" + "'" + xml.data[i]['uniq'] + "'" + "," + "'" + xml.data[i]['domain'] + "'" + "," + "'" + xml.data[i]['path'] + "'" + ",false);loadrss('" + xml.data[i]['uniq'] + "')><img src='images/dot.gif' border='0'></a>&nbsp;&nbsp;<a href=javascript:loadrss('" +xml.data[i]['uniq'] + "')>" + xml.data[i]['title'] + "</a><br>");
      
      if(update) {
	  updaterss(xml.data[i]['uniq'], xml.data[i]['domain'], (xml.data[i]['path']));
      }
  }

  if(update) {
      updaterss('kma_weather', 'www.kma.go.kr', '/wid/queryDFS.jsp?gridx=59&gridy=125',false);
      update = false;
  }

  //var f = Math.floor(Math.random()*xml.data.length);
  //loadrss(xml.data[f]['uniq'], xml.data[f]['domain'], xml.data[f]['path']);
}
    
function loadrss(uniq, domain, path) {
	       
  page = 0;
  var gx = null;
  var nocache = new Date().getTime();

  var nocache = new Date().getTime();
  var path = 'rss/' + uniq + '_latest.xml' + '?nocache=' + nocache;
  gx = new xmlRequest(rsshandle, gilai_disp, null, null);
  gx.open('GET', path);
  gx.header("Cache-Control", "no-store, no-cache, must-revalidate");
  gx.header("Pragma", "no-cache");
  gx.header("Connection", "close");
  gx.send(null);

  if(uniq == 'googlekey_weather') {

      updaterss('kma_weather', 'www.kma.go.kr', '/wid/queryDFS.jsp?gridx=59&gridy=125',false);

      var weather2 = new xmlRequest(kma_weather_api_handle, weather2_disp, null, null);
      weather2.open('GET', 'rss/kma_weather_latest.xml');
      weather2.header("Cache-Control", "no-store, no-cache, must-revalidate");
      weather2.header("Pragma", "no-cache");
      weather2.header("Connection", "close");
      weather2.send(null);
  }

  document.getElementById("adminshell").focus();
}

function updaterss(uniq, domain, path, async) {
  
  var cx = null;
  var nocache = new Date().getTime();
  var async = (async == null) ? null : async;

  if(/naver/.test(domain) || /google/.test(domain)) {
    path = path.replace(/\//g, '%2F');
    path = path.replace(/\&/g, '%26');
    path = path.replace(/\+/g, '%2B');
    path = path.replace(/\=/g, '%3D');
    path = path.replace(/\?/g, '%3F');
    
    var update_url = 'update.php?uniq=' + uniq + '&domain=' + domain + '&path=' + escape(path) + '&nocache=' + nocache;
  }
  else {
    var update_url = 'update.php?uniq=' + uniq + '&domain=' + domain + '&path=' + encodeURIComponent(path) + '&nocache=' + nocache;
  }

  cx= new xmlRequest(xmlhandle, log_disp, new Array('uniq','result'), null);
  cx.open('GET', update_url, async);
  cx.header("Cache-Control", "no-store, no-cache, must-revalidate");
  cx.header("Pragma", "no-cache");
  cx.header("Connection", "close");
  cx.send(null);

  //if(uniq == 'googlekey_weather') {
  //updaterss('kma_weather', 'www.kma.go.kr', '/wid/queryDFS.jsp?gridx=59&gridy=125',false);
  //}
}

function scrap(f) {
  
  
  if(confirm("스크랩한다") == true) {

    var titleID = 'ptitle' + f;
    var linkID = 'plink' + f;
    var descID = 'pdesc' + f;
  
    var sx = null;
    var scrap_url = 'scrap.php';
    var params = 
      "title=" + encodeURIComponent(document.getElementById(titleID).innerHTML) + '&' +
      "link=" + encodeURIComponent(document.getElementById(linkID).href) + '&' +
      "description=" + encodeURIComponent(document.getElementById(descID).innerHTML);
    
    sx= new xmlRequest(xmlhandle, log_disp, new Array('result'), null);
    sx.open('POST', scrap_url);
    sx.header("Content-type", "application/x-www-form-urlencoded");
    sx.header("Content-length", params.length);
    sx.header("Connection", "close");
    sx.send(params);
  }
}


function weather_disp(xml) {

  var weather_img = '';
  //document.getElementById('weather').innerHTML = "<img src='http://www.google.co.kr" + xml.data.cc.icon + "' alt='" + xml.data.fi.forecast_date + "/" + xml.data.cc.condition + "' title='" + xml.data.fi.forecast_date + "/" + xml.data.cc.condition + "' hight='20' width='20'>" + '&nbsp;' ;

  document.getElementById('weather').innerHTML = '';
  for(var i=0; i<xml.data.fc.length; i++) { 
    weather_img = "<img src='http://www.google.co.kr" + xml.data.fc[i].icon + "' alt='" + xml.data.fc[i].day_of_week + "/" + xml.data.fc[i].condition + "/" + xml.data.fc[i].low + "~" + xml.data.fc[i].high + "' title='" + xml.data.fc[i].day_of_week + "/" + xml.data.fc[i].condition + "/" + xml.data.fc[i].low + "~" + xml.data.fc[i].high + "' hight='20' width='20'>";

    $("#weather").append(weather_img);
  }
}

function weather2_disp(xml) {

  var weather_img = '';
  var expstr = ''
  for(var i=0; i<xml.data.length; i++) {
      expstr = xml.data[i]['day'] + " " + xml.data[i]['hour'] + "시/" + xml.data[i]['wfKor'] + "/비올확률" + xml.data[i]['pop'] + "%";
      weather_img += "<img src='" + xml.data[i]['icon'] + "' title='" + expstr + "' alt='" + expstr + "'>";
  }
  $("#kma_weather").append(weather_img);
}

function admin(v, e) {

  var keynum = null;
  if(window.event) { // IE 
    keynum = e.keyCode;
  }
  else if(e.which) { // Netscape/Firefox/Opera
    keynum = e.which
  }
  else {
    keynum = e.keyCode;
  }

  if(keynum == 39) { // left arrow
    page = page+1;
    gilai_disp(null);
  }

  if(keynum == 37) { // right arrow
    page = page - 1;
    gilai_disp(null);
  }
    

  if(/^\:/.test(v.value)) {
    if(keynum != 13) {
      return;
    }
    else {
      v.value = v.value.replace(/^\:/, '');

      var xml = null;
      var url = 'admin.php?cmd=' + encodeURIComponent(v.value); 
      
      xml = new xmlRequest(xmlhandle, log_disp, new Array('result'), null);
      xml.open('GET', url);
      xml.send(null);
    }
  }

  if(keynum == 13) {
    v.value = '';
  }
}

function log_disp(xml) {
  cnt++;
  document.getElementById('log').innerHTML = cnt + ':';
  for(i=0; i < xml.data.length; i++) {
    document.getElementById('log').innerHTML += xml.data[i]['result'] + '<br>';
  }
}

function search(s, e) {

  var keynum = null;
  if(window.event) { // IE 
    keynum = e.keyCode;
  }
  else if(e.which) { // Netscape/Firefox/Opera
    keynum = e.which
      }
  else {
    keynum = e.keyCode;
  }

  if(keynum == 13) {

    progress_log(true);
    //progress_event = window.setInterval("progress_log()", 100);
    
    if(document.getElementById('google').checked) {
      var uniq = 'googlesearch';
      var domain = 'news.google.co.kr';
      var path = '/news?ned=kr&hl=ko&&q=' + encodeURIComponent(s.value) + '+-chosun+-joins+-donga&output=rss&ie=UTF-8';

      updaterss(uniq, domain, path, false);
      loadrss(uniq);
    }
    else if(document.getElementById('flickr').checked) {
      var uniq = 'flickrsearch';
      var domain = 'api.flickr.com';
      
      s.value = s.value.replace(/\s+/g, ",");
      var path = '/services/feeds/photos_public.gne?tags=' + encodeURIComponent(s.value) + '&lang=ko-kr&format=rss_200';

      updaterss(uniq, domain, path, false);
      loadrss(uniq);
    }
    else if(document.getElementById('picasa').checked) {
      var uniq = 'picasasearch';
      var domain = 'picasaweb.google.com';

      if(/\sin\s/.test(s.value)) {
	var sk = s.value.split(" in ");
	sk[0] = sk[0].replace(/\s+/g, "+");
	var path = '/data/feed/base/all?alt=rss&kind=photo&access=public&imgmax=800' + '&l=' + sk[1] + '&q=' + sk[0];
      }else {
	s.value = s.value.replace(/\s+/g, "+");
	var path = '/data/feed/base/all?alt=rss&kind=photo&access=public&imgmax=800' + '&q=' + s.value;
      }
      
      updaterss(uniq, '', path, false);
      loadrss(uniq);
    }
    else {
      alert('what?');
    }
    
    //window.clearInterval(progress_event);
    // document.getElementById('ajax_progress_bar').innerHTML = '.';
    progress_log(false);
    
  }

  else {
    return;
  }
}

function progress_log(mode) {

  var node = document.getElementById('ajax_progress_bar');
  //node.appendChild(document.createTextNode(exp));
  //node.firstChild.nodeValue = exp;
  if(mode) {
    node.style.visibility = 'visible';
  }else {
    node.style.visibility = 'hidden';
  }
}

function load_scrapbook() {

    document.getElementById("content").innerHTML = "<embed src='http://www.gilai.net/images/scrapbook.swf?rows=10&bgcolor=0xffffff' width='660' height='450' alt='길아이스크랩'></embed>";

}