var path="http://"+window.location.host+"/servlet/PriceFeedServlet";
var id = ["stkCode","ssn","refPrice","high","low","buy","sell","lastDone","priceChg","pcentChg","volume","parentPrice","exPrice","exRatio","expiryDate"];
var id2 = ["buyPrice","buyQty","buyOrd","sellPrice","sellQty","sellOrd"];
var id3 = ["avgBuyPrice","totalBuyQty","totalBuyOrder","avgSellPrice","totalSellQty","totalSellOrder"];
var id4 = ["high","low","buy","sell","lastDone","priceChg","pcentChg"];
var isLoaded = false;
var timer = null;
var selectedRowId  = null;
var displayType = 0;
var scoreBoardArray = null;
$.tablesorter.addParser({
        id: "myDateParser",
        is: function(s){
              return false;
            },
        format: function (s){
               var tokens = s.split("-");
               return (tokens[2] * 10000) +  (toMonthDigit(tokens[1]) * 100) + tokens[0];
            },
       type: "numeric"});
$.tablesorter.addParser({
        id: "myVolParser",
        is: function(s){
               return false;
        },
        format: function(s){
               if(s == "-") {
                   return 0;
               }
               return s.replace(/[^\d]/g,'');
        },
        type: "numeric"});
 

function loadWarrants()
{
    if(!isLoaded)
    {
        $(function(){
            var dataString = {get:"20"};
            $.get(path,dataString,function(data){
                $("tr#loading").hide();
                if(data.result.length > 0)
                {
                    isLoaded = true;
                    clearTimeout(timer);
                    $.each(data.result,function(index,optionData){
                        var values = ["&nbsp;"+optionData.stockCode,"&nbsp;"+optionData.ssn,(optionData.refPrice==0?"-":optionData.refPrice),(optionData.high==0?"-":optionData.high),(optionData.low==0?"-":optionData.low),(optionData.buy==0?"-":optionData.buy),(optionData.sell==0?"-":optionData.sell),(optionData.lastDone==0?"-":optionData.lastDone),(optionData.lastDone == 0)? "-":optionData.priceChg,(optionData.lastDone==0? "-":(optionData.priceChg/optionData.refPrice * 100).toFixed(3)),(optionData.vol==0?"-":optionData.vol),optionData.parentPrice,optionData.exPrice,optionData.exRatio,optionData.exDate];
                        var row = $("tr#sample_row").clone().attr('id',optionData.stockCode).appendTo("#warrant_list").css("display","");
                        $(row).bind("mouseover",function(){
                            onWarrantMouseOver(optionData.stockCode);
                        }).bind("mouseout",function(){
                            onWarrantMouseOut(optionData.stockCode);
                        }).bind("click",function(){
                            onWarrantSelect(optionData.stockCode);
                        });
			if(optionData.issuer.toUpperCase() == "KIBB")
			{
			    $(row).find("td#"+id[0]).css("background-color","#800000");
			    $(row).find("td#"+id[1]).css("background-color","#800000");
			}
                        for(var i=0;i<id.length;i++)
                        {
                            var newId = id[i] + "_" + optionData.stockCode;
			    if(i==11)
			    {
				values[i] = (values[i]== '-')? values[i]: parseFloat(values[i]).toFixed(2);
			    }
                            changeCellColour($(row).find("td#"+id[i]).attr("id",newId).html(values[i]),id[i],values[2],values[i]);
                        }
                    });
                    getScoreboard();
                    $("#warrant_table").tablesorter({cssHeader: "bcopy",cssAsc: "bcopyDown",cssDesc:"bcopyDown",headers:{14 : {sorter:"myDateParser"},10:{sorter:"myVolParser"}}});
                    setInterval(updateWarrants,60000);
                }
            },"json");
        });
    }
}

function toMonthDigit(data)
{
   var g =["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
   var x = data.toLowerCase();
   for(var i=0;i<g.length;i++)
   {
      if(x == g[i])
      {
         return i+1;
      }
   }
   return -1;
}

function changeCellColour(cell,cellName,refPrice,currentValue)
{
       if(currentValue == "-")
       {
             $(cell).removeClass("rcopy ycopy gcopy").addClass("wcopy");
       }
       else if((cellName == id4[0])||(cellName == id4[1])||(cellName == id4[2])||(cellName == id4[3])||(cellName == id4[4]))
       {
             $(cell).removeClass("rcopy ycopy gcopy").addClass(currentValue>refPrice?"gcopy": (currentValue==refPrice || currentValue == 0 ? "ycopy": "rcopy"));
       }
       else if(cellName == id4[5]||(cellName == id4[6]))
       {
             $(cell).removeClass("rcopy ycopy gcopy").addClass(currentValue>0?"gcopy":(currentValue==0 ? "ycopy":"rcopy"));
       }
}

function changeCellColour2(cell,refPrice,currentPrice)
{
       if(currentPrice == "-")
       {
             $(cell).removeClass("rcopy ycopy gcopy").addClass("wcopy");
       }
       else
       {
             $(cell).removeClass("rcopy ycopy gcopy").addClass(currentPrice>refPrice?"gcopy":(currentPrice==refPrice || currentPrice == 0 ? "ycopy": "rcopy"));
       }
}

function updateWarrants()
{
    $(function(){
        var dataString = {get:"20"};
        $.get(path,dataString,function(data){
            $.each(data.result,function(index,optionData){
                var values = [optionData.stockCode,optionData.ssn,(optionData.refPrice==0?"-":optionData.refPrice),(optionData.high==0?"-":optionData.high),(optionData.low==0?"-":optionData.low),(optionData.buy==0?"-":optionData.buy),(optionData.sell==0?"-":optionData.sell),(optionData.lastDone==0?"-":optionData.lastDone),(optionData.lastDone == 0)? "-":optionData.priceChg,(optionData.lastDone==0? "-":(optionData.priceChg/optionData.refPrice * 100).toFixed(3)),(optionData.vol==0?"-":optionData.vol),optionData.parentPrice,optionData.exPrice,optionData.exRatio];
                var row = $("tr#"+optionData.stockCode).css("background-color","#C4D0F2");
                for(var i=2;i<id.length;i++)
                {
                    var newId = id[i] + "_" + optionData.stockCode;
		    if(i==11)
		    {
			values[i] = (values[i]== '-')? values[i]: parseFloat(values[i]).toFixed(2);
		    }
                    changeCellColour($(row).find("td#"+newId).html(values[i]),id[i],values[2],values[i]);
                };
		if(optionData.issuer.toUpperCase() == "KIBB")
		{
		    $(row).find("td#"+id[0]).css("background-color","#800000");
		    $(row).find("td#"+id[1]).css("background-color","#800000");
		}
                setTimeout(function(){
                    $("tr#"+optionData.stockCode).css("background-color","#000000");
                },2500);
            });
            getScoreboard();
        },"json");
    });
}

function onWarrantSelect(stockCode)
{
    $(function(){
        var dataString = {get:"10",s:stockCode};
        $.get(path,dataString,function(data){
            $.each(data.result,function(index,optionData){
                var values = [optionData.bestBuyPrice1,optionData.bestBuyPrice2,optionData.bestBuyPrice3,optionData.bestBuyPrice4,optionData.bestBuyPrice5,optionData.bestBuyQty1,optionData.bestBuyQty2,optionData.bestBuyQty3,optionData.bestBuyQty4,optionData.bestBuyQty5,optionData.bestBuyOrder1,optionData.bestBuyOrder2,optionData.bestBuyOrder3,optionData.bestBuyOrder4,optionData.bestBuyOrder5];
                var values2 = [optionData.bestSellPrice1,optionData.bestSellPrice2,optionData.bestSellPrice3,optionData.bestSellPrice4,optionData.bestSellPrice5,optionData.bestSellQty1,optionData.bestSellQty2,optionData.bestSellQty3,optionData.bestSellQty4,optionData.bestSellQty5,optionData.bestSellOrder1,optionData.bestSellOrder2,optionData.bestSellOrder3,optionData.bestSellOrder4,optionData.bestSellOrder5];
                var values3 = [optionData.avgBuyPrice,optionData.totalBuyQty,optionData.totalBuyOrder,optionData.avgSellPrice,optionData.totalSellQty,optionData.totalSellOrder];
                var tmp;
                for(var i=0;i<3;i++)
                {
                    for(var j=1;j<=5;j++)
                    {
                        var newId = "td#"+id2[i]+j;
                        tmp = values[i*5+(j-1)];
                        $("table#best_limits").find(newId).html(tmp == 0?"-":tmp);
                    }
                }
                for(var i=3;i<6;i++)
                {
                    for(var j=1;j<=5;j++)
                    {
                        var newId = "td#"+id2[i]+j;
                        tmp = values2[(i-3)*5+(j-1)];
                        $("table#best_limits").find(newId).html(tmp == 0? "-":tmp);
                    }
                }
                for(var i=0;i<id3.length;i++)
                {
                    tmp = values3[i];
                    $("td#"+id3[i]).html(tmp == 0 ? "-":tmp);
                }
                var refPrice = $("#refPrice_"+stockCode).html();
                for(var i =0;i<5;i++)
                {
                        var newId = "td#"+id2[0]+(i+1);
                        changeCellColour2($("table#best_limits").find(newId),refPrice,values[i]);
                        newId = "td#"+id2[3]+(i+1);
                        changeCellColour2($("table#best_limits").find(newId),refPrice,values2[i]);
                }
            });
        },"json");
        $("#warrant_table tr:gt(3)").css("background-color","#000000");
        $("tr#"+stockCode).css("background-color","#636363");
        selectedRowId = stockCode;
    });
}

function onWarrantMouseOver(stockCode)
{
    $(function(){
        if(stockCode!=selectedRowId)
        {
            $("tr#"+stockCode).css("background-color","#0000FF");
        }
    });
}

function onWarrantMouseOut(stockCode)
{
    $(function(){
        $("tr#"+stockCode).filter(":not(#"+selectedRowId+")").css("background-color","#000000");
    });
}

function getScoreboard()
{
    $(function(){
        var dataString  = {get:"30"};
        $.get(path,dataString,function(data){
            $("span#gainers").html(data.gainers);
            $("span#losers").html(data.losers);
            $("span#uchg").html(data.unchanged);
            $("span#untraded").html(data.untraded);
            $("span#vol").html(data.volume);
            $("span#values").html(data.value);
            $("span#trades").html(data.trades);
            updateSummaryBar(data.gainers,data.losers,data.unchanged,data.untraded);
        },"json");
    });
}

function updateSummaryBar(gainers,losers,unchanged,untraded)
{
   var total = gainers + losers + unchanged;
   var gainersLength = Math.round(gainers/total * 93);
   var losersLength = Math.round(losers/total * 93);
   var unchangedLength = 93 - gainersLength - losersLength;
   var grandTotal = total + untraded;
   scoreBoardArray = [[gainers,(gainers/grandTotal * 100).toFixed(2)+"%"],[losers,(losers/grandTotal * 100).toFixed(2)+"%"],[unchanged,(unchanged/grandTotal * 100).toFixed(2)+"%"],[untraded,(untraded/grandTotal * 100).toFixed(2)+"%"]];
   if(unchangedLength <0)
   {
      gainersLength -=1;
   }
   $(function(){
      $("td#bar_g").add("img#img_g").width(gainersLength);
      $("td#bar_l").add("img#img_l").width(losersLength);
      $("td#bar_u").add("img#img_u").width(unchangedLength);
   });
}

function swapScoreboardDisplay()
{
    if(scoreBoardArray!=null)
    {
        $(function(){
          $("span#gainers").html(scoreBoardArray[0][displayType]);
          $("span#losers").html(scoreBoardArray[1][displayType]);
          $("span#uchg").html(scoreBoardArray[2][displayType]);
          $("span#untraded").html(scoreBoardArray[3][displayType]);
          displayType = (displayType + 1) % 2
        });
     }
      setTimeout(swapScoreboardDisplay,10000);
}