var Home =  {
	container: null,
	currSelectedOptions: null,
	counter: 0,
	loadingAssets : {},
	
	init: function(){
		
		Home.container = $('div.container');
		Home.container.find('select#type1, select#type2, select#type3, select#type4').selectbox(
				{
					inputClass: 'selectboxType',
					containerClass: 'selectbox-wrapperType',
					scrollBar: true,
					chainTitle: false,
					onChange: Home.changeAsset
				}
		)
		Home.container.find('select#expireTime1, select#expireTime2, select#expireTime3, select#expireTime4').selectbox(
				{
					inputClass: 'selectboxTime',
					containerClass: 'selectbox-wrapperTime',
					scrollBar: true,
					chainTitle: true,
					onChange: Home.changeExpireTime
				}
		)
		
		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)
						var currAssets = new Array();
						Home.container.find('input[name="assetId"]').each(function(){
							currAssets.push($(this).val())
						});
												   
						Home.loadCurrentAssetRates(currAssets);
						clearTimeout(t2);
					}
					else
						setTimeout(b, 500);
				}, 500);
				
				clearTimeout(t1);
			}
			else
				setTimeout(dateTimeReady, 500);
		}, 500);
		
		//events
		Home.container.find('ul.mainNav').children('li:not(.selected)').bind('click', {}, Home.changeTab);
		Home.container.find('div#suggestLine').bind('click', {}, Home.suggestAssetOpen)
		//Home.container.find('input.callLong, input.putLong').tooltip({ fixPNG: true, left:30, top:-20});
		Home.container.find('input#closePromotion, input#closePromotionOneTouch').click(Home.onClosePromotion)
        
		//close suggestion
		if(AppData.isLoggedIn){
			General.container.find('input#closeSuggest').click(Home.onCloseSuggest);
		}
		//Home.container.find('marquee').marquee();
		
		//Home.loadHomePageMovie();
    /*.selectbox(
       3.       {  
       4.         inputClass: 'selectbox', //css class for the input which will replace the select tag, display the background image  
       5.         containerClass: 'selectbox-wrapper', // The list container class (a div element)  
       6.         hoverClass: 'current', // css class for the current element  
       7.         currentClass: 'selected', // css class for the selected element  
       8.         debug: false // debug mode on/off  
       9.       }  
      10.     );  
      11. });  */
    	
    	OneTouch.init();
	},
	
	/**
     * 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(i){
	            var color = 'rgb(195,7,0)'; //red
	            if(parseInt(props.color))
	           		var color = 'rgb(2,67,1)';//green
	            $(this).parent()
	            	   .parent()
	            	   .parent()
	            	   .parent()//box list
	            	   .find('input[name="rate"]').val(props.rate)
	            	   .end()
	            	   .find('div[id*="feed_asset_"]').css('color', color).text(props.rate)
	        	});
            	
            	
            																			 
        	});	

    	}, 'json');
  	},
	
	changeTab: function(event){
		Home.loadingBoxList();
		if($(event.target).get(0).tagName == 'LI') var liObj = $(event.target);
		else var liObj = $(event.target).parent();
		
		var ulObj = liObj.parent();
		
		var liPrevSelected = ulObj.children('li.selected')
		var tabContent = liPrevSelected.text();
		var currClassName = liPrevSelected.removeClass('selected').attr('class');
		//find asset type
		var currAssetType = liObj.attr('assettype');
		
		var optionsList = Home.container.find('ul#optionsList');
		//liPrevSelected.prevAll('li div').css('width', '107px')
	
		
		//fix for ie 6
		liPrevSelected.replaceWith($.create('li').bind('click', {}, Home.changeTab)
												 .addClass(currClassName)
												 .attr('assettype', liPrevSelected.attr('assettype'))
												 .append($.create('div').text(tabContent)));
		//correct tab width , this makes the text in the middle										 
		liObj.prevAll('li').each(function(){
			$(this).children('div').css('width', '109px');
		});
		liObj.nextAll('li').each(function(){
			$(this).children('div').css('width', '');
		});
		
		liObj.addClass('selected').unbind('click');
		if(jQuery.browser.msie && jQuery.browser.version == '6.0')
			liObj.parent().pngFix();
			
		if(currAssetType != 'oneTouch'){	
			$('div#oneTouchCommingSoon').addClass('hidden');
			$('ul#oneTouchList').addClass('hidden');
			Home.container.find('div[class*="oneTouchPromo"]').addClass('hidden');
			Home.container.find('div.promotion').show();
			
			$.post(AppData.url + AppData.pageId + '/onChangeTab', {assetType: currAssetType}, function(openOptions){
				var boxList = Home.container.find('ul#optionsList');
				
				if(openOptions.length){
					Home.container.find('div#noTradingMessage').addClass('hidden');//hide no tradeable options availible message 
					
					$.each(openOptions, function(i, openOption){
						var selectedLi = boxList.children('li:nth-child(' + (i+1) + ')');
						selectedLi.find('div.positionContent div.selectbox-wrapperType ul li').each(function(){
							if($(this).attr('id').split('_').slice(2,3) == openOption.assetId){	
								$(this).click();
								//show the box if hidden
								selectedLi.removeClass('hidden');
							}
						});
					});
				}
				else{//there is no open options in this tab, show message
					Home.container.find('div#noTradingMessage').removeClass('hidden');
					
				}
				
				//hide extra boxes
				boxList.children('li:gt(' + (openOptions.length-1) + ')').addClass('hidden');
				Home.loadCurrentAssetRates();
				
			}, 'json');
		}
		else{//show 'one touch' comming soon message
			Home.container.find('div#noTradingMessage').addClass('hidden');//hide no tradeable options availible message 
				liObj.children('div').addClass('selected')
				optionsList.children('li')
						   .addClass('hidden');
						   
			//show promo
			Home.container.find('div[class*="oneTouchPromo"]').removeClass('hidden');
			Home.container.find('div.promotion').hide();
			//if(AppData.isLocal){
				OneTouch.onTabClick();
				
			//}
			/*else{
				$('div#oneTouchCommingSoon').removeClass('hidden');
			}*/
				
		}
	},
	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).children().remove()});
	},
	/**
	*	every change of time value (Lightstreamer)
	*	we call to 'onUpdateTime' function
	*
	**/
	onUpdateTime: function() {
		
		if(General.dateTime.getSeconds() == 0)
			Position.onMinuteEnd();
		Home.changeEndTimeDesign();
		OneTouch.updateClock();
		
	},
	
	
	
  /**
	*	Getting open and currently selected 
	*	options number
	*	@param listId -> id of ul element that contains the
	*					 list of open options
	
	*	@param optionId 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('#' + listId);
		Home.currSelectedOptions = new Array();
		var idsArray = new Array();
		var inputElements = new Array();
		Home.counter++;
		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 (element.attr('id') in Home.loadingAssets && Home.loadingAssets[element.attr('id')] == true) {
			
			
			return;
		}
		
		
		
		Home.loadingAssets[element.attr('id')] = true;		
		
		var mainTab = Home.container.find('ul.mainNav');
		var assetTabType = mainTab.children('li.selected').attr('assettype');
		if(assetTabType == 'false') assetTabType = false
		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;
			popularity = objectRecieved.popularity;
			
			popularityDiv = boxElem.find('div.populGraphContainer');
			popularityDiv.find('div.green strong').text(popularity + '%');
			popularityDiv.find('div.orange strong').text((100-popularity) + '%');
			popularityDiv.find('div.green').css('height',Math.round(popularity/100*131,0));	
			popularityDiv.find('div.orange').css('height',Math.round((100-popularity)/100*131,0));	
			
			var selectedOption = Home.loadOptions(element, optionsByDate, assetTabType);
            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.find('span#upDownAssetName').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.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
				Graphs.notifyAssetChange( boxElem.find('div.graphContainer'));
                
               	Home.loadCurrentAssetRates([assetId]);
               // Position.onOptionChange(boxElem.find('div.expireTimeContainer input.selectboxTime'), selectedOption.id);
               
            }
		}, 'json');
		
		//Position.onOptionChange(element, optionId)		
	},
	
	changeExpireTime: function(name, optionId, element){
		//update list of selected options
		var boxSelected = element.parent()
								 .parent()
								 .parent()
								 .parent();	
		Home.loadingBoxList(boxSelected);			
		Home.getOptionsId('optionsList', optionId);
		//change css to default look
		element.css('background', 'url(appProxy/site/home/timeSelect/selectboxOrBell.jpg) 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');
		
		boxSelected.find('span.expMessage').text(AppData.langHome.optionExpiresAt);
		Position.onOptionChange(element);
		Home.completeLoadingBoxList(boxSelected);
		Graphs.notifyAssetChange( boxSelected.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, assetTabType){
		
		
		var optionsList = element.parent()
								 .find('div.expireTimeContainer ul');
		var inputElem = element.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();
 		//reset the input field background
		inputElem.css('background', 'url(appProxy/site/home/timeSelect/selectboxOrBell.jpg) no-repeat');
		boxSelected.find('span.expMessage').text(AppData.langHome.optionExpiresAt);
		
		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(assetTabType && keepCheck){
						if(option.assetType != assetTabType){//back to your choice tab
						
							keepCheck = false;
							var liObj = Home.container.find('ul.mainNav li.first');
							var ulObj = liObj.parent();
							
							var liPrevSelected = ulObj.children('li.selected')
							var tabContent = liPrevSelected.text();
							var currClassName = liPrevSelected.removeClass('selected').attr('class');
							
							//fix for ie 6
							liPrevSelected.replaceWith($.create('li').bind('click', {}, Home.changeTab)
												 .addClass(currClassName)
												 .attr('assettype', liPrevSelected.attr('assettype'))
												 .append($.create('div').text(tabContent)));
																	 
							liObj.addClass('selected').unbind('click');
							if(jQuery.browser.msie && jQuery.browser.version == '6.0')
								liObj.parent().pngFix();
							//correct tab width , this makes the text in the middle
							liObj.prevAll('li').each(function(){
									$(this).children('div').css('width', '109px');
								});
							liObj.nextAll('li').each(function(){
								$(this).children('div').css('width', '');
							});
									
							Home.container.find('ul#optionsList').children('li').removeClass('hidden');
						}	
					}
					
					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()
								 			.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/home/timeSelect/selectboxRedBell_' + AppData.langId + '.jpg) no-repeat'});
				selectedLi.find('span.expMessage').text(AppData.langHome.optionExpires);
				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.showOptonClosedPopup)
							  // .attr('disabled', true);
						
						selectedLi.find('span.expMessage').text(AppData.langHome.optionExpires);	   
				 	}
				 	else{
				 		selectedOption.inputElem.css({background: 'url(appProxy/site/home/timeSelect/selectboxRedBell_' + AppData.langId + '.jpg) 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.find('form.positionForm').attr('id').split('_').slice(1, 2)));

				}
					
			}	
		});	
		
	},
	
	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');
	},
	
	showOptonClosedPopup: function(event){
		var boxList = event.data.boxList
		Position.showPopup(boxList, AppData.langHome.optionIsClosedPopupTitle,  AppData.langHome.waitingForExpiryPopupMessage, '', false);
		
	},
	
	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();
		});
		
	},
	
	/**
	* Refresh Page
	*
	**/
	refresh: function(){
		location.reload(true);
		
	}
	
	
}
$(document).ready(function() { 
	
	Home.init();
});
