/**
 * This function is called when a flash movie of a chart has finished loading
 */
function amChartInited(chart_id) {
	
    GraphsCompact.graphs[chart_id].flash = document.getElementById(chart_id);

    if (chart_id.indexOf('assetChart') !== -1) {
        GraphsCompact.loadChartData( chart_id );
    } else {

    }


}

// This function is called after getData() invocation on the graph object.
// it returns the xml data.
// what we're doing here is updating the last point in the graph with current
// asset rate
function amReturnData(chart_id, data){
    if (GraphsCompact.graphs[chart_id].flash !== null) {
        var currRate = GraphsCompact.graphs[chart_id].currRate ;

        var xid = GraphsCompact.graphs[chart_id].lastXID ;
        if (  null !== currRate && currRate.rate) {

            data = unescape(data);
            var seriesRE = new RegExp('<value xid="'+ xid +'">[0-9:\.]+<\/value><\/series>', 'gmi');
            var graphRE = new RegExp('<value xid="' + xid +'" bullet="\.\.\/\.\.\/appProxy\/circle\.swf">[0-9\.]+<\/value><\/graph>', 'gmi');

            if (chart_id.indexOf('assetChart') !== -1) {

                // Options graphs on the left side
                var xid = GraphsCompact.graphs[chart_id].lastXID /*- 1*/;


                var g = GraphsCompact.graphs[chart_id];
                if (g.appending) {

                    ++g.lastXID;

                   // if there are more than 120 points remove the oldest point
                   if ( g.lastXID > 120 ) {

                       data = data.replace(new RegExp('<series><value xid="[0-9]+">[0-9:\.]+<\/value>', 'gmi'), '<series>')
                                  .replace(new RegExp('<graph gid="0"><value xid="[0-9]+">[0-9\.]+<\/value>'), '<graph gid="0">');
                       //alert('too many points, replacing')
                   }

                   // remove old bullet and place new point
                    data = data.replace(' bullet="../../appProxy/circle.swf"', '')
                                .replace('</series>', '<value xid="'+g.lastXID+'">'+General.timeString+'</value></series>')
                                .replace('</graph>', '<value xid="'+g.lastXID+'" bullet="../../appProxy/circle.swf">' +g.currRate.rate+'</value></graph>');

                    console.log('appending');
                } else {
                    console.log('updating');
                    data = data.replace(seriesRE,  '<value xid="'+ xid +'">'+General.timeString+'</value></series>')
                               .replace(graphRE,  '<value xid="' + xid +'" bullet="../../appProxy/circle.swf">'+currRate.rate+'</value></graph>');

                }
            } else {
                // Open position graph on the right side

                if (xid === null) {
                    xid = 'missing_0';
                }
                data = data.substring(0, data.indexOf('</graph>'));
                // remove old bullet
                data = data.replace('bullet="round" bullet_color="#33567FF" bullet_size="5"', '');
                // place new data entry with new bullet
                data += '<value bullet="round" bullet_color="#33567FF" bullet_size="5" xid="' + xid +'">'+currRate.rate+'</value></graph></graphs></chart>';


                var j = xid.split('_')[1];
                ++j;
                xid = 'missing_' + j;
                GraphsCompact.graphs[chart_id].lastXID = xid;
            }

            GraphsCompact.graphs[chart_id].flash.setData(data);
        } // end if ( null !== currRate)
    }
}

var GraphsCompact = {

    /**
     * This object keeps data about the option graphs, its filled within init()
     */
    graphs: {},

    emptyData: ('<chart><series><value xid="0">0</value></series>'+
                          '<graphs><graph gid="0"><value xid="0">0</value></graph></graphs></chart>'),

    /**
     * Contains all open positions
     */
    openPositionGraphs: {},

    nextUpdate: null,

    initialized: false,

    init: function() {
	 
       $('li.regular .graphContainer').each( function (i) {
           //'data_file' : AppData.url + 'home/getAssetGraphXML/1',

           var chart_id = 'assetChart_' + (i+1);
           $('<div/>').attr('id', chart_id).addClass('assetChart').appendTo(this);

           var assetId = this.id.split('_')[1];
           var optionId = $(this).parents('li').prev('.applyPosition').find('input[name=optionId]').val();

           GraphsCompact.graphs[chart_id] = {
                currRate: null,
                itemName: 'asset_' + assetId + '_' + optionId + '_' + AppData.whiteLabelName,
                lastXID: null,
                flash: null, // This will point to the flash movie, set by amChartInited()
				container: this
           };

           swfobject.embedSWF(
            "sysProxy/amline/amline.swf", chart_id,
            "186", "133", "9.0.0", "sysProxy/expressInstall.swf",
            { path: 'sysProxy/amline/',

              chart_data: encodeURIComponent(GraphsCompact.emptyData),
              chart_id: chart_id,
              settings_file : encodeURIComponent('appProxy/amline/settings.xml')
            },
            {wmode:'opaque'},
            {'class': 'assetChart'});
        });


       GraphsCompact.startStreaming();

    }, // end init()

       startStreaming: function () {

        var page = General.initLightstreamer();

        //console.log('in startStreaming()')

        // Each graph container has an id in this format: graphContainer_<assetId>
        // we need to fill up an array of assetIds which will be sent to lightstreamer
        // for subscription.
        var assetsToSubscribe = [];

		$.each(GraphsCompact.graphs, function(key) {
			if (key.indexOf('assetChart_') !== -1) {
				var assetId = this.container.id.split('_')[1];
				var optionId = $(this.container).parents('li').prev('.applyPosition').find('input[name=optionId]').val();
				this.itemName = 'asset_' + assetId + '_' + optionId + '_' + AppData.whiteLabelName;
				assetsToSubscribe.push (this.itemName);
			}
		});
		/*
        $('div.graphContainer').each(function() {
            var assetId = this.id.split('_')[1];
            
			var itemName = 'asset_' + assetId + '_' + optionId + '_' + AppData.whiteLabelName;
            assetsToSubscribe.push (itemName);

        });
*/
        $('div.open_positions ul.positions li.open_position').each(function() {
            var assetId = this.id.split('_')[3];
            var optionId = $(this).attr('optionid');
            var itemName = 'asset_' + assetId + '_' + optionId ;
           // console.log('curr item from open_position: ' + itemName);
            if (-1 === jQuery.inArray( itemName, assetsToSubscribe) ) {
              // console.log('got item from open_position: ' + itemName);
                assetsToSubscribe.push ( itemName );
            }

        });

        page.removeTable('assetsTable');
        console.log("assets subscribed to: " + assetsToSubscribe);

        var assetsTable   = new NonVisualTable(assetsToSubscribe, ['rate', 'id', 'lastUpdated', 'color', 'pricingRate'], "MERGE");
        page.addTable(assetsTable, "assetsTable");
        assetsTable.onItemUpdate =  GraphsCompact.onItemUpdate; //GraphsCompact.onItemUpdate;
    },

    // This method should be called when user selects another asset from the options drop select box
    notifyAssetChange: function( graphContainer ) {
		
        var chart_id = graphContainer.find('.assetChart').attr('id');

        if (chart_id) {
            GraphsCompact.loadChartData( chart_id );

        }
    },

    /**
     * Calculate next graph update, at every round 30 seconds,
     * if now the time is 12:11:21 then the update will occur in 12:11:30
     */
    calculateNextUpdate: function() {
        var nextUpdate = Math.floor( General.dateTime.getTime() / 30000 ) * 30 + 30;
       // console.log('next update at: ' + (new Date(nextUpdate * 1000)).toString());
        return new Date(nextUpdate * 1000);
    },

    /**
     * Loads a given chart data, chart_id is a key in GraphsCompact.graph object,
     * a chart knows which asset data it should load, the asset id is located
     * in its parent container id ( div#graphContainer_<assetId> ).
     *
     * @param string chart_id - chart to update
     */
    loadChartData: function( chart_id ) {//chart_id =assetChart_x -> <object> elem id

        var assetId = $('#' + chart_id).parent('div.graphContainer').attr('id').split('_')[1];

		var boxList = $('#' + chart_id).parent().parent().parent().prev().prev();
		console.log(boxList.attr('class'))
       $.get(AppData.url + 'home/getAssetGraphXML/' + assetId, function(chart_id) {
            return function(xml) {

                // For charts showing assets
                if (chart_id.indexOf('assetChart') !== -1) {
                    // Get asset id from its parent container's id'
                    var assetId = $('#' + chart_id).parent('div.graphContainer')
                                    .attr('id').split('_')[1];
                    var optionId = $('#' + chart_id).parents('li').prev('.applyPosition').find('input[name=optionId]').val();
                    var itemName = 'asset_' + assetId + '_' + optionId + '_' + AppData.whiteLabelName;
                    GraphsCompact.graphs[chart_id].itemName = itemName;
                }

                //console.log('current chart id is: ' + chart_id + ' and itemName is: ' + GraphsCompact.graphs[chart_id].itemName);



                if ($.trim(xml) !== '' && xml != 'Not tradeable') {
                    GraphsCompact.graphs[chart_id].lastXID = $(xml).find('series value').size();
                    GraphsCompact.graphs[chart_id].currRate = {lastUpdated:  new Number($(xml).find('graph series:last').html()),
                                                        rate: new Number($(xml).find('graph value:last').html())};

                    // problrms on ie $('#feed_asset_' + chart_id.split('_')[1]).html( GraphsCompact.graphs[chart_id].currRate.rate  );

                    if (  GraphsCompact.graphs[chart_id].flash !== null && GraphsCompact.graphs[chart_id].flash.setData) {
                        GraphsCompact.graphs[chart_id].flash.setData(xml);
                    }

                    if (typeof Position !== 'undefined' && Position.onRateChange) {
                        //Position.onRateChange(positionContainer.find('input.rate'), GraphsCompact.graphs[chart_id].currRate.rate);
                        $('#feed_asset_' + chart_id.split('_')[1]).html(GraphsCompact.graphs[chart_id].currRate.rate);

                    }
                } else {
                	console.log('in')
                    GraphsCompact.graphs[chart_id].flash.setData(GraphsCompact.emptyData);
                    GraphsCompact.graphs[chart_id].currRate = null;
                    GraphsCompact.graphs[chart_id].lastXID = -1;

                    if (xml === 'Not tradeable') {
                        $('#feed_asset_' + chart_id.split('_')[1]).html('<div style="position:absolute;width:200px;">Not Tradeable</div>');
                    } else {
                        $('#feed_asset_' + chart_id.split('_')[1]).html('N/A');
                    }



                }

                GraphsCompact.startStreaming();
                //boxList.find('li.currentPosition div').text(AppData.langHome.loading);
				//Home.completeLoadingBoxList(boxList)
            }

        }(chart_id));
    },

    /**
     *
     * Called every lightstreamer clock tick.
     *
     * When called first time, initializes lightstreamer graphs
     *
     * Periodically updates all graphs every round 30 seconds.
     * (e.g 12:20:30 and 12:21:00 are proper update periods)
     *
     * @param timeString - current time in HH:MM:SS format
     */
    onUpdateTime: function() {
	
        if ( !GraphsCompact.initialized ) {
            GraphsCompact.init();
            GraphsCompact.initialized = true;
        }

        if ( GraphsCompact.nextUpdate === null ) {
            GraphsCompact.nextUpdate = GraphsCompact.calculateNextUpdate();
        }


        if (  GraphsCompact.nextUpdate <= General.dateTime ) {
            GraphsCompact.nextUpdate = GraphsCompact.calculateNextUpdate();
        	//console.log('Now updating : nextUpdate = ' + new Date(GraphsCompact.nextUpdate) + ' now = ' + General.dateTime);
            $.each(GraphsCompact.graphs, function(key) {

                if (this.flash) {
                    if (key.indexOf('assetChart') !== -1) {
                        if ( this.currRate && this.currRate.rate) {
                               this.appending = true;
                        }
                    } else {
                        this.appending =  false;

                       //console.log('updating position graph');
                   }
                  this.flash.getData();
                }
            }); // end $.each

            GraphsCompact.nextUpdate = GraphsCompact.calculateNextUpdate();
        } // end if


    },

    /**
     * Lightstreamer callback, update rightmost point of each graph to the
     * newly fetched asset rate.
     */

 onItemUpdate: function(item, itemUpdate, itemName) {
	 console.log('updating: ' + itemName);

        if (itemUpdate.isValueChanged('pricingRate')) {
            var pricingRate = itemUpdate.getNewValue('pricingRate');
            var rate        = itemUpdate.getNewValue('rate');
            // -COLOR HERE
            var color = parseInt(itemUpdate.getNewValue('color'));
            var lastUpdated = itemUpdate.getNewValue('lastUpdated');

            // Iterate each graph and check if its the one being updated
            $.each(GraphsCompact.graphs, function(key) {

               if (  this.itemName  ==  itemName) {
                   this.currRate = { rate:rate, lastUpdated:lastUpdated };

                   console.log('onItemUpdate() Current chart key is:  ' + key + ' and item name is: ' + this.itemName);


                   if ( key.indexOf('assetChart') !== -1 ) {


                       this.appending =  false;
                       if (this.flash) this.flash.getData();

					   // index goes from 0..N and denotes the order of rate reporting boxes
					   // first box is 0, second is 1 etc
					   var index = key.split('_')[1];

                       if (color) {

                       		if($('#feed_asset_' + index).hasClass('longDisabled')){
                       			$('#feed_asset_' + index).html(pricingRate).css('color', '#BBCBBB');
                       		} else {
                       			$('#feed_asset_' + index).html(pricingRate).css('color', '#024301');
                       		}
                       } else {
					   		if($('#feed_asset_' + index).hasClass('longDisabled')){
					   			$('#feed_asset_' + index).html(pricingRate).css('color', '#DAC3C3');
					   		}
					   		else{
					   			$('#feed_asset_' + index).html(pricingRate).css('color', '#C30700');
					   		}

                   	   } // end if (color)

					    // this sets the rate in the box found the put/call form when you click put/call
						$('#putcall_rate_' + index).val(pricingRate);
						console.log('setting: ' + pricingRate + ' putcall box is: ' + $('#putcall_rate_' + index));
                   }

                   if (typeof Position !== 'undefined' && Position.onRateChange) {
                        var positionContainer = $('#feed_asset_' + index).parents('.positionContent');
                        // fill current rate in the put/call form.
                        Position.onRateChange(positionContainer.find('input.rate'), pricingRate);
                   }

               }

            }); // end $.each
        }
    } // end onItemUpdate()
};


