SHOW_DELAY = 2000;
HIGHLIGHT_TIME = 10000;
REFRESH_TIME = 20000;
STOP_TIME = 1800;
DOMAIN = 'akcie-cz.kurzy.cz';
STATWEBDOMAIN = 'http://x.kde.cz/kurzy/akcie/';
MAX_TYPE_LENGTH = 8;


var response = 0;
var request = 0;
var in_progress = 1;
var g_tm = ''

function go(typ, user) {  // bezi REFRESH_TIME/1000 sekund * pocet requestov, napr. 30*30 sekund, 15 minut 
  request++;
  var sec_in_progress = (REFRESH_TIME/1000) * request
  if (( sec_in_progress < STOP_TIME) && (in_progress)) {
    write_streamer_data(typ, user, 1)

	if (request > 0 && typ == 'title') {
      rs = randomString(32)
      $("#graf_px").empty().hide().html('<img src="http://'+DOMAIN+'/g/online-index-px-burza-praha.png?x='+rs+'" alt="online index px" border="0" width="234" height="150" />').fadeIn(1000);
      $("#graf_rm").empty().hide().html('<img src="http://'+DOMAIN+'/g/online-index-rm-system-praha.png?x='+rs+'" alt="online index rm" border="0" width="234" height="150" />').fadeIn(1000);
    }
    
	if ((request % 3 == 0) || (request<2)) //#kazdu  ( % 3 ) poziadavku nacitaj spravy
	{
        write_streamer_data("zpr_ptek", user, 0)
        write_streamer_data("naz", user, 0)
	}
    setTimeout("go('"+typ+"',"+user+")", REFRESH_TIME);
  } else {
	in_progress = 0
    stream_stoped()
  }
}

function stream_stoped() {
    $("#control_status").text("Vypnuto").css("color", "red")
    $("#control_button").attr("value", "Zapnout").css("color", "green").css("font-size", "12px")
    $("#data_online_tab").css("color", "#808080")    
}

function online_arrows(val_old, hodnota, typ, j) {
    if (hodnota != " ") {
        var id_img = "#span_" + typ + "_" + j
        if (val_old != hodnota) {
            if (val_old > hodnota) { pom = "arrd.gif" } 
            else { pom = "arru.gif" }            
            setTimeout('$("' +id_img + '").html("<img src=http://i.fin.cz/i/flag/'+pom+' border=0 width=8 height=10 />")', SHOW_DELAY)
            setTimeout('$("' +id_img + '").html("  ")', HIGHLIGHT_TIME)
        } 
    }
}

function child_val_delay(id, val, type) {
    if (val != " ") {
        if (request > 1) {
            setTimeout('$("#' + id + '").html = ""', SHOW_DELAY)
            if (type == "zm") val += "%"
            setTimeout('$("#' + id + '").text("' +val+ '")', SHOW_DELAY)
        } else {
            child_val(id, val, type)
        }
    }
}

function green_red(id, hodnota) {
  if (hodnota>0)
    setTimeout('$("#' + id + '").css("color", "green")', SHOW_DELAY)  
  else
    setTimeout('$("#' + id + '").css("color", "red")', SHOW_DELAY) 
}

function gs(res_str, cas) { g_write(res_str, cas, "spad") }    

function g(res_str, cas) { g_write(res_str, cas, "title") }

function g_write(res_str, cas, typ) {
  response++;
  g_tm = cas.substring(9) //"16.01.09 13:09:03"    

  res_str = decode(res_str)
  var results = res_str.split(",")
  var g_result_length = get_result_length(results)
  if (typ == "title")   {
    var show_change_req = 0
    var sp = new Array("ka","zm","ob")
  } else {
    var show_change_req = 1
    var sp = new Array("ka","zm", "po", "na", "ob", "ok", "o2" , "t1", "ce", "k2", "t2")
  }
  var j = 0

  for (var i = 0; i < g_result_length; i = i + sp.length) {
    var k = 0
    var change_on_row = 0
    for(var sp_index in sp) {
      var id = "span_" + sp[sp_index] + "_" + j

      try 
      { 
          var val_old = document.getElementById(id).innerHTML.replace('%', '')
      } catch(e) {
        continue
      }

      var hodnota = results[i + k]

      if (sp[sp_index].substring(0,1) == "t")  { 
          if (hodnota.substring(2,3) != ".")
            hodnota = hodnota.substring(0,2) + ':' + hodnota.substring(2,4) + ':' + hodnota.substring(4,6) 
      }
      if (sp[sp_index] == "ka")  { online_arrows(val_old, hodnota, "im", j) }
      if (response > show_change_req) {
        if (sp[sp_index] == "na")  { online_arrows(val_old, hodnota, "imna", j) }
        if (sp[sp_index] == "po")  { online_arrows(val_old, hodnota, "impo", j) }
      }

      if ((val_old != hodnota) && (hodnota != -1) && (hodnota != ' ')) {
	    child_val_delay(id, hodnota, sp[sp_index])
	    if (sp[sp_index] == "zm") green_red(id, hodnota)
	    if (val_old != "" ) {
            setTimeout('$("#' + id + '").attr("class", "val_bold")', SHOW_DELAY)
	        setTimeout('$("#' + id + '").attr("class", "val_nobold")', HIGHLIGHT_TIME)
	    }        
        if (sp[sp_index] != "t1") change_on_row = 1
      } k++
    }

    if ((change_on_row == 1) && (response > show_change_req)) {
      id = "tr_" + j
      $("#" + id).attr("class", "gold") 
      var p = "nogoldgray"
      if ((j % 2) == 0)  p = "nogold" 
      setTimeout('$("#' + id + '").attr("class", "' +p+ '")', HIGHLIGHT_TIME)
    } j++
  }
}

function kz(res_str, type) {
  var results = res_str.split(";")
  var g_result_length = get_result_length(results)
  var sp = new Array("ka","zm","tm")
  j = 0
  for (var i = 0; i < g_result_length; i = i + sp.length) {
    k = 0
    for(var sp_index in sp) {
      hodnota = results[i + k]
      var id = type + "_" + sp[sp_index] + "_" + j
      if (hodnota != " ") {
        span_act = child_val(id, hodnota, sp[sp_index])
        if (sp[sp_index] == "zm")
	       green_red(span_act, hodnota)
	  }
      k++
    }
    j++
  }
}

function child_val(id, val, type) {
    //$("#" + id ).html = ""
    if (type == "zm") val += "%"
    $("#" + id ).text(val)
}

function z(res_str, type) {
  var results = res_str.split(";")
  var g_result_length = get_result_length(results)
  var sp = new Array("ur","tm","ti","au")
  var j = 1
  for (var i = 0; i < g_result_length; i = i + sp.length) {
    var k = 0
    var show_change = 0
    for(var sp_index in sp) {        
        var hodnota = results[i + k]        
        var id = type + "_" + sp[sp_index] + "_" + j        

        switch (sp[sp_index]) {
        case "tm":
            if (j == 1) { 
                var val_old = document.getElementById(id).innerHTML
                if (val_old != hodnota) show_change = 1 
            }
            child_val(id, hodnota, sp[sp_index])
            break
	    case "ur": 
            var url = hodnota
	        break
	    case "ti":
            $("#" + id).html('<a href="' +url+ '">' + hodnota + '</a>')
            if ((j==1) && (show_change) && request > 1) {
                $("#" + type + "_" + j).attr("class", "gold")
                setTimeout('$("#' + type + "_" + j + '").attr("class", "nogoldf5")', HIGHLIGHT_TIME)
            }                
	        break
	    default:
	        try {
	            child_val(id, hodnota, sp[sp_index])
	        } catch(err) { alert(id) }
        }
      k++
    }
    j++
  }
}

function a(res_str, type) {
  var results = res_str.split(";")
  var g_result_length = get_result_length(results)
  var sp = new Array("u1","u2","na","sm","va","tm")
  var j = 1
  for (var i = 0; i < g_result_length; i = i + sp.length) {
    var k = 0
    for(var sp_index in sp) {
      hodnota = results[i + k]
      var id = type + "_" + sp[sp_index] + "_" + j
      switch (sp[sp_index]) {
	case "u1":
	  var url1 = hodnota
	  break
	case "u2":
	  var url2 = hodnota
	  break
	case "na":
	  span_act = document.getElementById(id)
	  span_act.innerHTML = ""
	  nav_a = make_anchor(url1, hodnota)
	  span_act.appendChild(nav_a)
	  break
	default:
	  //try {
	    span_act = child_val(id, hodnota, sp[sp_index])
	 // } catch(err) { alert(id) }
      }
      k++
    }
    var id = type + "_no_" + j
    span_act = document.getElementById(id)
    span_act.innerHTML = ""
    nav_a = make_anchor(url2, "Nová nabídka")
    span_act.appendChild(nav_a)
    j++
  }
}

function ob(res_str, type) {
  var results = res_str.split(";")
  var g_result_length = get_result_length(results)
  var sp = new Array("ur","ak","cn","ks","tr","tm")
  j = 1
  for (var i = 0; i < g_result_length; i = i + sp.length) {
    k = 0
    for(var sp_index in sp) {
      hodnota = results[i + k]
      var id = type + "_" + sp[sp_index] + "_" + j
      //try {
      switch (sp[sp_index]) {
	case "ur": var url = hodnota
	  break
	case "ak":
	  span_act = document.getElementById(id)
	  span_act.innerHTML = ""
	  nav_a = make_anchor('/' + url + '/', hodnota)
	  span_act.appendChild(nav_a)
	  break
	default:
	  span_act = child_val(id, hodnota, sp[sp_index])
      }
      k++
    }
    j++
  }
}

function randomString(string_length) {
  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  var randomstring = '';
  for (var i = 0; i < string_length; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(rnum,rnum+1);
  }
  return randomstring;
}

function control_event() {
    
    if (in_progress) {
        in_progress = 0
        stream_stoped()
    } else {
        document.location.reload(true)        
    }        
}

function write_streamer_data(type, user, online) {
    //check MAX_TYPE_LENGHT
    var oScript = document.createElement('script');
    oScript.setAttribute('type','text/javascript');
    type = Left(type, MAX_TYPE_LENGTH)
    if ((user > 0) && (online == 1)) src = 'http://'+DOMAIN+'/streamer_online_data.asp?file=s_' + type + '.js&x='       
    else src = STATWEBDOMAIN + 's_' + type + '.js?x='
    oScript.setAttribute('src', src + randomString(32));        
    document.getElementById('source_pages').appendChild(oScript);
}

function replace_all(txt, from, to) {
  while (txt.indexOf(from)>-1)
    txt = txt.replace(from, to)
  return txt
}

function Left(str, n){
     if (n <= 0)
        return "";
     else if (n > String(str).length)
         return str;
     else
         return String(str).substring(0,n);
}

function make_anchor(url, text) {
    var nav_a =document.createElement('a')
    //nav_a.className="second_menu"
    var href = document.createAttribute('href')
    href.value = url
    nav_a.setAttributeNode(href)
    val = document.createTextNode(text)
    nav_a.appendChild(val)
    return nav_a
}

function get_result_length(results) {
  var result_len
   if (results)
    result_len = results.length
  else
    result_len = 0
  
  return result_len
}

function my_int2date(hodnota) {
  return hodnota.slice(0,2) + ":" + hodnota.slice(2,4) + ":" + hodnota.slice(4,6)
}

function decode(res_str) {
    a = ":;<=>?*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz{|}~[]()+%^&`/"
    var a_long=a.length;
    for (var i=0; i<a_long ; i++) {
      pom = a.charAt(i)
      if (i<10)
	  res_str = replace_all(res_str, pom, '0' + i)
      else
	  res_str = replace_all(res_str, pom, i)
    }
    res_str = res_str.replace(/!/g,".0")
    res_str = res_str.replace(/@/g,",0")
    res_str = res_str.replace(/#/g,".1")
    res_str = res_str.replace(/\$/g,",1")
    return res_str
}

function startTime(str_date, str_time, user) {

  var arr1 = str_date.split(",")

  if (g_tm != '') {  
    
    var p = g_tm.split(":") 
    h = p[0]
    m = p[1]
    s = p[2]    

    if (s.indexOf('~~')>-1) {        
        s = s.replace('~~', '')
        in_progress = 2
    }
    
    var today = new Date(arr1[0], arr1[1], arr1[2], h, m, s)
    g_tm = ''
    $("#sc_time").css("color", "black")
    setTimeout('$("#sc_time").css("color", "green")', HIGHLIGHT_TIME)
  } else {    
    var arr2 = str_time.split(",")
    var today = new Date(arr1[0], arr1[1], arr1[2], arr2[0], arr2[1], arr2[2])
    var h=today.getHours()
    var m=today.getMinutes()
    var s=today.getSeconds()
    // add a zero in front of numbers<10    
    h = checkTime(h)
    m = checkTime(m)
    s = checkTime(s)
  }  

  if (in_progress)  {
    var pom = 0
    if ((h >= 8) && (h < 17)) {
        pom = 1
        if ((h == 16) && ((m >= 8) && (s >= 0)))  { pom = 0 }    
    }

        if (pom) {
            $("#sc_time").text(h+":"+m+":"+s)

            if (in_progress != 2) {
            today = DateAdd("s",1,today)
            str_time = today.getHours()+","+today.getMinutes()+","+today.getSeconds()
            t=setTimeout("startTime('" + str_date + "','" + str_time + "')",1000)
        }
    } else {
        pom = str_date.split(",")
        $("#sc_time").text(pom[2]+"."+pom[1]+"."+pom[0]+" 16:08")
        $("#sc_text").text("Závěr")
        $("#sc_help").empty()
    }    
  }
}

function checkTime(i) {
  if (i<10){i="0" + i}
  return i
}

function DateAdd(timeU,byMany,dateObj) {
    var millisecond=1;
    var second=millisecond*1000;
    var minute=second*60;
    var hour=minute*60;
    var day=hour*24;
    var year=day*365;
    var newDate;
    var dVal=dateObj.valueOf();
    switch(timeU) {
	case "ms": newDate=new Date(dVal+millisecond*byMany); break;
	case "s": newDate=new Date(dVal+second*byMany); break;
	case "mi": newDate=new Date(dVal+minute*byMany); break;
	case "h": newDate=new Date(dVal+hour*byMany); break;
	case "d": newDate=new Date(dVal+day*byMany); break;
	case "y": newDate=new Date(dVal+year*byMany); break;
    }
    return newDate;
}
