var General = {
	container: null,

	// @var Date Time from lightstreamer
	dateTime: null,
        
        clockMgr: null,


    // @var string - contains time formatted as HH:MM:SS
    timeString: '',

	browserOffset : 0,

	serverOffset : 0,

    // @var PushPage Lightstrearer page
    lsPage: null,

	init: function() {

		var userTime = new Date();
		General.browserOffset = -userTime.getTimezoneOffset() * 60 * 1000;
        
		General.serverOffset = AppData.timeZoneOffset;
		//Apply browser (user) timezone offset to the server offset, to correct times
		AppData.timeZoneOffset = General.serverOffset - General.browserOffset;
//AppData.langId = "en";
//alert(AppData.langId);
        General.startClock();
		/*General.container = $('div.container'); SLOW!!!*/
        General.container = $('#mainContainer');
		/*General.container.find('select#langSelect').selectbox(
			{
				inputClass: 'selectboxLang',
				containerClass: 'selectbox-wrapperLang',
				hoverClass: 'current',
				scrollBar: false
			});*/
            General.container.find('#langSelect').sSelect();
		//events
			//login fields
                        
		$('li.text input[name="email"], #loginDialog input[name="email"]').focus(General.onFocusEmail).blur(General.onBlurEmail);
		General.container.find('li.textPassword input[name="passwordFake"]').bind('focus', {container: 'li.textPassword'}, General.onFocusPassword);
		General.container.find('li.textPassword input[name="password"]').bind('blur', {container: 'li.textPassword'}, General.onBlurPassword);

        $('#loginDialog input[name="passwordFake"]"').bind('focus', {container: '#loginDialog'}, General.onFocusPassword);
        $('#loginDialog input[name="password"]').bind('blur', {container: '#loginDialog'}, General.onBlurPassword);

		//change lang event - this ul created by iSelect plugin
		//General.container.find('div#langSelect_container ul li').click(General.changeLang);
		General.container.find('#langSelect').change(General.changeLang);

            //General.container.find('div.leftSide .clickLiveChat').click(General.onclickLiveChat);

//if (AppData.allowedTrader == '0'){
//    General.allowUserDialog();
//}
            //if login error exists, shake it
           /* if( !AppData.isLoggedIn && General.container.find('#loginError').length ){
                //wait half a sec for js to finish
                setTimeout( function(){General.shakeById('loginError')}, 800);
            }*/
           //show login form if login error
            if ( typeof AppData.loginError != 'undefined' && AppData.loginError == true){
                        General.loginDialog();
            }

            //show important messagse sent from the server, if any
            General.displayFlashMessages();

		/** turn on the lang seelct 
			fixes ie bug in which design goes 
			wild when the site was open in small window
		**/
        // General.checkCookie();

         General.changMarquee();
		$('div#selectLangPane').css('visibility', 'visible')
	},

 changMarquee: function (){
            var obj = $('.news_box marquee');
            var objTop = $('#HeaderNews marquee');
            var objCont = obj.html();
            var objTopCont = objTop.html();
            var objTopW = 0;
            objTop.find('.expiredItem').each(function(i){
                objTopW = objTopW + $(this).outerWidth();
                return objTopW;
            });
 
            if( $(obj).children('*').length > 0 ){
                obj.replaceWith('<div id="marqueeParent" style="position: relative; height: '+obj.height()+'px; overflow: hidden; width: '+obj.width()+'px; left: 9px;" ><div  id="marquee" style="position: absolute; top: 0;">'+objCont+'</div></div>')
                var goMarquee = setTimeout("General.scroll('#marquee')", 1000);
                $('#marqueeParent').hover(function(){
                    $(this).find('#marquee').stop();
                }, function(){
                    General.scroll("#marquee");
                });
            }
 
            if( $(objTop).children('*').length > 0 ){
                objTop.replaceWith('<div id="marqueeTopParent" style="position: relative; height: '+objTop.height()+'px; overflow: hidden; width: '+objTop.width()+'px;float: left;" ><div  id="marqueeTop" style="position: absolute; top: 0; left: 0; width: '+objTopW+'px;">'+objTopCont+'</div></div>')
                var goMarquee = setTimeout("General.scroll('#marqueeTop')", 1000);
                $('#marqueeTopParent').hover(function(){
                    $(this).find('#marqueeTop').stop();
                }, function(){
                    General.scroll("#marqueeTop");
                });
            }
        },


                scroll: function(cont)
                {
                    var speed = 0.01 ;
                    var obj=$(cont);
                    var posBlock=0;

                    /*detect marquee top or side*/

                    if(cont == '#marquee'){
                        posBlock='top';
                        jQuery.fn.getHW = function(){return $(this).height()}
                    }
                   else if(cont == '#marqueeTop'){
                        posBlock='left';
                        jQuery.fn.getHW = function(){return $(this).width();}
                    }

                    var objHW = parseFloat(obj.getHW());
                    var scrollHW = objHW - parseFloat(obj.parent().getHW());

                    var objPos = parseFloat(obj.css(posBlock));
                    var speedHW = scrollHW + objPos;
                    var speedTime0 = scrollHW/speed;
                    var speedTime = speedHW*speedTime0/scrollHW;


                    if(cont == '#marquee'){
                        obj.animate({'top':  -scrollHW+'px'}, speedTime, 'linear', function(){
                            $(cont).css({'top': 0});
                            General.scroll(cont);
                        });
                    }
                    else if(cont == '#marqueeTop'){
                        obj.animate({'left':  -scrollHW+'px'}, speedTime, 'linear', function(){
                            $(cont).css({'left': 0});
                            General.scroll(cont);
                        });
                    }
                },



	onFocusEmail: function(event){
		var field = $(event.target);
		var value = $.trim(field.val());
		if(value == AppData.generalLang.email)
			field.val('');
	},

	onBlurEmail: function(event){
		var field = $(event.target);
		var value = $.trim(field.val());
		if(value == '')
			field.val(AppData.generalLang.email)

	},

	onFocusPassword: function(event){
		var elementContainer = event.data.container;
		
		var fakeField = $(event.target);
		var realField = $(elementContainer + ' input[name="password"]');
		//hide fake field, and show the real one
		fakeField.addClass('hidden');
		realField.removeClass('hidden').focus();
	},

	onBlurPassword: function(event){
		var elementContainer = event.data.container;
		var field = $(event.target);
		var fakeField = $(elementContainer + ' input[name="passwordFake"]');
		var value = $.trim(field.val());
		if(value == ''){
			field.addClass('hidden');
			fakeField.removeClass('hidden');
		}
	},

	changeLang: function(event){
            
	//var optionText = $(event.target).text();
		var lang = $('select#langSelect :selected').val();
                
        //if logged, log this
        if(AppData.isLoggedIn == true){
            $.post(
                    'rpcProxy/setPreferenceLanguage',
                    {langId : lang},
                    function(result){
                        location = location.protocol + '//' +location.hostname + location.pathname + '?lang=' + lang;
                    },
                    'json'
                );
        }else{
        	location = location.protocol + '//' +location.hostname + location.pathname + '?lang=' + lang;
                console.log(lang);
                console.log(location);
        } 
	},

    /**
     * Intiates lightstreamer
     *
     * @return PushPage - light streamer's page object
     */
     initLightstreamer: function() {
        if ( General.lsPage === null ) {
            var page = new PushPage();
            General.lsPage = page;
            if ( AppData.domain.indexOf('server') !== -1 && jQuery.browser.msie) {
                // page domain in IE should be null when in local server
                page.context.setDomain( null );
            } else {
                page.context.setDomain(AppData.domain.substring(AppData.domain.indexOf('.')+1));
				
            }


            page.context.setDebugAlertsOnClientError(false);

            page.onEngineCreation = function(engine) {
                    if (AppData.domain.indexOf('server') !== -1)  {
                        engine.connection.setLSHost(AppData.domain);
                        engine.connection.setLSPort(8080);
                    } else {
					engine.connection.setLSHost("ls2." + AppData.domain.substring(AppData.domain.indexOf('.')+1));
					engine.connection.setLSPort(80);
                    }
                    engine.connection.setAdapterName("WinSOLSDataAdapter");
                    
                    engine.changeStatus("STREAMING");

                    engine.onStatusChange = function(status) {
                        //console.log('ls status change trigger, new status: ' + status)
                    }
					

            }



            /*           page.onClientError = function(msg) {
                if (console) {
                    console.log(msg);
                }
            }

            page.onClientAlert = page.onClientError;*/

            page.bind();
            page.createEngine("SpotOption", "appProxy", "SHARE_SESSION", true);
            //console.log('init lightstreamer');
        } // end if ( typeof General.lsPage === 'undefined' )

        return General.lsPage;
    },

    
    startClock: function ( ) {
        
        General.clockMgr = new Clock(General.onUpdateTime);
        
        var page = General.initLightstreamer();

        var timeTable   = new NonVisualTable(['time'], ['dateTime'], "MERGE");
        page.addTable(timeTable, "timeTable");
        
        /* called every minute */
        timeTable.onItemUpdate = function( item, itemUpdate, itemName ) {
            //sync the client clokc with the server
            General.clockMgr.resetDateTime(itemUpdate.getNewValue('dateTime'));
                
        } // end timeTable.onItemUpdate

    },
    /*
     * called form clock.js
     **/
     onUpdateTime: function(){
        
        if (!$('#LStime #LShour').size()) {
            return;
        } 
        
        var hoursDiv = $('#LStime #LShour');
        var minutesDiv = $('#LStime #LSminute');
        var secondsDiv = $('#LStime #LSseconds');
        var dateLi     = $('#LStime #LSdate');
        var hours = General.dateTime.getHours();
        var minutes =  General.dateTime.getMinutes();
        var seconds =  General.dateTime.getSeconds();

        if ( hours < 10) hours     = '0' + hours;
        if ( minutes < 10) minutes = '0' + minutes;
        if ( seconds < 10) seconds = '0' + seconds;


        hoursDiv.text( hours );
        minutesDiv.text ( minutes );
        secondsDiv.text ( seconds );
       
        General.timeString =  hours + ':' + minutes + ':' + seconds;
        if ( typeof Graphs !== 'undefined' ) {
            Graphs.onUpdateTime();

        }
       
        if( typeof window[AppData.pageId] === 'object' ) { 
            window[AppData.pageId].onUpdateTime();
        } else if (AppData.pageId == 'home') {
                
                if(typeof AppData.oneTouchCompact != 'undefined'){
                       
                        OneTouch.onUpdateTime();//Reffers to one touch compact



                }
            Home.onUpdateTime(); 
            MyPositions.onUpdateTime();
        }
       
        // console.log('after Home.onUpdateTime()');

        var day = General.dateTime.getDate();
        var month = General.dateTime.getMonth() + 1;
        var year = new String(General.dateTime.getFullYear());

        if (day < 10) day     = '0' + day;
        if (month < 10) month = '0' + month;

        var s=AppData.generalLang.th;
        if(month===1) s=AppData.generalLang.st;
        if(month===2) s=AppData.generalLang.nd;
        if(month===3) s=AppData.generalLang.rd;

        var monthName = AppData.generalLang["month"+parseInt(month)];
        var date =  day + s + ' ' + monthName + ' ' + year;


        if (dateLi.html() != date)  {
                dateLi.html(date);
        }  
     },
    
    /*
     * this will shake whatever object inserted, by id
     */
       shakeById: function(itemId){
        function s(id,pos){g(id).left=pos+'px';}
        function g(id){return document.getElementById(id).style;}
        function shake(id,a,d){c=a.shift();s(id,c);if(a.length>0){setTimeout(function(){shake(id,a,d);},d);}else{try{g(id).position='static';;}catch(e){}}}
        var p=new Array(7,15,7,0,-7,-15,-7,0);
//        var p=new Array(15,30,15,0,-15,-30,-15,0);
//        var p=new Array(5,10,5,0,-5,-10,-5,0);
        p=p.concat(p.concat(p));
        g(itemId).position='relative';
        shake(itemId,p,12)
       },
       /*
        * centralized code for calling one liveChat popup window
        */
       onclickLiveChat: function(){
          lpButtonCTTUrl = 'https://server.iad.liveperson.net/hc/33115296/?cmd=file&file=visitorWantsToChat&site=33115296&imageUrl=https://server.iad.liveperson.net/hcp/Gallery/ChatButton-Gallery/English/General/1a&referrer='+escape(document.location);lpButtonCTTUrl = (typeof(lpAppendVisitorCookies) != 'undefined' ? lpAppendVisitorCookies(lpButtonCTTUrl) : lpButtonCTTUrl);lpButtonCTTUrl = ((typeof(lpMTag)!='undefined' && typeof(lpMTag.addFirstPartyCookies)!='undefined')?lpMTag.addFirstPartyCookies(lpButtonCTTUrl):lpButtonCTTUrl);window.open(lpButtonCTTUrl,'chat33115296','width=475,height=400,resizable=yes');return false;
       },
           /*
     * for geting specific cookie value
     */
    getCookie: function(name) {
		var search = name + "="
		var returnvalue = "";
		if (document.cookie.length > 0) {
			offset = document.cookie.indexOf(search)
			if (offset != -1) {
	    		offset += search.length
	    		end = document.cookie.indexOf(";", offset);
	    		if (end == -1) end = document.cookie.length;
	    		returnvalue = unescape(document.cookie.substring(offset, end))
			}
		}
			return returnvalue;
	},

          /* a generic dialog box */
       dialog: function(html, title, options) {
                if(typeof title == 'undefined' || title == null )
                title == '';

           var defaults = {
                autoOpen: true,
                width: '400',
                height: '170',
                modal:true,
                dialogClass: 'baseTheme',
                title: title,
                buttons: {"Ok": function() {$(this).dialog("close");}} ,
                closeText: 'close X', //TODO:this will need to be tanslatable,
                close: function(event, ui) {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;
       },

       stopPropagation: function(event){
         event.stopPropagation();
       },

//         allowUserDialog: function(sInstructions){
//            var loginDialog = $('#allowDialog');
//            loginDialog.dialog({
//                autoOpen: true,
//                width: '320',
//                height: '280',
//                modal:true,
//                dialogClass: 'baseTheme allowDialog',
//                title: 'Attention Traders from the US',
//                closeText: '', //TODO:this will need to be translatable,
//                close: function() {},
//                resizable: false,
//                buttons: {"Accept": function() {
//$.post('AllowUser/agree', function() {
//location.reload(true);
//});
//            }
//                }
//            });
//            $('.ui-dialog-titlebar-close').remove();
//       },

       loginDialog: function(sInstructions){
            var loginDialog = $('#loginDialog');
            loginDialog.dialog({
                autoOpen: true,
                width: '270',
                height: '276',
                modal:true,
                dialogClass: 'baseTheme',
                title: AppData.generalLang.startTrading,
                closeText: 'close X', //TODO:this will need to be translatable,
                close: function() {loginDialog.dialog('destroy');},
                resizable: false,
                buttons: {"openAccount": function() {General.redirect('OpenAccount')},
                           "forgotPassword": function() {General.redirect('ForgotPassword')}
                }
            });
            
         var dialogBaseDiv = loginDialog.parent();
            dialogBaseDiv.find("button span:contains('openAccount')").text(AppData.generalLang.openAccount);
                    /*.parent().button({icons: {primary:'ui-icon-cart'}})
                    .find('span.ui-button-text').text(AppData.generalLang.openAccount);*/
                
            dialogBaseDiv.find("button span:contains('forgotPassword')").text('Forgot Password');
                    /*.parent().button({icons: {primary:'ui-icon-comment'}})
                    .find('span.ui-button-text').text('Forgot Password');*/
            loginDialog.find("input[name='email']").blur();
                

           if(typeof sInstructions != 'undefined'){
             loginDialog.find('div.instructions').html(sInstructions);
           }
          loginDialog.find('input:submit').button();

         /*loginDialog.find('a.forgotPass').button({icons: {primary:'ui-icon-comment'}});
          loginDialog.find('a.openAccount').button({icons: {primary:'ui-icon-cart'}});*/
       },
       /*
        * javascript redirect to a page within the site
        */
       redirect:function(page, langId , moreGetParams){
           if(typeof page == 'undefined' || page == '' || page == null)
               page = AppData.pageId;
           if(typeof langId == 'undefined' || langId == '' || langId == null)
               langId = AppData.langId;

              newLocation = location.protocol + '//' +location.hostname
               + AppData.url + page + '?lang=' + langId
               if(typeof moreGetParams != 'undefined'){
                   newLocation += '&' + moreGetParams;
               }
               window.location =  newLocation ;
       },
       getURLParam: function( name )
        {
          name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
          var regexS = "[\\?&]"+name+"=([^&#]*)";
          var regex = new RegExp( regexS );
          var results = regex.exec( window.location.href );
          if( results == null )
            return "";
          else
            return results[1];
        },
        /*
	* useage
	*   General.jnotification({
			removebutton     : false, //if to show close button. default false
			message			 : 'error reading the file!', //your message
			time			 : 4000, //timeout. default 5000
			msgType		     : 'error', // can be notice, success, alert, error. default value 'notice'.
			className        : 'myClass' //custom class if needed
		})});
	*/
	jnotification: function(options) {
		var defaults = {
		removebutton     	: false,
		time			 	: 5000,
		msgType             : 'notice',
		className			: ''
		};

		var o = $.extend({}, defaults, options);
				if(!$('.jnotification').length){    
					var timeout = setTimeout('removebar()',o.time);
					var _message_span = $(document.createElement('span')).addClass('jnotification-content').html(o.message);
					var _wrap_bar;
					_wrap_bar	  = $(document.createElement('div')).addClass('jnotification jnotification_'+o.msgType) ;
					if(o.className) _wrap_bar.addClass(o.className);

					if(o.removebutton){
						var _remove_cross = $(document.createElement('a')).addClass('jnotification-cross');
						_remove_cross.click(function(e){removebar();})
					}
					else{
						_wrap_bar.css({"cursor"	: "pointer"});
						_wrap_bar.click(function(e){removebar();})
					}
					_wrap_bar.append(_message_span).append(_remove_cross).insertBefore($('.container'))//.fadeIn('fast');
					.css({top:'-50px'}).animate({top: 0}, 200);
				}
		removebar = function () {
			if($('.jnotification').length){
				clearTimeout(timeout);
				$('.jnotification')//.fadeOut('fast',function(){
					.animate({top: '-50px'}, 200, function(){
					$(this).remove();
				});
			}
		};
	},
        /*display flash messages shows after server redirect */
    displayFlashMessages: function() {

            if(AppData.flashMessage != undefined){
                var len = AppData.flashMessage.length;
                for (i=0; i <len ;i++){
                    if (AppData.flashMessage[i].options.msgDisplay == 'notification'){
                        var params = $.extend({}, AppData.flashMessage[i].options , {message: AppData.flashMessage[i].message});
                        General.jnotification(params);
                    }else{ //fallback option is dialog
                       if(typeof AppData.flashMessage[i].options.title == 'string')
                            var title = AppData.flashMessage[i].options.title;
                        else
                            var title = '';
                        General.dialog(AppData.flashMessage[i].message, title ,AppData.flashMessage[i].options);
                    }
                }
            }
    }
}
$(document).ready(function() {
    
	General.init();
});
