/*
    Document   : MyPositions
    Created on : 09/08/2010
    Author     : Nadav
    Description:
        Purpose of the js: my positions code for all platforms
*/
var MyPositions  =  {
        container: null,
        todayOpenPositions : new Array(), //array of objects that contains position that closed today
        positionDialog: null,
        rollOverPercentage: 30, /* set the percentage to the new position using roll over function - need to move to site options */
        openDialogGraphs: {},

        init: function(){
                MyPositions.container = $('div.container');
                MyPositions.fillTodayOpenPositions();
                
                MyPositions.updateMyPayout();
                MyPositions.container.find('#lastExpires').bind('click',{},MyPositions.lastTrades);
                MyPositions.container.find('#myTrades').bind('click',  MyPositions.myTrades);
                MyPositions.container.find('#oneTouchPositions').bind('click',  MyPositions.oneTouchPositions);
        },

        /* run through the open positions elements on the page and fill the today open positions array */
        fillTodayOpenPositions: function(){
            MyPositions.todayOpenPositions = null; /* reset current array */
            MyPositions.todayOpenPositions = new Array(); /* reset current array */
            
            // Click on a position, expands it and shows a graph
            $('div[class="open_positions today"] ul li.open_position').each(function(){
                $('div.showGraphBtn',$(this)).unbind('click',MyPositions.onClickGraph).bind('click',{},MyPositions.onClickGraph);
                //$(this).unbind('click',MyPositions.onClickPosition).bind('click',{},MyPositions.onClickPosition);
                
                /* roll over and double up */
                $(this).find('li.tools div.rollOver').unbind('click',MyPositions.onClickRollOver).bind('click',{},MyPositions.onClickRollOver);
                $(this).find('li.tools div.x2').unbind('click',MyPositions.onClickDoubleUp).bind('click',{},MyPositions.onClickDoubleUp);
                
                var endDate = new Date(parseInt($(this).attr('enddate')) * 1000);

                var optionId         = parseInt($(this).attr('optionId'));
                var assetId          = parseInt($(this).attr('id').split('_').slice(3,4));
                var positionId       = parseInt($(this).attr('id').split('_').slice(2,3));
                var elementId        = 'open_position_' + positionId + '_' + assetId;
                var noPositionTime   = parseInt($(this).attr('times').split('_').slice(0,1));
                var lastPositionTime = parseInt($(this).attr('times').split('_').slice(1,2));
                var noRollOverTime 	=  parseInt($(this).attr('norollover'));
                var liElem = $('div[class="open_positions today"]').find('li[id*="open_position_' + positionId +'_"]');
                var type="regular";
                /* if not found it's a one touch position */
                if (!liElem.length){
                    liElem = $('div[class="open_positions today"]').find('li[id*="open_positiononetouch_' + positionId +'_"]');
                    var type = 'onetouch';
                }

			var timeLeftElem = liElem.find('li.timeLeft');

                MyPositions.todayOpenPositions.push({
                                                    id: positionId,
                                                    elementId: elementId,
                                                    optionId: optionId,
                                                    endDate: parseInt($(this).attr('enddate')) * 1000,
                                                    timeLeftElem: timeLeftElem,
                                                    /*the LI element of the position in the my trades section*/
                                                    liElem: liElem,
                                                    noPositionTime:noPositionTime,
                                                    lastPositionTime:lastPositionTime,
                                                    noRollOverTime: noRollOverTime,
                                                    type: type /* regular position or one touch */
                                                });
            });
        },

        /* this function is called every second
         * Check the conditions for double and rollover buttons and enable/disable these buttons*/
        onUpdateTime: function() {
            if (MyPositions.todayOpenPositions){
                /* find positions with this option id and disable double up button */
               $.each(MyPositions.todayOpenPositions , function(index,elem){
                    /* time difference between option end time and now */
                    var that = $(this)[0];
                    
                    var timeDifference =  (that.endDate.getTime() - General.dateTime.getTime())/1000;
					if(timeDifference < that.noRollOverTime * 60)
						MyPositions.enableDisableButtons(that.elementId , 'disable');
					
                    //$('li#' + that.elementId).find('li.tools div.x2, li.tools div.x2disabled , li.tools div.rollOver, li.tools div.rollOverdisabled').attr('style', '');
               });
            }
        },

        /* Check the conditions for double and rollover buttons and enable/disable these buttons*/
        enableDisableButtons: function(elementId,status){
            /* if there are today open positions */
            if (MyPositions.todayOpenPositions){
               if (status == 'disable'){
                    $('li#' + elementId).find('div.rollOver').addClass('rollOverdisabled')
                                        .unbind('click').bind('click',{},function(event){
                                                                                    General.dialog(AppData.langHome.cannotRollover, AppData.langHome.error);
                                                                                    General.stopPropagation(event);
                                                                                   });
               }
               else if (status == 'enable'){
                  $('li#' + elementId).find('div.rollOverdisabled').removeClass('rollOverdisabled')
                                      .unbind('click').bind('click',{},MyPositions.onClickRollOver);
               }
            }
        },

       
       onClickRollOver: function(event){
           if($(this).hasClass('rollOverdisabled')){
//                console.log('disabled');
                return;
           }

           var liElem = null;
               liElem         = $(this).parents('li.open_position');
           var optionId       = liElem.attr('optionid');
           var newOptionId    = null;
           
           /* if small button is clicked */
           var positionId     = liElem.attr('id').split('_').slice(2,3)[0];

           var positionAmount = null;
           var positionRate   = null;
           var position       = null; /* call/put */
           var assetId        = null;
           var expiryExists   = false; /* true if future expiries exists and we can choose them */
           
           /* profit and loss of the new option */
           var profit = null;
           var loss = null;
           
           /*$('div#dialog2').find('div.firstRow div.right').html(expiryTime);*/
           var optionsIds = new Array();
           var endTime = null;
           var expirySelect = null;
           var currentExpiryTime = null;
           var currentOptionEndTime = null;

           optionsIds[0] = parseInt(optionId);
           $.ajax({
                    type: "POST",
                    url:AppData.url + AppData.pageId + '/getOptionEndDate',
					data:{optionIds: JSON.stringify(optionsIds)},
                    async:false,
                    dataType:'json',
                    error: function(){
                        console.log("cant rollover: general error");
                      General.dialog(AppData.langHome.error, AppData.langHome.error)
                      return;
                    },
                    success:function(data){
                       endTime = new Date(data[0].endDate + AppData.timeZoneOffset);

                       assetId = data[0].assetId;

                        /* the timestamp of current option endTime */
                        currentOptionEndTime = data[0].endDate / 1000;
                       }
                   });

            var hours   = endTime.getHours();
            var minutes = endTime.getMinutes();
            if (hours<10)   hours = '0' + hours;
            if (minutes<10) minutes = '0' + minutes;
            currentExpiryTime = hours + ':' + minutes;
			

          $.ajax({
                     type: "POST",
                     url: AppData.url + AppData.pageId + '/getAssetOpenOptions',
                     data:{assetId: assetId},
                     async:false,
                     dataType:'json',
                     success: function(objectRecieved){
                            if(typeof objectRecieved!= 'object'){
                                //Home.refresh(); // if there is no open options for specific asset then refresh page
                            }
                            var optionsByDate = objectRecieved.options;
                            /* insert expiry times into select box */
                            $.each(optionsByDate, function(key, option){
                               if (key == "today"){
                                   /* show only todays options */
                                   if (option){
                                        expirySelect = $('<select>').addClass('expirySelect');
                                        var optionStr = '';
                                        $.each(option, function(key, todayOption){
                                            /* show only today future expiry times */
                                            if (todayOption.endDateUnix > currentOptionEndTime)
                                                optionStr += '<option value=' + todayOption.id + '>' + todayOption.expireTime + '</option>';
                                        });
                                        if (optionStr != ''){
                                            expiryExists = true;
                                        }
                                        expirySelect.append(optionStr);
                                        /* check if last today option is allowed for rollover */
                                        if (AppData.siteOptions['lastDayOptionRollover']['value'] == ''){
                                            /* not allowed - delete last option from the expire time select */
                                            expirySelect.find('option:last').remove();

                                            /* check how many options exists in rollover */
                                            if (!expirySelect.find('option').length)
                                                expiryExists = false;
                                        }
                                   }
                               }
                               
                            });
                     }
				//var selectedOption = Home.loadOptions(element, optionsByDate);
                 });

              if (!expiryExists){
                  console.log("cant rollover: noFuturesExpiries");
                  General.dialog(AppData.langHome.noFuturesExpiries,AppData.langHome.error);
                  event.preventDefault();
                  return false;
              }
              
              var prevPositionAmount = null;// previous amount of the position
              $.ajax({type: "POST",
                    url:'rpcProxy/getPositionInfo/' + positionId,
                    async:false,
                    success: function(data){
                        /* fill the missing parameters for the newPosition RPC call */

                        /* calculate the amount for the new position */
                        /* the new position amount */
                        positionAmount = parseFloat(data.amount * (MyPositions.rollOverPercentage/100) + parseInt(data.amount)).toFixed(2);
                        profit = data.profit;
                        loss   = data.loss;
                        position = data.position;
                        
                        prevPositionAmount = data.amount;
                    },
                    dataType: 'json'
                });

             
          /*destory old dialog, if exists*/
          if(MyPositions.positionDialog !== null){
              MyPositions.positionDialog.remove();
              MyPositions.positionDialog = null;
              $('div.ui-dialog').remove();
              $('#rolloverDialog').remove();
          }
          /* insert the data into the dialog */
          //var dialogDiv =  $('#dialog2')//.clone()
          var dialogDiv =  $('#dialog2').clone()
                                .attr('id', 'rolloverDialog');
          dialogDiv.find('div.firstRow   div.right').html(currentExpiryTime).end()
          .find('div.secondRow  div.right').html(expirySelect).end()
          .find('div.thirdRow   div.right').html(positionAmount + AppData.accountCurrency);

           /* Show confirmation window */
           /*var temp      =  $('div#dialog2').html();
           var dialogDiv =  $('<div/>').html(temp).addClass('platformDialog');*/
           MyPositions.positionDialog = dialogDiv;
           
           MyPositions.positionDialog.dialog({
                autoOpen: false,
                width: '280',
                height: '300',
                modal:true,
                resizable: false,
                dialogClass: 'platformDialog rollover_dialog bbinary_dialog',
                closeText: 'X' //TODO:this will need to be tanslatable
           });

           MyPositions.positionDialog.parent()
                .find('a.ui-dialog-titlebar-close span.ui-icon').removeClass('ui-icon');

           $('#rolloverDialog').find('select').selectbox(
				{
					inputClass: 'selectboxTime',
					containerClass: 'selectbox-wrapperTime',
					scrollBar: true,
					chainTitle: true
				}
            );

           /* events for buttons */
           /* apply button */
           MyPositions.positionDialog.find('button.btnApply').unbind('click').bind('click',{},function(){
               newOptionId = dialogDiv.find('div[id="_container"] ul li.selected').attr('id').split('_').splice(2,1)[0];

               if (MyPositions.positionDialog != null)
                    MyPositions.positionDialog.dialog('close');
                    $('div.ui-dialog').remove();
                    $('div#rolloverDialog').remove();

                 $.post(
                    'rpcProxy/rollover',
                     {
                                positionId: positionId,
                                optionId  : newOptionId,
                                assetId   : assetId,
                                newAmount:  positionAmount,
                                percentage: MyPositions.rollOverPercentage
                      },
                            function(data){
                                if (data.status == 'true'){
                                    /* no errors */
                                    /* create params as in new position form */
                                    var params = new Array();

                                    params[0] = new Array();
                                    params[1] = new Array();
                                    params[2] = new Array();
                                    params[3] = new Array();
                                    params[4] = new Array();
                                    params[5] = new Array();


                                    params[0]['name'] = 'amount';
                                    params[0]['value'] = positionAmount;
                                    params[1]['name'] = 'position';
                                    params[1]['value'] = positionId[0];
                                    params[2]['name'] = 'optionId';
                                    params[2]['value'] = optionId;
                                    params[3]['name'] = 'assetId';
                                    params[3]['value'] = assetId;
                                    params[4]['name'] = 'profit';
                                    params[4]['value'] = profit;
                                    params[5]['name'] = 'loss';
                                    params[5]['value'] = loss;

                                     //Apply browser (user) timezone offset, to correct times
									var userTime = new Date();	
                                    var newPositionEndTime = new Date(data.endDate * 1000 + AppData.timeZoneOffset);
                                    
                                    var newHours   = newPositionEndTime.getHours();
                                    var newMinutes = newPositionEndTime.getMinutes();
                                    if (newHours<10)   newHours = '0' + newHours;
                                    if (newMinutes<10) newMinutes = '0' + newMinutes;
                                   
                                    liElem.find('li.investment').html(positionAmount + AppData.accountCurrency);
                                    liElem.find('li.expireTime').html(newHours + ':' + newMinutes);
                                    liElem.attr('optionId',newOptionId);
                                    liElem.attr('endDate',data.endDate);

                                    var elementClasses = liElem.attr('class').split(' ');
                                    $.each(elementClasses, function(index, elem){
                                        if(elem.indexOf('optionPosition') !== -1){
                                            liElem.removeClass(elem);
                                            liElem.addClass('optionPosition' + newOptionId);
                                        }
                                    })

                                    /* update today open positions */
                                    MyPositions.fillTodayOpenPositions();
                                    liElem.addClass('special'); /* yellow background*/


                                    //Update balance
                                    var currentBalance = parseInt($('#currentBalance').text());
                                    $('#currentBalance').text(currentBalance - (positionAmount - prevPositionAmount));
                                }
                                else{
                                    //console.log('cant rollover: '+data.status);
                                    switch(data.status){
                                        case 'notLoggedIn':
                                            General.dialog(AppData.langHome.notLoggedIn,AppData.langHome.error)
                                            break;
                                        case 'optionIsClosed':
                                            General.dialog(AppData.langHome.optionIsClosedErrorPopupMessage,AppData.langHome.error)
                                            break;
                                        case 'insuficientFunds':
                                            General.dialog(AppData.langHome.insufficientFundsIsErrorPopupMessage,AppData.langHome.error);
                                            break;
                                        case 'invalidPositionRate':
                                            General.dialog(AppData.langHome.positionRateIsInvalid,AppData.langHome.error);
                                            break;
                                        case 'suspended':
                                            General.dialog(AppData.langHome.optionSuspended,AppData.langHome.error);
                                            break;
                                        case 'riskSuspentionActivated':
                                            General.dialog(AppData.langHome.riskSuspentionPopupMessage,AppData.langHome.error);
                                            break;
										case 'noTime':
											General.dialog(AppData.langHome.noRolloverTimePopupMessage,AppData.langHome.error);
											break;
										case 'positionWinning':
											General.dialog(AppData.langHome.positionIsWinningPopupMessage,AppData.langHome.error);
											break;
                                        case 'numberOfRolloversExceeded':
                                            General.dialog(AppData.langHome.numberOfRolloversExceededPopupMessage,AppData.langHome.error);
                                            break;
                                        case 'error':
                                            General.dialog(AppData.langHome.error,AppData.langHome.error);
                                            break;
                                    }
                                }
                            },
                            'json'
                       );
                 if (MyPositions.positionDialog != null){
                    MyPositions.positionDialog.dialog( "destroy" );
                    MyPositions.positionDialog = null;
                 }
               });
               
           /* cancel button */
           MyPositions.positionDialog.find('button.btnCancel').unbind('click').bind('click',{},function(){
               MyPositions.positionDialog.dialog('close');
               if (MyPositions.positionDialog != null){
                 MyPositions.positionDialog.dialog('destroy');
                 MyPositions.positionDialog = null;
                 $('div.ui-dialog').remove();
                 $('div#rolloverDialog').remove();
               }
           });
           
           /* close button */
           MyPositions.positionDialog.parent().find('a.ui-dialog-titlebar-close').unbind('click').bind('click',{},function(){
             if (MyPositions.positionDialog != null){
                 MyPositions.positionDialog.dialog('destroy');
                 MyPositions.positionDialog = null;
                 $('div.ui-dialog').remove();
                 $('div#rolloverDialog').remove();
               }
           });
           
           
           MyPositions.positionDialog.dialog('open');
           //$('#rolloverDialog').css('height', '');//quick fix
           
           event.stopPropagation();//prevent of opening graph container
           
       },

       /* Double up functionality
        * Create new position with the same values as current position
        */
       onClickDoubleUp: function(event){
           if($(this).hasClass('x2disabled')){
                //console.log('disabled');
                return;
           }
           var that = $(this);
           /* show dialog */
           var dialogDiv =  $('#dialog1').clone()
                                .attr('id', 'doubleUpDialog');

           MyPositions.positionDialog = dialogDiv;
           MyPositions.positionDialog.dialog({
                title: AppData.langHome.newPositionIsMade,
                autoOpen: false,
                resizable: false,
                width: '300',
                height: '230',
                modal:true,
                dialogClass: 'bbinary_dialog',
                closeText: 'X' //TODO:this will need to be tanslatable
           });
           MyPositions.positionDialog.parent()
                .find('a.ui-dialog-titlebar-close span.ui-icon').removeClass('ui-icon');

            MyPositions.positionDialog.parent()
                .find('a.ui-dialog-titlebar-close').unbind('click').bind('click',{},function(){
                    $('div.ui-dialog').remove();
                    $('#doubleUpDialog').remove();
                    MyPositions.positionDialog.dialog('close');
                });

                
            /* apply button */
            MyPositions.positionDialog.find('button.btnApply').unbind('click').bind('click',{},function(){
                MyPositions.positionDialog.dialog('close');
                $('div.ui-dialog').remove();
                $('#doubleUpDialog').remove();


               /* if small button is clicked */
               var liElem     = that.parents('li.open_position');
               var positionId = liElem.attr('id').split('_')[2];

               /* if large button is clicked */
               if (typeof(positionId) == 'undefined'){
                   positionId = that.parent().parent().parent().attr('id').replace(/\D/g,'');
               }

               var amount     = null;
               var position   = null;
               var assetId    = null;
               var loss       = null;
               var profit     = null;
               var optionId   = null;

               var params = new Array();

               $.ajax({type: "POST",
                        url:'rpcProxy/getPositionInfo/' + positionId,
                        async:false,
                        success: function(data){
                            /* fill the missing parameters for the newPosition RPC call */
                            amount   = data.amount;
                            position = data.position;
                            assetId  = data.assetId;
                            loss     = data.loss;
                            profit   = data.profit;
                            optionId = data.optionId;
                        },
                        dataType: 'json'
                    });
               /* create new position */
               $.ajax({
                        type: "POST",
                        url: 'rpcProxy/newPosition',
                        data: "amount=" + amount + "&position=" + position + "&assetId=" +assetId + "&loss=" + loss + "&profit=" + profit + "&optionId=" + optionId,
                        async: false,
                        dataType: 'json',
                        error : function() {
                            General.dialog(AppData.langHome.error,AppData.langHome.error)
                        },
                        success: function(result){
                                /*** end of bug fix ***/
                            if (typeof result == 'object') {

                                /* create params as in new position form */
                                var params = new Array();

                                params[0] = new Array();
                                params[1] = new Array();
                                params[2] = new Array();
                                params[3] = new Array();
                                params[4] = new Array();
                                params[5] = new Array();


                                params[0]['name'] = 'amount';
                                params[0]['value'] = amount;
                                params[1]['name'] = 'position';
                                params[1]['value'] = position;
                                params[2]['name'] = 'optionId';
                                params[2]['value'] = optionId;
                                params[3]['name'] = 'assetId';
                                params[3]['value'] = assetId;
                                params[4]['name'] = 'profit';
                                params[4]['value'] = profit;
                                params[5]['name'] = 'loss';
                                params[5]['value'] = loss;

                                /* add new position */
                                Position.addPosition(params, result , function(){
                                         /* after position added do some animation
                                        * the scroll is a bit tricky because we don't have the last position in the positions list when we want to scroll there
                                        * The solution: get the last positions id and get the height of this LI
                                        * then we scroll to last position LI -5 pixels */
                                       var idOfLastPosition =  $('ul.positions li[id*="open_position_"]:last').attr('id');
                                       var myPos = MyPositions.findPos(document.getElementById(idOfLastPosition));

                                       //$('body').scrollTo( parseInt(myPos[1] - 5) + 'px',800);

                                       /* animate the background of the positions LI */
                                       var new_pos = $('ul.positions li[id*="open_position_"]:last')
                                       new_pos.fadeTo(800, 0.5, function(){});
                                       new_pos.fadeTo(800, 1, function(){});
                                       new_pos.addClass('special'); /* change background of the element */

                                       MyPositions.positionDialog.dialog('destroy');
                                       MyPositions.positionDialog = null;

                                       /* update payout */
                                       MyPositions.updateMyPayout();
                                }, 'open', false);

                                 /* prevent openning graph */
                                 event.stopPropagation();

                               /* The new position is made - show popup */
                                         /* insert the data into the dialog */
                              if(MyPositions.positionDialog !== null){
                                  MyPositions.positionDialog.dialog( "destroy" );
                              }
                               return false;

                            } else { //Error! -> user not logged in
                                switch(result){
                                    case 'notLoggedIn':
                                        General.dialog(AppData.langHome.notLoggedIn,AppData.langHome.error)
                                        break;
                                    case 'optionIsClosed':
                                        General.dialog(AppData.langHome.optionIsClosedErrorPopupMessage,AppData.langHome.error)
                                        break;
                                    case 'insufficientFunds':
                                        General.dialog(AppData.langHome.insufficientFundsIsErrorPopupMessage,AppData.langHome.error);
                                        break;
                                    case 'invalidPositionRate':
                                        General.dialog(AppData.langHome.positionRateIsInvalid,AppData.langHome.error);
                                        break;
                                    case 'suspended':
                                        General.dialog(AppData.langHome.optionSuspended1,AppData.langHome.error);
                                        break;
                                    case 'riskSuspentionActivated':
                                        General.dialog(AppData.langHome.riskSuspentionPopupMessage,AppData.langHome.error);
                                        break;
                                    case 'error':
                                        General.dialog(AppData.langHome.error,AppData.langHome.error)
                                        break;
                                }

                                  event.stopPropagation();
                            }
                       }
                    });
               });
               MyPositions.positionDialog.dialog('open');
                MyPositions.positionDialog.find('button.btnCancel').unbind('click').bind('click',{},function(){
                    MyPositions.positionDialog.dialog('close');
                    /* when closing the dialog - the dialog div stays on the page. we need to remove it manually */
                    $('div.ui-dialog').remove();
                    $('div#doubleUpDialog').remove();
                    return;
            });


            
            return false;
       },
       
    addTodayPosition : function(positionProps, optionProp, params) {
				var positionId = positionProps.positionId;
                var positionRate   = positionProps.positionRate;
                var positionPayout = positionProps.positionPayout;
                //console.log(positionPayout);

                //var positionDate   = positionProps.positionDate;
                var positionDate = new Date();
                
        		var optionEndDate = new Date(parseInt(optionProp['endDate']) + AppData.timeZoneOffset);
            	var optionEndHour = optionEndDate.getHours();
            	var optionEndMinute = optionEndDate.getMinutes();
                var optionEndMonth = optionEndDate.getMonth() + 1; /* starts with 0 */
                var optionEndYear = optionEndDate.getFullYear();
            	//if(optionEndHour < 10 ) optionEndHour = '0' + optionEndHour;
            	//if(optionEndMinute < 10) optionEndMinute = '0' + optionEndMinute;

            	var optionEndMinute = optionEndDate.getMinutes();
            	if(optionEndHour   < 10) optionEndHour   = '0' + optionEndHour;
            	if(optionEndMinute < 10) optionEndMinute = '0' + optionEndMinute;
                if(optionEndMonth  < 10) optionEndMonth  = '0' + optionEndMonth;
                if(optionEndYear   < 10) optionEndYear   = '0' + optionEndYear;


		//var posDate = new Date((parseInt(positionDate)*1000 + parseInt(AppData.timeZoneOffset)));
                var posDate = new Date(parseInt(positionDate.getTime()) + parseInt(AppData.timeZoneOffset));
				var positionDateHours   = posDate.getHours();
				var positionDateMinutes = posDate.getMinutes();
				if(positionDateHours < 10 ) positionDateHours = '0' + positionDateHours;
            	if(positionDateMinutes < 10) positionDateMinutes = '0' + positionDateMinutes;

                          console.log('positionDate');
                console.log(positionDate);
                console.log(positionDate);

                /* type of position regular or custom */
                var type=false;
                if (optionProp.ownedBy != 0)
                    type = 'custom';
                else
                    type = 'regular'

                    /* remove the open_position_last class from the last li element */
                    $('ul.positions li.noPositionsMessage').addClass('hidden');
                    $('ul.positions li.open_position:last').removeClass('open_position_last');
                
                    positionTodayHTML = '<li id="open_position_' + positionId + '_' + optionProp['assetId'] + '" class="open_position open_position_last optionPosition'+ optionProp['id'] + '" optionid="' + optionProp['id'] + '" endDate="' + optionProp['endDate']/1000 +  '" profit="' + optionProp['profit'] + '" loss="' + optionProp['loss'] + '" payout="0" times="' + optionProp['noPositionTime'] + '_' + optionProp['lastPositionTime'] + '" norollover="' + optionProp['noRolloverTime'] + '" optiontype=' + type +'" ';
                    positionTodayHTML +=   ' direction="' + params.position.toLowerCase() +'">';
					positionTodayHTML +=	'<ul class="positionDetails">';
                    positionTodayHTML +=	'<li class="id">' + positionId+ '</li>';
					positionTodayHTML +=	'<li class="name" title="' + optionProp['assetName'] + '">' + optionProp['assetName'] + '</li>';
                    positionTodayHTML +=    '<li class="strikeRate">' + positionRate + '</li>';
					positionTodayHTML +=    '<li class="currentRate">' + positionRate + '</li>';
                    positionTodayHTML +=	'<li class="arrow"><img src="appProxy/site/home/optionArr' + MyPositions.capitaliseFirstLetter(params.position) + '.png"><span class="type">&nbsp;<b>' + params['position'].toLowerCase() +'</b></span></li>';
                    positionTodayHTML +=	'<li class="date">'  + positionDateHours + ":" + positionDateMinutes + '</li>';
					/* positionTodayHTML +=	'<li class="timeLeft">...</li>'; */
                    positionTodayHTML +=	'<li class="expireTime">' + optionEndHour + ":" + optionEndMinute + '</li>';
					positionTodayHTML +=	'<li class="investment">' + AppData.accountCurrency + params.amount + '</li>';
					positionTodayHTML +=	'	<li class="payout">' + AppData.accountCurrency + positionPayout +'</li>';
					positionTodayHTML +=	'	<li class="chart"><div class="showGraphBtn"></div></li>';
					positionTodayHTML +=    '<li class="clock_disabled tools"><div class="controls">';
                                        if (optionProp['ownedBy']==0)
                    positionTodayHTML +=    '<div class="rollOver rollOverdisabled"></div>';
                    positionTodayHTML +=    '<div class="x2"></a></div></li>';
                    positionTodayHTML +=	'</ul>';
					positionTodayHTML += '</li>';
                      

					$('ul.positions').append(positionTodayHTML).find('li.name').truncate(15);
					$('ul.positions')
						.find( '#open_position_' + positionId + '_' + optionProp['assetId'])
						.find('div.showGraphBtn').unbind('click',MyPositions.onClickGraph).bind('click',{},MyPositions.onClickGraph).end()
                        .find('div.rollOver').unbind('click',MyPositions.onClickRollOver).bind('click',{},MyPositions.onClickRollOver).end()
                        .find('div.x2').unbind('click',MyPositions.onClickDoubleUp).bind('click',{},MyPositions.onClickDoubleUp);

                        if (optionProp.ownedBy != 0){
                            $('ul.positions').find( '#open_position_' + positionId + '_' + optionProp['assetId'])
                                             .find('div.rolloverDiv').remove();
                            $('ul.positions').find( '#open_position_' + positionId + '_' + optionProp['assetId'])
                                             .find('div.x2Div').css('margin-left','85px');
                        }


					///$('ul.positions').show(); this is not working
					MyPositions.container.find('div.noPositionsMessage').hide();
					$('div.today').removeClass('hidden');
				
                    try{
                    var liElem = $('div[class="open_positions today"]').find('li[id*="open_position_' + positionId +'_"]');
					var timeLeftElem = liElem.find('li.timeLeft');
					MyPositions.todayOpenPositions.push({
														id: parseInt(positionId),
														optionId: parseInt(params.optionId),
                                                        elementId: 'open_position_' + positionId + '_' + positionProps.assetId,
														endDate: parseInt(optionProp['endDate']),
                                                        noPositionTime:parseInt(optionProp['noPositionTime']),
                                                        lastPositionTime:parseInt(optionProp['lastPositionTime']),
                                                        noRollOverTime:optionProp['noRolloverTime'],
                                                        ownedBy:optionProp['ownedBy'],
                                                        liElem: liElem,
														timeLeftElem: timeLeftElem
													});
                    }catch(ex){
                        console.log(ex);
                    }
                    /* update open trades payout */
                    var payoutElement = $('div.open_positions div.content div.openTradesPayout div.payoutAmount');
                    var currentPayoutAmount = parseFloat(payoutElement.html().substr(1));
                    var newPayout = currentPayoutAmount + parseFloat(params.amount);
                    payoutElement.html(AppData.accountCurrency + newPayout.toFixed(2));
                    
                    /* add this position to global_positions table in gcp */
                    $.get(
                            'rpcProxy/addGlobalPosition/' + positionId,
                            {},
                            function(data){

                            },
                            'json'
                            );
    },
/**
     * When a customer clicks on an open position item a container with a graph and a flip
     * button is created, it looks like this:
     *
     * <div id="openPositionGraphContainer_<positionId>">
     *  <div id="openPositionGraphContainer_<positionId>_">
     *     <!-- Here the flash object gets created, it replaces this div -->
     *  </div>
     *
     *  <input type="button" class="flipPositionButton" />
     *
     * </div>
     */
    onClickGraph: function() {
        var currentItem = $(this).parents('li.open_position');
        //console.log(currentItem);
        var domCurrentItem = currentItem[0];

        var parts = domCurrentItem.id.split('_');
        var positionId = parts[2];
        var assetId    = parts[3];
        var optionId = currentItem.attr('optionId');
		var positionType = currentItem.attr('type');

        var containerId = 'openPositionGraphContainer_' + positionId;
		var graphContainerId = containerId + '_';
        //console.log(currentItem)

        if ( 0 === $('#' + containerId).size() ) {


               var assetName = currentItem.find('li.name').html()        
             var dialogTitle = "<div class='info'><span class='name'>"+assetName + '</span>&nbsp;';
             dialogTitle += "<span class='expireTime'>"+currentItem.find('li.expireTime').html() + '</span>&nbsp;';
             dialogTitle += "<span class='investment'>"+currentItem.find('li.investment').html() + '</span>&nbsp;';
             dialogTitle += "<span class='direction'>"+currentItem.find('li.arrow').html() + '</span>&nbsp;';
             dialogTitle += "<span class='strikeRate'>"+currentItem.find('li.strikeRate').html() + '</span>&nbsp;';
             dialogTitle += "</div><br/>";
             
                
                            var graphDiv = $('<div/>').attr('id', containerId).css('display','block')
                        .attr('data-positionId', positionId)
                       .append( $('<div/>')
                                .attr('id', graphContainerId)
								.addClass('positionGraph')
                                .html('<img height="16" width="16" src="appProxy/loading.gif"> Loading Graph...')
                        );
                        var graphDiv =  dialogTitle + graphDiv.html();  
                MyPositions.graphDialog(graphDiv, 'Position Id: '+positionId, optionId);
			Graphs.graphs[graphContainerId] = {
                    currRate: new Array(0, 0),
                    itemName: 'asset_' + assetId + '_' + optionId + '_' + AppData.whiteLabelName,
					series : {},
					options : {}
             };
			$.ajax({
                url: AppData.url + 'home/getOpenPositionGraphJSON/' + positionId,
                method: 'GET',
                dataType: 'json',
                success: function (graphData) {

					Graphs.graphs[graphContainerId].series = [ graphData.series ];
					Graphs.graphs[graphContainerId].options = graphData.options;
					Graphs.redraw(graphContainerId);

					Graphs.startStreaming();
				}

				
			});
                }
       },
      /*OLD onMinuteEnd: function(){
		$.each(MyPositions.todayOpenPositions, function(i, todayPosition){
			if(todayPosition.endDate.getTime() < General.dateTime.getTime()){
				Position.onOptionEnd(todayPosition.optionId)
				delete 	MyPositions.todayOpenPositions[i];
                }

		});
       },*/
       onMinuteEnd: function(){
		//var d = new Date();
      	for(var i = MyPositions.todayOpenPositions.length - 1; i>=0; i--){
			if(MyPositions.todayOpenPositions[i].endDate/1000  <= Math.round((General.dateTime.getTime() - AppData.timeZoneOffset)/1000)){
				MyPositions.onOptionEnd(MyPositions.todayOpenPositions[i].optionId);
                MyPositions.todayOpenPositions.splice(i,1);
			}
      	}
		//if no open positions
		if (!MyPositions.todayOpenPositions.length && $('div.myPositionsTabsEmpty li#myTrades').hasClass('selected'))
			Home.container.find('div.noPositionsMessage').show();
		else
			Home.container.find('div.noPositionsMessage').hide();
       },
	onOptionEnd : function (optionId) {
//        console.log('option end ' + optionId);
//        console.log($('li.optionPosition' + optionId));
        //close the dialog graph, if open, for positions of this option
        $('div.dialogGraphOptionId'+optionId).remove();
$('li.optionPosition' + optionId).remove();//remove all positions
        /* check if custom options has been expired */
        OptionsBuilder.onMinuteEnd();
       },

    /* this function finds the coordinates of obj element in the page and returns (x,y) of the element*/
	findPos: function(obj)  {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
				curleft = obj.offsetLeft
				curtop = obj.offsetTop
				while (obj = obj.offsetParent) {
						curleft += obj.offsetLeft
						curtop += obj.offsetTop
				}
		}
		return [curleft,curtop];
	},


    /* update My Payout in open positions according to the positions rate */
    updateMyPayout: function(){
        /* save total amount of open positions */
		var totalAmount = 0;
		/* used for calculation of current real time payout */
		var totalPayout = 0;

		$('div.open_positions div.content ul.positions li[id*="open_position_"]').each(function(){
			totalAmount += parseFloat($(this).find('li.investment').html().substr(1));
            totalPayout += parseFloat($(this).find('li.payout').html().substr(1));
			//totalPayout += parseFloat($(this).attr('payout'));
		});
        
		var myPayout = parseFloat(totalPayout) - parseFloat(totalAmount);
		if (myPayout > 0){
			$('div.open_positions div.openTradesPayout div.payoutAmount')
			.html(AppData.accountCurrency + parseFloat(totalPayout).toFixed(2))
			.css('color','#006e00');
		}
		else if(myPayout < 0){
			$('div.open_positions div.content div.openTradesPayout div.payoutAmount')
			.html(AppData.accountCurrency + parseFloat(totalPayout).toFixed(2))
			.css('color','#bc7979');
		}else{
			$('div.open_positions div.content div.openTradesPayout div.payoutAmount')
			.html(AppData.accountCurrency + parseFloat(totalPayout).toFixed(2))
			.css('color','#aaaaaa');
		}
                $('ul.positions').find('li.name').truncate(15);
    },

    /* update payout in the positions LI in the open positions section */
    updatePositionPayout: function(itemName,pricingRate){

        //console.log('** in update position payout **');

        var elem = null;
        /* find this element in open positions */
        var optionId = itemName.split('_').splice(2,1)[0];


                       /* update rates in open positions */
			 var elem = $('ul.positions li.optionPosition'+optionId);


			 $.each(elem,function(index,element){
                             
				var elem = $(this);
                                var elemId = elem.attr('id');
				if (!elem.hasClass('close_position')){
                    //var positionType = elem.find('span.type').text().toLowerCase();
					var positionType = elem.attr('direction');
					var strikeRate   = elem.find('li.strikeRate').html();
					//var payout       = elem.find('li.payout');
					var payout       = elem.find('li.payout');
					//var payout       = parseFloat(elem.find('li.payout').html().substr(1))
					var amount       = parseFloat(elem.find('li.investment').html().substr(1)); //without the currency sign
                    //console.log('amount = ' + amount);
					var profit       = parseFloat(parseInt(elem.attr('profit')));
					var loss         = parseFloat((elem.attr('loss')));

					elem.find('li.currentRate').html(pricingRate)
					.animate({backgroundColor: '#BB923E'}, 150).animate({backgroundColor: '#E7E9EB'}, 300);

					/* update payout color in open positions - only for regular options*/
                     if (!elem.hasClass('onetouch')){
                        if (positionType == 'call') {
                            if (parseFloat(pricingRate) > parseFloat(strikeRate)){
                                payout.css('color','#006e00');
                                var thisSum = parseFloat((100 + profit) * amount)/100;
                                payout.html( AppData.accountCurrency + thisSum.toFixed(2) ).addClass('bold');
                                MyPositions.enableDisableButtons(elemId, 'disable');
                            }else if(parseFloat(pricingRate) < parseFloat(strikeRate)){
                                payout.css('color','#cc0000');
                                var thisSum = parseFloat((100-loss) * amount)/100;
                                payout.html( AppData.accountCurrency + thisSum.toFixed(2) ).removeClass('bold');
                                MyPositions.enableDisableButtons(elemId, 'enable');
                            }else{
                                payout.css('color','#333333');
                                payout.html(AppData.accountCurrency + amount).removeClass('bold');
                                MyPositions.enableDisableButtons(elemId, 'enable');
                            }
                        } else if (positionType == 'put')   { //Put
                            if (parseFloat(pricingRate) < parseFloat(strikeRate)){
                                payout.css('color','#006e00');
                                var thisSum = parseFloat(((100 + profit) * amount)/100 );
                                payout.html( AppData.accountCurrency + thisSum.toFixed(2) ).addClass('bold');
                                MyPositions.enableDisableButtons(elemId, 'disable');
                            }else if(parseFloat(pricingRate) > parseFloat(strikeRate)){
                                payout.css('color','#cc0000');
                                var thisSum = parseFloat((100 - loss) * amount)/100;
                                payout.html( thisSum.toFixed(2)).removeClass('bold');
                                MyPositions.enableDisableButtons(elemId, 'enable');
                            }else{
                                payout.css('color','#333333');
                                payout.html(AppData.accountCurrency + amount).removeClass('bold');
                                MyPositions.enableDisableButtons(elemId, 'enable');
                            }
                        }else
                            console.log('error: cannot define position direction');
                    }
				} //end of if has class
			 }); //end of foreach
    },

    noTradesMsg: function(action){
            if (action == 'hide')
             PlatformNav.container.find('#noTradingMessage').addClass('hidden');
            else
             PlatformNav.container.find('#noTradingMessage').removeClass('hidden');
        },
     graphDialog: function(html, title, optionId, options) {
               /* if(typeof title == 'undefined' || title == null )
                title == '';
*/
                //for findthis this dialog when option expires
                //var optionClass = 'dialogGraphOptionId'+optionId;
            var optionClass = '';
           var defaults = {
                autoOpen: true,
                resizable: false,
                width: 400,
                height: 200,
                modal: false,
                dialogClass: 'bbinary_dialog '+optionClass,
                title: title,
                stack: true,
                //buttons: {"Ok": function() {$(this).dialog("close");}} ,
                closeText: 'X', //TODO:this will need to be tanslatable,
                close: function(event, ui) {
                    //destroy graph
                    $(this).find('div').remove();
                    myDialog.dialog('destroy');
                }
            }

            if(typeof options != 'object' )
                options = {};

              options = $.extend({}, defaults, options);

              /* fix a bug that breaks JS when the lang string in AppData cannot be found */
              if (typeof(html) === 'undefined')
                  html = '';

              var myDialog = $('<div/>').html(html);
              myDialog.dialog(options);
              return myDialog;
       },
       /*
	 *
	 * Get last trades with AJAX and display it in last trades section in my trades
	 *
	 */
	lastTrades: function(event){
        //change the tabs
        var myPositionsTabs = $('div.myPositionsTabsEmpty',MyPositions.container);
        myPositionsTabs.addClass('myPositionsTabs_lastExpires');
        myPositionsTabs.removeClass('myPositionsTabs_myTrades');
        myPositionsTabs.removeClass('myPositionsTabs');
        myPositionsTabs.removeClass('myPositionsTabs_lastExpiresOneTouch');

        $('ul.positions li.open_position').hide();

		$('div.noPositionsMessage').hide();

		$(this).addClass('selected');
		$('#myTrades').removeClass('selected');
		$('#oneTouchPositions').removeClass('selected');

        $('ul.listTitle').hide();
        //show the title bar for last trades
        $('ul.listTitle_lastTrades').show();
        $('ul.listTitle_onetouch').hide();

        $.post('rpcProxy/getPositionsFiltered',
				{
				},
				function(trades){
					if (typeof(trades) != 'object')
						return;

					var tradesHTML = '';
                    var last = '';
					$.each(trades, function(index, element){
						if (typeof(element) != 'object'){
							return;
						}
                        if((trades.numberRecords)-1 == index){
                         last = ' open_position_last';
                        }
						tradesHTML += '<li id="close_position_' + element.id + '_' + element['assetId'] + '" class="close_position'+last+'">';
						tradesHTML +=	'<ul class="positionDetails">';
						tradesHTML +=	'	<li class="id">' + element.id + '</li>';
						tradesHTML +=	'	<li class="name" title="' + element.name + '">' + element.name + '</li>';
						tradesHTML +=	'	<li class="strikeRate">' + element.entryRate + '</li>';
						if(element.position != undefined) {
              if (element.position == 'call') {
                  tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrCall.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Call</b></li>';
              } else {
                tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrPut.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Put</b></li>';
              }
            } else {
              if (element.direction == 'above') {
                  tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrCall.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Above</b></li>';
              } else {
                tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrPut.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Under</b></li>';
              }
            }
						tradesHTML +=	'	<li class="date">' +  element.executionDate +'</li>';
						tradesHTML +=	'	<li class="endDate">' +  element.optionEndDate + '</li>';
						tradesHTML +=	'	<li class="expiryRate">' +  element.endRate + '</li>';
						tradesHTML +=	'	<li class="investment">' + AppData.accountCurrency + element.amount + '</li>';
						tradesHTML +=	'	<li class="status">' + element.status + '</li>';
						if (element.status == 'won')
							tradesHTML +=	'	<li class="payout payoutWin">' + AppData.accountCurrency + element.winSum + '</li>';
						else if (element.status == 'lost')
							tradesHTML +=	'	<li class="payout payoutLose">' + AppData.accountCurrency + element.loseSum + '</li>';
						else if (element.status == 'tie')
							tradesHTML +=	'	<li class="payout">' + AppData.accountCurrency + element.amount + '</li>';
						tradesHTML +=	'</ul>';
	
						tradesHTML +=	'</li>';
					});


					//hide the title bar for my trades
					$('ul.listTitle').hide();

					//hide the open position (my trades) and the graph if opened
					$('ul.positions li[id*="open_position_"]').hide().next().hide();


					//remove last trades if exists(we want it to be updated from ajax
					$('ul.positions li[id*="close_position_"]').remove();

                    //remove onetouch positions if displayed
                    $('ul.positions li[id*="onetouch_position_"]').remove();

					//append these trades to the open position
					$('ul.positions').append(tradesHTML).addClass('lastExpiryScroll');
                                        $('ul.positions').find('li.name').truncate(15);

				},
		'json');

	},
    
    /* display the *open* one touch positions of the current customers */
    oneTouchPositions: function(event){
        //change the tabs
        var myPositionsTabs = $('div.myPositionsTabsEmpty',MyPositions.container);
        myPositionsTabs.addClass('myPositionsTabs_lastExpiresOneTouch');
        myPositionsTabs.removeClass('myPositionsTabs_lastExpires');
        myPositionsTabs.removeClass('myPositionsTabs_myTrades');
        myPositionsTabs.removeClass('myPositionsTabs');

        $('ul.positions li.open_position').hide();

		$('div.noPositionsMessage').hide();

        /* add selected class to the selected tab */
		$(this).addClass('selected');
		$('#myTrades').removeClass('selected');
        $('#lastExpires').removeClass('selected');

        

        $('ul.listTitle').hide();
        $('ul.listTitle_lastTrades').hide();
        /* show title for onetouch */
        $('ul.listTitle_onetouch').show();

        $.post('rpcProxy/getOpenOneTouchPositions',
				{
				},
				function(trades){
					if (typeof(trades) != 'object')
						return;

					var tradesHTML = '';
                    var last = '';
					$.each(trades, function(index, element){
						if (typeof(element) != 'object'){
							return;
						}
                        if((trades.numberRecords)-1 == index){
                         last = ' open_position_last';
                        }
						tradesHTML += '<li id="onetouch_position_' + element.id + '_' + element.assetId + '" class="onetouch_position'+last+'">';
						tradesHTML +=	'<ul class="positionDetails">';
						tradesHTML +=	'	<li class="id">' + element.id + '</li>';
						tradesHTML +=	'	<li class="name" title="' + element.assetName + '">' + element.assetName + '</li>';
						tradesHTML +=	'	<li class="strikeRate">' + element.goalRate + '</li>';
						if(element.position != undefined) {
              if (element.position == 'call') {
                  tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrCall.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Call</b></li>';
              } else {
                tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrPut.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Put</b></li>';
              }
            } else {
              if (element.direction == 'above') {
                  tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrCall.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Above</b></li>';
              } else {
                tradesHTML +=	'	<li class="arrow direction"><img src="appProxy/site/home/optionArrPut.png" style="_overflow:hidden;_margin-top:11px;"/>&nbsp;<b>Under</b></li>';
              }
            }
						tradesHTML +=	'	<li class="date">' +  element.executionDate +'</li>';
						tradesHTML +=	'	<li class="endDate">' +  element.optionEndDate + '</li>';
						tradesHTML +=	'	<li class="expiryRate">' +  element.numberUnits + '</li>';
						tradesHTML +=	'	<li class="investment">' + AppData.accountCurrency + element.amount + '</li>';
						tradesHTML +=	'</ul>';

						tradesHTML +=	'</li>';
					});

					//remove last trades if exists(we want it to be updated from ajax
					$('ul.positions li[id*="onetouch_position_"]').remove();

                    //remove last trades if exists(we want it to be updated from ajax
					$('ul.positions li[id*="close_position_"]').remove();

					//append these trades to the open position
					$('ul.positions').append(tradesHTML);
                                        $('ul.positions').find('li.name').truncate(15);
                    $('ul.positions').removeClass('lastExpiryScroll');
				},
		'json');

	},
    myTrades: function(){
        //expired positions
        //change the tabs
        var myPositionsTabs = $('div.myPositionsTabsEmpty',MyPositions.container);
        myPositionsTabs.addClass('myPositionsTabs');
        myPositionsTabs.removeClass('myPositionsTabs_lastExpires');
        myPositionsTabs.removeClass('myPositionsTabs_myTrades');
        myPositionsTabs.removeClass('myPositionsTabs_lastExpiresOneTouch');

        			//click on my trades section
			$('ul.position li[id*="close_position"]').remove();

			//show the title bar for my trades
            $('ul.listTitle_lastTrades').hide();
			$('ul.listTitle').show();
            $('ul.listTitle_onetouch').hide();


			//show the open position (my trades)
            $('ul.positions li[id*="open_positiononetouch_"]').hide();
			$('ul.positions li[id*="open_position_"]').show();

			//if no open positions found
			if (!$('ul.positions li[id*="open_position_"]').length){
				Home.container.find('div.noPositionsMessage').show();
			}else{
				Home.container.find('div.noPositionsMessage').hide();
			}

			$('ul.positions').removeClass('lastExpiryScroll');

			//remove last trades if exists(we want it to be updated from ajax)
			$('ul.positions li[id*="close_position_"]').remove();

            //remove onetouch positions if displayed
            $('ul.positions li[id*="onetouch_position_"]').remove();

			$(this).addClass('selected');
			$('#lastExpires').removeClass('selected');
			$('#oneTouchPositions').removeClass('selected');

    },
    capitaliseFirstLetter:function(string){
        return string.charAt(0).toUpperCase() + string.slice(1);
}

}

$(document).ready(function() {
	MyPositions.init();
});


