var Position = {
	
	positionForms : null,
	
	lastPositions : null,
	
	todayOpenPositions : new Array(), //array of objects that contains position that closed today
	
	init : function() {
		//Events
		$('.callLong').bind('click',{position: 'Call'}, Position.showCallPut); //on "Call" click
		$('.putLong').bind('click',{position: 'Put'}, Position.showCallPut); //on "Put" click
		$('.closeCallPutFolder').bind('click',Position.hideCallPut); //on close
        // Click on a position, expands it and shows a graph
        $('div.leftSide div[class="open_positions today"] ul li.open_position').each(function(){
        	$(this).click( Position.onClickPosition )
        	if (AppData.domain.indexOf('server') === -1) {
				var d = new Date();
				var endDate = new Date(parseInt($(this).attr('enddate')) * 1000 + d.getTimezoneOffset()*60*1000);			 			
						   
			} else 
				var endDate = new Date(parseInt($(this).attr('enddate')) * 1000);
        	
        	Position.todayOpenPositions.push({
        										id: parseInt($(this).attr('id').split('_').slice(2,3)),
        										optionId: parseInt($(this).attr('optionid')),
        										endDate: endDate
        									});
        										
        });
            
            
		
		//Set the positionForms array
		Position.positionForms = new Array();
		Position.lastPositions = new Array();
		$('.positionForm').each(function(i) {
			var formId = i+1;
			Position.positionForms[formId] = $(this);
			Position.lastPositions[formId] = 'Call'; //default
			
			//When the amount changes on each form
			$(this).find('input[name="amount"]').bind('keyup',{id : formId}, Position.onAmountChange);
			$(this).find('input[name="amount"]').bind('click', function() {
				$(this).val('');
			});
			
			Position.validateForm(formId);
		});
		
		//events
		$('input.popupClose').bind('click', {}, Position.closePopup);
		
			//login fields
		General.container.find('div.popup input[name="email"]').focus(General.onFocusEmail).blur(General.onBlurEmail);
		General.container.find('div.popup input[name="passwordFake"]').bind('focus', {container: 'div.popup '}, General.onFocusPassword);
		General.container.find('div.popup  input[name="password"]').bind('blur', {container: 'div.popup '}, General.onBlurPassword);
		
	},
	
	/**
		Show the Call/Put form
	**/
	showCallPut : function(e) {
		var newPosition = e.data.position; //set the new position (call or put)
		
		var formId = Position.getElementFormId($(this), newPosition + '_position_');
		

		if (newPosition == 'Call')
			$(this).attr('class', '').addClass('callLongSelected');//css('background-image', "url(appProxy/site/home/selectedOption/callBtn.png)");
		else
			$(this).attr('class', '').addClass('putLongSelected');//css('background-image', "url(appProxy/site/home/selectedOption/putBtn.png)");
		
		if (Position.lastPositions[formId] != newPosition) { //position has changed!
			Position.switchCallPut(formId, newPosition); //switch the form (from call to put of vise versa)
		}
		
		Position.positionForms[formId].parent().show('slow');
		
		Position.lastPositions[formId] = newPosition; //update the lastPositions property

		//do tracking only if user has logged in
		if (AppData.isLoggedIn){
			//get assetId from the clicked button
			var assetId = $(this).parent().parent().parent().parent().parent().find('div.positionTitle').find('select[id*="type"] option:selected').val();
			var optionId = Position.positionForms[formId].find('input[name="optionId"]').val();

			$.post(AppData.url + AppData.pageId + '/selectedPositionTrack',
			{assetId:assetId,direction:e.data.position,optionId:optionId},
			{},
			'json');
		}
	},
	
	/** 
		Switch the form (from Call to Put and vise versa)
	**/
	switchCallPut : function(formId, newPosition) {
		
		Position.positionForms[formId].find('input.closeCallPutFolder').removeClass('closeFolder' + Position.lastPositions[formId]); //Close folder button (X)
		Position.positionForms[formId].find('input.closeCallPutFolder', Position.positionForm).addClass('closeFolder' + newPosition); 
		
		Position.positionForms[formId].find('img.arrow').attr('src', 'appProxy/site/home/optionArr' + newPosition + '.jpg'); //arrow direction (up or down)
		
		//switch lower and higher rate text (Above Rate and Below Rate)
		if (newPosition == 'Call') { 
			Position.positionForms[formId].find('td.rateDirection').text(AppData.langHome.aboveRate);
			Position.positionForms[formId].find('span.otherRateDirection').text(AppData.langHome.belowRate); 
			//change the call btn (to "clicked")
			$('#Call_position_' + formId).attr('class', '').addClass('callLongSelected');//css('background-image', "url(appProxy/site/home/selectedOption/callBtn.png)");
			//change the put btn (to unclicked)
			$('#Put_position_' + formId).attr('class', '').addClass('putLong');//css('background-image', "url(appProxy/site/home/longTermOption/putBtn.png)");
		} else {
			Position.positionForms[formId].find('td.rateDirection').text(AppData.langHome.belowRate);
			Position.positionForms[formId].find('span.otherRateDirection').text(AppData.langHome.aboveRate);
			//change the call btn (to unclicked)
			$('#Call_position_' + formId).attr('class', '').addClass('callLong');//css('background-image', "url(appProxy/site/home/longTermOption/callBtn.png)");
			//change the put btn (to clicked)
			$('#Put_position_' + formId).attr('class', '').addClass('putLongSelected');//css('background-image', "url(appProxy/site/home/selectedOption/putBtn.png)");
		}
		
		Position.positionForms[formId].find('input[name="position"]').val(newPosition); //'position' hidden input
		
		Position.positionForms[formId].find('input.positionBtn').removeClass('positionBtn' + Position.lastPositions[formId]); //"Apply" submit button
		Position.positionForms[formId].find('input.positionBtn').addClass('positionBtn' + newPosition);
		
		Position.onAmountChange(formId);
	},
	
	/**
		Close the form
	**/
	hideCallPut : function(formId) {
		
		if (typeof formId == 'object')
			var formId = Position.getElementFormId($(this), 'close_position_');
			
		Position.positionForms[formId].parent().hide('slow');

		Position.positionForms[formId].find('input[name="amount"]').val(0); //reset the amount
		
		//Change the call/put buttons to unclicked

		$('#Call_position_' + formId).attr('class', '').addClass('callLong');//css('background-image', "url(appProxy/site/home/longTermOption/callBtn.png)");
		$('#Put_position_' + formId).attr('class', '').addClass('putLong');//css('background-image', "url(appProxy/site/home/longTermOption/putBtn.png)");

	},
	
	//Called from home.js on asset change
	onAssetChange : function(element, assetId, optionElement) {
		
		var formId = Position.getElementFormId(element, 'type');
		
		
		Position.positionForms[formId].find('input[name="rate"]').removeClass(); //remove the old class
		
		Position.positionForms[formId].find('input[name="rate"]').addClass("rate assetId_" + assetId); //update the asset for the current form
		Position.positionForms[formId].find('input[name="assetId"]').val(assetId);
		Position.onOptionChange(optionElement);
	},
	
	//called from home.js on option change
	onOptionChange : function(element) {
		
		var formId = Position.getElementFormId(element, 'expireTime');
		
		//Wait for currSelectedOptions to be ready, then update the position form.
		var runtime = 0;
		var optcheck = setInterval(function checkOptions() {
			runtime += 100; //update runtime (in ms)
			//console.log('checking');
			if (Home.currSelectedOptions.length >=2) {
			
				//console.log('ready');
				//console.log(Home.currSelectedOptions);
				//Itterate through all the currently selected options, to find the wanted option, which is the one that was clicked
				//var optionParams = new Array();
				$.each(Home.currSelectedOptions, function(i, optionParams) { 
					
					if (Position.getElementFormId(optionParams.inputElem, 'expireTime') == formId) {//found! 
						
						Position.positionForms[formId].find('input[name="optionId"]').val(optionParams.id);
						Position.positionForms[formId].find('input[name="profit"]').val(optionParams.profit);
						Position.positionForms[formId].find('input[name="loss"]').val(optionParams.loss);
						
						var endTime = optionParams.endDate;
						if (AppData.domain.indexOf('server') === -1) {
					   		var d = new Date();
							endTime = new Date(endTime + d.getTimezoneOffset()*60*1000);			 			
						   
			            } else 
			              endTime = new Date(endTime);
						Position.positionForms[formId].find('td.date').html(date('m.d.y', endTime) + ' <strong>' + date('H:i', endTime) + '</strong>');
					}
				});
				
				Position.onAmountChange(formId);
				clearInterval(optcheck);
			} else {
				if (runtime > 10000) {//more than 10 seconds, stop
					//console.log('Unable to update option!');
					Position.hideCallPut(formId);
					clearInterval(optcheck);
				}
			}
			
		},100);
	},

	onOptionEnd : function (optionId) {
		//Get option open positions for this option, and remove them from display as they already ended.
		$('.optionPosition' + optionId).each(function(i) {
			if($(this).next().size() && $(this).next().attr('id').indexOf('openPositionGraphContainer') != -1)
				$(this).next().remove();//remove graph container
				
		});
		
		//console.log($('.optionPosition' + optionId).size());
		//console.log(optionId)
		$('.optionPosition' + optionId).remove();//remove all positions
	},
	
	/**
		When the amount is changed, this function is called to re-calculate the profits and loses. 
	**/
	onAmountChange : function(formId) {
		
		if (typeof formId == 'object')
			var formId = formId.data.id;
		
		var amount = parseInt(Position.positionForms[formId].find('input[name="amount"]').val());
		var profit = parseInt(Position.positionForms[formId].find('input[name="profit"]').val());
		var loss = parseInt(Position.positionForms[formId].find('input[name="loss"]').val());
		
		var position = Position.positionForms[formId].find('input[name="position"]').val();
		
		var profitElement = Position.positionForms[formId].find('td.profitSum span');
		var lossElement = Position.positionForms[formId].find('span.otherProfitSum');

		
		
		if (amount > 0) {
			if (position == 'Call') {
				var payoutAbove = ((100 + profit) * amount)/100;
				var payoutBelow = ((100-loss) * amount)/100;
			} else { //Put
				var payoutBelow = ((100 - loss) * amount)/100; //This should be above 
				var payoutAbove = ((100 + profit) * amount)/100; //This should be Below
			}
		} else { //no valid amount
			var payoutAbove = '0'; //reset both fields to zero
			var payoutBelow = '0';
		}
		
		profitElement.html(payoutAbove);
		lossElement.html(payoutBelow);


	},
	
	//called from graphs.js when a rate updates
	onRateChange : function(container, rate) {
		container.val(rate);
	},


	//called from validateForm function when the apply button is pressed
	setPositionClick: function(type,formParams){
		var params = new Array();
		$.each(formParams, function(i, obj) {
			params[obj.name] = obj.value;
		});

			$.post(AppData.url + AppData.pageId + '/selectedPositionTrack',
			{assetId:params['assetId'],direction:type},
			{},
			'json');
		},



	validateForm : function(formId) {
		var boxList = $('form#positionForm_' + formId).parent().parent().parent();
	
		
		Position.positionForms[formId].validate({
			rules: {
				amount: {
					required: true,
					number: true,
					min:25,
					max:1000
				}
			},
			messages: {
				amount: {
					required: 'required',
					min: 'min',
					max: 'max',
					number: 'number'
				}
			},
			onfocusout: false,
			onkeyup: false,
			errorPlacement: function(error, element) {
				var errorType = error.text();
				switch(errorType){
					case 'required':Position.showPopup(boxList, AppData.langHome.requiredErrorPopupTitle,  AppData.langHome.requiredErrorPopupMessage, '', false);
									break
					case 'min':		Position.showPopup(boxList, AppData.langHome.minErrorPopupTitle,  AppData.langHome.minErrorPopupMessage, AppData.accountCurrency + '25', false);
									break;
					case 'max':     Position.showPopup(boxList, AppData.langHome.maxErrorPopupTitle,  AppData.langHome.maxErrorPopupMessage, AppData.accountCurrency + '1000', false);
									break;
					case 'number':  Position.showPopup(boxList, AppData.langHome.numberErrorPopupTitle,  AppData.langHome.numberErrorPopupMessage, '', false);
									break;
				}
				
			},
			submitHandler: function() { //submit the form when everything is valid
				var formParams = Position.positionForms[formId].serializeArray();
				$.ajax({
					type: "POST",
					url: 'rpcProxy/newPosition',
					data: formParams,
					async: false,
					dataType: 'json',
					error : function() {
						alert('Unknown Error');
					},
					success: function(result){
							/*** This code propuse to fix the bug
								when position made on asset that deffers from
								asset that listed in 'select'
							**/ 
							var assetInFormId  = boxList.find('input[name="assetId"]').val();
							var assetInSelectId = boxList.find('div.selectbox-wrapperType ul li.selected').attr('id').split('_')[2];
							
							if(assetInSelectId != assetInFormId){
								Position.showPopup(boxList, AppData.langHome.errorOccuredPoupTitle,  AppData.langHome.errorOccuredPoupMessage, '', false);
								setTimeout(function(){
									boxList.find('div.selectbox-wrapperType ul li').each(function(){
										if($(this).attr('id').split('_')[2] == assetInFormId){
											$(this).click();
										}
									});
								}, 3000);
								return;
							}
							
							/*** end of bug fix ***/
						if (typeof result == 'object') {
							Position.hideCallPut(formId);
							Position.addPosition(formParams, result);
							//save the position tracking
							Position.setPositionClick("apply",formParams);

						} else { //Error! -> user not logged in
							switch(result){
								case 'notLoggedIn':
									
									boxList.find('div.popup')
																   		.removeClass('hidden')
																   		.find('div.popupTitle span')
																   			.text(AppData.langHome.loginPopupTitle)
																   .end()
																   .end()
																   .find('div#notLoggedIn')
																   		.removeClass('hidden');
												  			break;
								case 'optionIsClosed':
									Position.showPopup(boxList, AppData.langHome.optionIsClosedErrorPopupTitle,  AppData.langHome.optionIsClosedErrorPopupMessage, '', false);
															break;
								case 'insufficientFunds':
									Position.showPopup(boxList, AppData.langHome.insufficientFundsErrorPopupTitle,  AppData.langHome.insufficientFundsIsErrorPopupMessage, '', true);
															break;
								case 'invalidPositionRate':
										Position.showPopup(boxList, AppData.langHome.invalidPositionRate,  AppData.langHome.positionRateIsInvalid, '', false);
										break;
								case 'suspended':
									  Position.showPopup(boxList, AppData.langHome.optionSuspendedPopupTitle,  AppData.langHome.optionSuspendedPopupMessage, '', false);
									  break;
								case 'riskSuspentionActivated':
									   Position.showPopup(boxList, AppData.langHome.riskSuspentionPopupTitle,  AppData.langHome.riskSuspentionPopupMessage, '', false);
									  break;
							}
						}
						
						boxList.find('input[name="amount"]').val(0)
								.end()
								.find('td.profitSum span').text('0')
								.end()
								.find('span.otherProfitSum').text('0'); //reset the amount
				   }

				});
				
				
			}
		});
	},
	
	addPosition : function(formParams, positionProps) {
		var positionId = positionProps.positionId;
		var positionRate = positionProps.positionRate;
		//console.log(positionId);
		//console.log(positionRate)
		var params = new Array();
		$.each(formParams, function(i, obj) {
			params[obj.name] = obj.value;
		});
		
		//Update balance
		var currentBalance = parseInt($('#currentBalance').text());
		var amount = params.amount;
		$('#currentBalance').text(currentBalance - amount);
		

		$.getJSON('rpcProxy/getOptionInfo/' + params.optionId, function(optionProp){
				if (AppData.domain.indexOf('server') === -1) {
		   			var d = new Date();
					var optionEndDate = new Date(parseInt(optionProp['endDate']) + d.getTimezoneOffset()*60*1000);
				} else {
               		var optionEndDate = new Date(parseInt(optionProp['endDate']));     
            	}
            	var optionEndHour = optionEndDate.getHours();
            	var optionEndMinute = optionEndDate.getMinutes();
            	if(optionEndHour < 10 ) optionEndHour = '0' + optionEndHour;
            	if(optionEndMinute < 10) optionEndMinute = '0' + optionEndMinute;
				
            	if (optionEndDate.getDate() == General.dateTime.getDate() && optionEndDate.getMonth() == General.dateTime.getMonth()) { //only add poisitions which end today
					
					
					positionTodayHTML = '<li id="open_position_' + positionId + '_' + optionProp['assetId'] + '" class="open_position optionPosition'+ optionProp['id'] + '">';
					positionTodayHTML +=	'<ul>';
					positionTodayHTML +=	'<li class="name" title="' + optionProp['assetName'] + '">' + optionProp['assetName'] + '</li>';
					positionTodayHTML +=	'<li class="time">' + optionEndHour + ':' + optionEndMinute + '</li>';
					positionTodayHTML +=	'<li class="investment">' + AppData.accountCurrency + params.amount + '</li>';
					positionTodayHTML +=	'<li class="arrow"><img src="appProxy/site/home/optionArr' + params.position + '.png" style="_overflow:hidden;_margin-top:11px;"/></li>';
					positionTodayHTML +=	'<li class="asset">' + positionRate + '</li>';
					positionTodayHTML +=	'</ul>';
					positionTodayHTML +=	'<div class="positionGraph">';
					positionTodayHTML +=	'</div>';
					positionTodayHTML +=	'</li>';

					$('ul.positions').append(positionTodayHTML).find('li.name').truncate(10);
					$('ul.positions')
						.find( '#open_position_' + positionId + '_' + optionProp['assetId'])
						.click( Position.onClickPosition );

					///$('ul.positions').show(); this is not working
					$('div.today').removeClass('hidden');
					
					Position.todayOpenPositions.push({
														id: parseInt(positionId),
														optionId: parseInt(params.optionId), 
														endDate: optionEndDate
													});
				}
				else{
					positionFutureHTML = '<li id="open_position_' + positionId + '_' + optionProp['assetId'] + '" class="open_position optionPosition"'+ optionProp['id'] + '">';
					positionFutureHTML +=	'<ul>';
					positionFutureHTML +=	'<li class="name">' + optionProp['assetName'] + '</li>';
					positionFutureHTML +=	'<li class="time">' + date('H:i', parseInt(optionProp['endDate'] ))+ '</li>';
					positionFutureHTML +=	'<li class="investment">' + AppData.accountCurrency + params.amount + '</li>';
					positionFutureHTML +=	'<li class="arrow"><img src="appProxy/site/home/optionArr' + params.position + '.png" style="_overflow:hidden;_margin-top:11px;"/></li>';
					positionFutureHTML +=	'<li class="asset">' + positionRate + '</li>';
					positionFutureHTML +=	'</ul>';
					positionFutureHTML +=	'<div class="positionGraph">';
					positionFutureHTML +=	'</div>';
					positionFutureHTML +=	'</li>';
					
					$('ul.futurePositions').append(positionFutureHTML);
				
					///$('ul.positions').show(); this is not working
					$('div.future').removeClass('hidden');
				}
			});			

	},
	
	/**
		Get the element form identification digit (1-4 nornally) by removing the prefix
	**/
	getElementFormId : function(element, prefix) {
		return element.attr('id').substr(prefix.length, 1);
	},


    /**
     * 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>
     */
    onClickPosition: function() {
        var parts = this.id.split('_');
        var positionId = parts[2];
        var assetId    = parts[3];
        var optionId = $(this).attr('class').match(/\d+$/);
        

        var containerId = 'openPositionGraphContainer_' + positionId;
        

        if ( 0 === $(this).next('#' + containerId).size() ) {

            $('<div/>').attr('id', containerId)
                       .insertAfter(this)
                       .append( $('<div/>')
                                .attr('id', containerId + '_')
                        )
                       /*.append( $('<input type="button" />')
                                .click(Position.onClickFlip)
                                .addClass('flipPositionButton')
                        )*/
                       .hide();

            Graphs.graphs[containerId + '_'] = {
                currRate: null,
               	itemName: 'asset_' + assetId + '_' + optionId,
                lastXID: null,
                flash: null // This will point to the flash movie, set by amChartInited()
            };
            
            swfobject.embedSWF(
                "sysProxy/amline/amline.swf", containerId + '_',
                "250", "139", "9.0.0", "sysProxy/expressInstall.swf",
                { path: 'sysProxy/amline/',

                  data_file: encodeURIComponent(AppData.url + 'home/getOpenPositionGraphXML/' +  positionId),
                  chart_id: containerId + '_',
                  settings_file : encodeURIComponent( AppData.url +
                                   'home/getOpenPositionGraphSettingsXML/' +
                                   positionId +  '/?' + new Date().getTime() )
                },
                {wmode:'opaque'},
                {'class': 'openPositionChart'});

               

            } // end if ( 0 === ... )

            $('#' + 'openPositionGraphContainer_' + positionId).toggle();
            $(this).toggleClass('selected');

       },

       /**
        * Click on the flip button event
        */
       onClickFlip: function( event ) {
           alert('Not Implemented Yet.')
       },
       
       /**
       * Close pop up window
       */
       closePopup: function(event){
       		var popupWindow = $(event.target).parent()
       										 .parent();
       		popupWindow.addClass('hidden')
       				   .find('div.popupMessageContainer, div#notLoggedIn, a#depositLink')
       				   	.addClass('hidden');
       },
       
       showPopup: function(boxList, popupTitle, popupFirstLine, popupSecondLine, showDeposit){
       		
       		if(showDeposit) boxList.find('div.popup a#depositLink').removeClass('hidden');
       		boxList.find('div.popup').find('div.popupTitle span')
       								 .text(popupTitle)
       								 .end()
       								 .find('span.popupWarning').text(popupFirstLine)
       								 .end()
       								 .find('span.popupSum span').text(popupSecondLine)
       								 .end()
       								 .removeClass('hidden')
       								 .find('div.popupMessageContainer')
       								 	.removeClass('hidden');
       							
       	
       },
       
       onMinuteEnd: function(){
       //	console.log(Position.todayOpenPositions)
		$.each(Position.todayOpenPositions, function(i, todayPosition){
			//console.log(todayPosition.optionId + ' option id')
			if(todayPosition.endDate.getTime() < General.dateTime.getTime()){
				Position.onOptionEnd(todayPosition.optionId)
				delete 	Position.todayOpenPositions[i];
			}
				
		});
       },
	  
       
       
       testFunction: function(){
       		$('ul#optionsList').children('li').each(function(i){
       			var selectAssetId = $(this).find('div.selectbox-wrapperType ul li.selected').attr('id').split('_').slice(2,3);
       			var formAssetId = $(this).find('form.positionForm input[name="assetId"]').val();
       			var selectOptionId = $(this).find('div.expireTimeContainer ul li.selected').attr('id').split('_').slice(2,3);
       			var formOptionId = $(this).find('form.positionForm input[name="optionId"]').val();
       			//console.log('box number ' + i + ' assetId in select =' + selectAssetId + ', in form assetId = ' + formAssetId);
       			//console.log('box number ' + i + ' optionId in select =' + selectOptionId + ', in form optionId = ' + formOptionId);
       		});
       }
       
	
}

$(document).ready(function(){
	Position.init();
});