var Home =  {
	container: null,
	currSelectedOptions: null,
	
	loadingAssets : {},
	
	init: function(){
		
	
		Home.container = $('div.container');
		Home.container.find('select[id*="type"]').selectbox(
				{
					inputClass: 'selectboxType',
					containerClass: 'selectbox-wrapperType',
					scrollBar: true,
					chainTitle: false,
					onChange: Home.changeAsset
				}
		)
		Home.container.find('select[id*="expireTime"]').selectbox(
				{
					inputClass: 'selectboxTime',
					containerClass: 'selectbox-wrapperTime',
					scrollBar: true,
					chainTitle: true,
					onChange: Home.changeExpireTime
				}
		)
		
		//insert selected options profits
		Home.container.find('ul.options li.regular').each(function(){
			$(this).find('strong.payout').text($(this).find('span.profitHidden').text() + '%');
		});
		
		t1 = setTimeout(function dateTimeReady(){
				if(General.dateTime){
					
					Home.getOptionsId('optionsList', false, null);
					t2 = setTimeout(function b(){
						if(Home.currSelectedOptions){
							Home.changeEndTimeDesign();//change the design of
													   //current option if nedded (red bell, and countdown)
							clearTimeout(t2);
						}
						else
							setTimeout(b, 500);
					}, 500);
					
					clearTimeout(t1);
				}
				else
					setTimeout(dateTimeReady, 500);
			}, 500);
			
			//events
			Home.container.find('ul.options li.regular input.showGraph').click(Home.showGraph);
			Home.container.find('ul.options li.regular input.graphBack').click(Home.hideGraph);
			Home.container.find('ul.options li.regular input.positionBack').click(Home.hidePositionBox);
			Home.container.find('div#suggestLine').bind('click', {}, Home.suggestAssetOpen);
			Home.container.find('input#closePromotion').click(Home.onClosePromotion)
	        
			//close suggestion
			if(AppData.isLoggedIn){
				General.container.find('input#closeSuggest').click(Home.onCloseSuggest);
			}

            Home.loadCurrentAssetRates();
           
		},

        /**
         * Gets specified asset rates from server.
         *
         * @param {array} assetIds[optional:[]] - if not set then loads all asset rates
         */
        loadCurrentAssetRates: function( assetIds ) {
			
            if (typeof assetIds === 'undefined') {
            	
            
                assetIds = [];
            }

            
            $.post(AppData.url + AppData.pageId + '/loadCurrentAssetRates', {'assetIds' : JSON.stringify(assetIds)},function(data) {
            	
            	$.each(data.rates, function(assetId, props){
            		Home.container.find('input[name="assetId"][value="' + assetId + '"]').each(function(){
            			var color = 'rgb(195,7,0)'; //red
            			if(parseInt(props.color))
           					var color = 'rgb(2,67,1)';//green
            			$(this).parent()
            				   .parent()
            				   .parent()
            				   .parent()//applyPosition li
            				   .find('input[name="rate"]').val(props.rate)
            				   .end()
            				   .prev()
            				   .find('div[id*="feed_asset"]').css('color', color).text(props.rate)
            		});
            	
            	
            																			 
            	});	

            }, 'json');
        },

		
		onCloseSuggest: function(event){
			var saggestElem = $(event.target).parent().parent();
			
			saggestElem.animate({
					height:'0px'
	      	}, 1500, function(){$(this).css('display', 'none')});
			
		},
		
		onClosePromotion: function(event){
			var promotionElem = $(event.target).parent();
			promotionElem.animate({
					height:'0px'
	      	}, 1500, function(){$(this).css('display', 'none')});
		},
		/**
		*	every change of time value (Lightstreamer)
		*	we call to 'onUpdateTime' function
		*
		**/
		onUpdateTime: function() {
			
			if(General.dateTime.getSeconds() == 0)
				Position.onMinuteEnd();
			Home.changeEndTimeDesign();
			
			
		},
		
	  /**
		*	Getting open and currently selected 
		*	options number
		*	@param listId -> id of ul element that contains the
		*					 list of open options
		
		*	@param seloptionId this param get the id of currently selected option
		*   otherwise selOptionId = false
		*
		*	update global array Home.currSelectedOptions
	   **/
		getOptionsId: function(listId, selOptionId, element){
			var openOptionsList = Home.container.find('ul.options');
			var idsArray = new Array();
			var inputElements = new Array();
			Home.currSelectedOptions = new Array();
			
			openOptionsList.children().find('div.expireTimeContainer').each(function(i){
				var expireContainer = $(this);
				var selectedLi = expireContainer.find('ul li.selected');
	            if ( !selectedLi.size() ) {
	                return;
	            }
				idsArray.push(parseInt(selectedLi.attr('id').split('_').slice(2,3)));
				inputElements.push(expireContainer.find('input[id*="expireTime"]'));
			});
			$.ajax({
						type: "POST",
						url: AppData.url + AppData.pageId + '/getOptionEndDate',
						data: {optionIds: JSON.stringify(idsArray)},
						async: true,
						dataType: 'json',
						error : function() {
							if (typeof console !== 'undefined') console.log('error');
						},
						success: function(optionProps){
							$.each(optionProps, function(i, option){
								var optionProp = {
									id: 				option.id, 
									endDate: 			option.endDate,
									noPositionTime: 	option.noPositionTime,
									lastPositionTime: 	option.lastPositionTime,
									profit:				option.profit,
									loss:				option.loss,
									assetId:			option.assetId,	
									inputElem:			inputElements[i]
								}
								var boxList = inputElements[i].parent().parent().parent().parent();
								Home.currSelectedOptions.push(optionProp);
								//Home.completeLoadingBoxList(boxList);
								if(selOptionId && option.id == selOptionId){
								//change the profit value
									boxList.find('strong.payout')
										.text(optionProp.profit + '%');
								};
							
								Position.onOptionChange(inputElements[i]);
							
							});
							// Allow loading of element again.
							if (element != null) {
								Home.loadingAssets[element.attr('id')] = false;
	                           
							}				
					   }
						
					});
		},
		
		changeAsset: function(assetName, assetId, element){
			
			
			//if mirror select was clicked
			var boxNumber = element.attr('id').replace(/\D/g,'');
			if(element.attr('id').indexOf('Mirror') !== -1){
				//simulate click on the real asset select
				
				var realLi = Home.container.find('div#type' + boxNumber + '_container' + ' ul li[id="type' + boxNumber + '_input_' + assetId + '"]');
				if(realLi.hasClass('selected')){
					return;
				}
				realLi.click();
				return;
			}
			else{
				//get mirror and simulate click
				Home.container.find('div#typeMirror' + boxNumber + '_container' + ' ul li[id="typeMirror' + boxNumber + '_input_' + assetId + '"]').click();
			}
			
			
			if (element.attr('id') in Home.loadingAssets && Home.loadingAssets[element.attr('id')] == true) {
				return;
			}
			
			Home.loadingAssets[element.attr('id')] = true;		
			var boxElem = element.parent()
	                             .parent()
	                             .parent();
	        Home.loadingBoxList(boxElem);
			$.post(AppData.url + AppData.pageId + '/getAssetOpenOptions',{assetId: assetId}, 
			function(objectRecieved){
				if(typeof objectRecieved!= 'object'){
					Home.refresh(); // if there is no open options for specific asset then refresh page
					
				}	
				optionsByDate = objectRecieved.options;
				
				var selectedOption = Home.loadOptions(element, optionsByDate);
	            if (selectedOption) {
	 				
	                boxElem.find('strong.payout').text(selectedOption.profit + '%');
	                boxElem.find('ul.actions input').each(function(){
	                    if($(this).attr('class').indexOf('call') != -1){
	                        $(this).attr('class', 'callLong')
	                        	   .unbind('click')
	                        	   .bind('click',{position: 'Call'}, Position.showCallPut); //on "Call" click
	                    }
	                    if($(this).attr('class').indexOf('put') != -1){
	                        $(this).attr('class', 'putLong')
	                        	   .unbind('click')
	                        	   .bind('click',{position: 'Put'}, Position.showCallPut); //on "Put" click
	                    }
	                });
	                   
	                //reset rate box
	                if(boxElem.find('li.currentPosition div.longDisabled').size())
	                    boxElem.find('li.currentPosition div.longDisabled').attr('class', 'long');
	                    
	                // change asset name
	                if(assetName)
						boxElem.next().next().find('div.assetName').text(assetName);
					else{//called when option expires
						boxElem.find('span#upDownAssetName').text(boxElem.find('div.positionTitle div.selectbox-wrapperType ul li.selected')
																		  .text());	
					}
																		  
	                //change graph for selected asset
	                boxElem.next().next().find('div.graphContainer').attr('id', 'graphContainer_' + assetId);
	                
	                Position.onAssetChange(element, assetId, boxElem.find('div.expireTimeContainer input.selectboxTime'));
					// Order of these two invocations change by Max due to optionId timing bug
					GraphsCompact.notifyAssetChange( boxElem.next().next().find('div.graphContainer'));

	                
	               Home.loadCurrentAssetRates([assetId]);
	                      
	            }
			}, 'json');	
		},
		
		changeExpireTime: function(name, optionId, element){
			//update list of selected options
			var boxSelected = element.parent()
									 .parent()
									 .parent();
			
			Home.loadingBoxList(boxSelected);			
			Home.getOptionsId('optionsList', optionId);
			//change css to default look
			element.css('background', 'url(appProxy/site/homeCompact/expireTimeSelectOrBox.gif) no-repeat');
			boxSelected.find('li.actionButton input').each(function(){
				if($(this).attr('class').indexOf('call') !== -1){
					$(this).attr('class', '').addClass('callLong')
											.attr('disabled', false)
											.unbind('click')
											.bind('click',{position: 'Call'}, Position.showCallPut); //on "Call" click;
				}
				else
					$(this).attr('class', '').addClass('putLong')
											 .attr('disabled', false)
											 .unbind('click')
											 .bind('click',{position: 'Put'}, Position.showCallPut); //on "Call" click;
			});
			boxSelected.find('li.currentPosition div').attr('class', '').addClass('long');
			Position.onOptionChange(element);
			Home.completeLoadingBoxList(boxSelected);
			GraphsCompact.notifyAssetChange( boxSelected.next().next().find('div.graphContainer'));
			
		},
		
		/*var optionsByDate  => 
	    /*Array
		(
		    [today] => Array
		        (
		            [0] => Array
		                (
		                    [id] => 606
		                    [assetId] => 2
		                    [startDate] => 2009-08-17 13:00:00
		                    [endDate] => 2009-08-17 13:30:00
		                    [expireTime] => 13:30
		                    [profit] => 68
		                    [loss] => 10
		                    [multiplier] => 1
		                )
		    [tommorow] => Array
		    	(
		    		 [0] => Array
		                (
		                    [id] => 606
		                    [assetId] => 2
		                    [startDate] => 2009-08-17 13:00:00
		                    [endDate] => 2009-08-17 13:30:00
		                    [expireTime] => 13:30
		                    [profit] => 68
		                    [loss] => 10
		                    [multiplier] => 1
		                )
		
		            [1] => Array
		                (
		                    [id] => 607
		                    [assetId] => 2
		                    [startDate] => 2009-08-17 13:30:00
		                    [endDate] => 2009-08-17 14:00:00
		                    [expireTime] => 14:00
		                    [profit] => 68
		                    [loss] => 10
		                    [multiplier] => 1
		                )
		    	
		    	)
		    [date] => Array
		    (
		    	[0] => Array
		                (
		                    [id] => 606
		                    [assetId] => 2
		                    [startDate] => 2009-08-17 13:00:00
		                    [endDate] => 2009-08-17 13:30:00
		                    [expireTime] => 13:30
		                    [profit] => 68
		                    [loss] => 10
		                    [multiplier] => 1
		                )
		    )
		    
		    return @param selected option	
	    **/	
		loadOptions: function(element ,optionsByDate){
			
			
			var optionsList = element.parent()
									 .parent()
									 .find('div.expireTimeContainer ul');
			
			var inputElem = element.parent()
								   .parent()
								   .find('div.expireTimeContainer input.selectboxTime');
			var tempLi = optionsList.children('li').not('.title').slice(0,1)
									.clone(true)
									.text('');
			
	        if (!tempLi.size()) {
	            return;
	        }
	      					
			var tempLiTitle = optionsList.children('li.title:first').slice(0,1)
									.clone(true)
									.text('')
									.attr({id: ''});
									
			var liIdPrefix = tempLi.attr('id').split('_');
			
			var boxSelected = element.parent().parent().parent();
			
	 		//reset the input field background
			inputElem.css('background', 'url(appProxy/site/homeCompact/expireTimeSelectOrBox.gif) no-repeat');
			
			tempLi.attr({id: '', className: ''});
			liIdPrefix = liIdPrefix[0] + '_'+ liIdPrefix[1] + '_'; 							   
			
			optionsList.children('li').remove();
			
			var selectedOption = null;
			var alreadySelected = false;
			var keepCheck = true;
			$.each(optionsByDate, function(date, options){
				
				if(typeof options == 'object'){
					optionsList.append(tempLiTitle.clone(true).attr({id:  liIdPrefix + date})
								  					 .addClass('title')
								 					 .text(date));
					
					$.each(options, function(key, option){
						var liElem = tempLi.clone(true).attr({id:  liIdPrefix + option.id})
								 						 .text(option.expireTime);
						
							if(/*key == 0*/!option.optionClose && !alreadySelected){
								inputElem.val(option.expireTime + ' ' + date);
								liElem.addClass('selected');
								alreadySelected = true;
								//set the selected option
								selectedOption = option;
							}
						optionsList.append(liElem);
						
					});
				}			  
			});
			//update list of selected options
			Home.currSelectedOptions = null;
			Home.getOptionsId('optionsList', false, element);
			
			
			return selectedOption;
		},
		
		changeEndTimeDesign: function(){
			
			$.each(Home.currSelectedOptions, function(i, selectedOption){
			
			var selectedLi  = selectedOption.inputElem
									  		.parent()
									  		.parent()
									 		.parent();
			   if (AppData.domain.indexOf('server') === -1) {
			   		var d = new Date();
					var endTime = new Date(selectedOption.endDate + d.getTimezoneOffset()*60*1000);			 			
				    deferenceTime = endTime.getTime() - General.dateTime.getTime();
	            } else 
	               deferenceTime = (selectedOption.endDate - General.dateTime.getTime());     
			
				if(deferenceTime < 1000){//option expired
					if(deferenceTime < -15000){
						
						var element  = selectedLi.find('div.positionContent input.selectboxType');
						
						if (element.attr('id') in Home.loadingAssets && Home.loadingAssets[element.attr('id')] == true) {
	                        return;
						}

						// Removes expired option.
	                    Home.currSelectedOptions.splice(i, 1);
						
						//delete option and reload open options 
						//to related asset
						selectedLi.find('ul.actions input').each(function(){
							if($(this).attr('class').indexOf('call') !== -1){
								$(this)
								.unbind('click')
								.bind('click',{position: 'Call'}, Position.showCallPut); //on "Call" click
							}
							else{
								$(this)
								.unbind('click')
								.bind('click',{position: 'Put'}, Position.showCallPut); //on "Put" click
							}
						});
	
						Home.changeAsset(false, selectedOption.assetId, element);
						Position.onOptionEnd(selectedOption.id); //remove the open positions display for this option
					}
					else{
						//0sec 0 min blinking effect
						if(selectedOption.inputElem.val() == '') selectedOption.inputElem.val('0 min 0 sec');
						else selectedOption.inputElem.val('');
						selectedLi.find('ul.actions input').each(function(){
							if($(this).attr('class').indexOf('Disabled') != -1){
								$(this).attr('disabled', false);
							}
						});
					}
				}
				else if(deferenceTime < selectedOption.lastPositionTime && deferenceTime > selectedOption.noPositionTime){//last time for make a position
					//calculate time left
					var d = new Date();
					var timeLeft = new Date(deferenceTime + d.getTimezoneOffset()*60*1000);
					//changeBackground
					selectedOption.inputElem.css({background: 'url(appProxy/site/homeCompact/expireTimeSelectRedBox.gif) no-repeat'});
					selectedOption.inputElem.val(timeLeft.getMinutes() + ' min ' + timeLeft.getSeconds() + ' sec');
					
					
				}
				else if(deferenceTime < selectedOption.noPositionTime){//no position can be made
					var timeLeft = new Date(deferenceTime);

					selectedLi.find('ul.actions input').each(function(){
					 	if($(this).attr('class').indexOf('Disabled') == -1){
					 		$(this).attr('class', $(this).attr('class') + 'Disabled')
								   .unbind('click')
								   .bind('click', {boxList: selectedLi}, Home.showOptionClosedPopup);
														   
					 	}
					 	else{
					 		selectedOption.inputElem.css({background: 'url(appProxy/site/homeCompact/expireTimeSelectRedBox.gif) no-repeat'});
					 	}
					});
					
					if(selectedLi.find('li.currentPosition div.long').size()){
						selectedLi.find('li.currentPosition div.long')
								  .attr('class', selectedLi.find('li.currentPosition div.long').attr('class') + 'Disabled');
					}
					
					selectedOption.inputElem.val(timeLeft.getMinutes() + ' min ' + timeLeft.getSeconds() + ' sec');	
					//close new position box
					
					/*if(selectedLi.find('div.putCallFolder').css('display') != 'none'){
						Position.hideCallPut(parseInt(selectedLi.next().find('form.positionForm').attr('id').replace(/\D/g,'')));
	
					}*/
						
				}	
			});	
			
		},
		
		loadHomePageMovie: function(){
		var flashvars = false;
		var params = {
			  wmode: "transparent",
			  loop: false
		}
	
	
	    if (!iOkun.readCookie('moviePlayed')) {
	        iOkun.createCookie('moviePlayed', '1', 60);
	        swfobject.embedSWF("appProxy/homepage.swf", "homePageMovie", "705", "330", "9.0.0", "expressInstall.swf", flashvars, params);
	    }
			
		},
		
		onFlashEnded: function(){
			var movieContainer = Home.container.find('div#movieContainer');
			movieContainer.animate({height:'0px'}, 2500, function(){
				$(this).remove()
			});
		},
		
		/**
		* if boxList = false , make all elements loading,
		* otherwise make the specific element loading
		**/
		
		loadingBoxList: function(boxList){
			
			/*if(boxList)	boxList.addClass('loading');
			else Home.container.find('ul#optionsList').children('li').addClass('loading');*/
			
		},
		
		completeLoadingBoxList: function(boxList){
			/*if(boxList)	boxList.removeClass('loading');
			else Home.container.find('ul#optionsList').children('li').removeClass('loading');*/
		},
		
		showOptionClosedPopup: function(event){
			var boxList = $(event.data.boxList).addClass('hidden');
			var popupContainer = boxList.next()
				   						.next()
				  						.next();
			popupContainer.find('input.popupClose')
						  .unbind('click')
						  .click(Home.closeOptionClosePopup);
			Position.showPopup(boxList.next(), AppData.langHome.optionIsClosedPopupTitle,  AppData.langHome.waitingForExpiryPopupMessage, '', false);
			
		},
		
		closeOptionClosePopup: function(event){
			var popupWindow = $(event.target).parent()
       										 .parent()
       										 .parent();
       		popupWindow.addClass('hidden')
       				   .find('div.popupMessageContainer, div#notLoggedIn, a#depositLink')
       				   	.addClass('hidden');
       		popupWindow.prev().prev().prev().removeClass('hidden');
       		popupWindow.find('input.popupClose').unbind('click').click(Position.closePopup)
		},
		
		suggestAssetOpen: function(event){
			var suggestAssetId = $(event.target).attr('assetid');
			var boxList = Home.container.find('ul#optionsList li.first');
			boxList.find('div#type1_container ul li').each(function(){
				var assetId = $(this).attr('id').split('_').slice(2, 3);
				if(assetId == suggestAssetId)
					$(this).click();
			});
			
		},
		
		showGraph: function(event){
			
			var boxList = $(event.target)
								 .parent()
								 .parent()
								 .parent();
			//hide main box
			//and show graph box
			boxList.addClass('hidden')
					.next()
					.next()
					.removeClass('hidden');
		},
		
		hideGraph: function(event){
			var graphBox = $(event.target)
								 .parent()
								 .parent();
			graphBox.addClass('hidden')
					.prev()
					.prev()
					.removeClass('hidden');					 
		},
		
		hidePositionBox: function(event){
			var positionBox = $(event.target).parent()
											 .parent()
											 .parent()
											 .parent();
			positionBox.addClass('hidden')
					   .prev()
					   .removeClass('hidden');
								
								
		},
		/**
		* Refresh Page
		*
		**/
		refresh: function(){
			location.reload(true);
			
		}
	
}

$(Home.init)
