var General = {
	container: null,

	// @var Date Time from lightstreamer
	dateTime: 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;


		General.startClock();
		General.container = $('#mainContainer');
        
		$('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);

		//remove the live person title
		General.container.find('tr.lpPoweredBy').remove();

        //fix for selelected page for sidebar navigation
        General.fixSidebarNavigation();

		//navigation
		General.container.find('div.navRightSide ul').droppy();
		//sidebar navigation
		General.container.find('#pageGroupNavigation ul').droppy();

            //show important messagse sent from the server, if any
     General.displayFlashMessages();
		//footer navigation
		General.container.find('div.footer div.nav ul').droppy();



       $("a.livechat_link").click(function(event){General.onClickLiveChat(event)});
                
//                var callMeNowAID = $("div#callmenow_link_script a").attr("id");
                $("div#callmenow_link_script span").remove();
                $("div#callmenow_link_script a").html($("div#callmenow_actual_design a").html());
//                console.log($("div#callmenow_actual_design a").html());
//                $("div#callmenow_link_script a").html($("div#callmenow_actual_design a").html());

//                $("#" + callMeNowAID).remove();

//                $("a#callmenow_link").attr("id", callMeNowAID);
            var url = document.URL;
 var regEx1 = /relogin/i;
      if (AppData.isLoggedIn){
            setInterval ( General.stillLoggedCheck , 60000 );
        }
  else if(url.search(regEx1) != -1){ 
  General.dialog(AppData.generalLang.reloginMessage, AppData.generalLang.reloginHeader);
  }
            General.changMarquee();
	},
        
        
            stillLoggedCheck: function(event){
        $.post(
                'home/amILoggedIn',
                {},
                function(result){
                 if (result =='notLoggedIn') {
                     window.location=AppData.url+"home/pro/relogin";
                 }
                },
                'json'
               );
    },
        /*change Marquee*/

                changMarquee: function (){
                        var obj = $('.news marquee');
                        var objTop = $('div.news_flash ul.expiredRates marquee');
                        var objCont = obj.html();
                        var objTopCont = objTop.html();
                        var objTopW = 0;
                        objTop.find('li').each(function(i){
                                objTopW = objTopW + $(this).outerWidth();
                                return objTopW;
                            });
                        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>')
                        objTop.replaceWith('<div id="marqueeTopParent" style="position: relative; height: '+objTop.height()+'px; overflow: hidden; width: '+objTop.width()+'px;" ><div  id="marqueeTop" style="position: absolute; top: 0; left: 0; width: '+objTopW+'px;">'+objTopCont+'</div></div>')

                        var goMarquee = setTimeout("General.scroll('#marquee')", 1000);
                        var goMarquee = setTimeout("General.scroll('#marqueeTop')", 1000);

                        $('#marqueeParent').hover(function(){$(this).find('#marquee').stop();}, function(){General.scroll("#marquee");});
                        $('#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 option[text="' + optionText + '"]').val();

		location = location.protocol + '//' +location.hostname + location.pathname + '?lang=' + lang;
	},

   /**
     * 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("ls." + AppData.domain.substring(AppData.domain.indexOf('.') + 1));
                    engine.connection.setLSPort(80);
                }
                engine.connection.setAdapterName("SOLSDataAdapter");

                    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;
    },

    /**
     * Initializes a clock which starts its sync from the server's own clock.
     * Ticks every 100ms
     *
     */
    startClock: function ( ) {
        if (!$('#LStime #LShour').size()) {
            return;
        }

        var hoursDiv = $('#LStime #LShour');
        var minutesDiv = $('#LStime #LSminute');
        var secondsDiv = $('#LStime #LSseconds');
        var dateLi     = $('#LStime #LSdate');

        var page = General.initLightstreamer();

        var timeTable   = new NonVisualTable(['time'], ['dateTime'], "MERGE");
        page.addTable(timeTable, "timeTable");
        /**
         *
         * item, itemUpdate, itemName) {

        if (itemUpdate.isValueChanged('rate')) {
            var rate = itemUpdate.getNewValue('rate');
            //alert(rate);
            var lastUpdated = itemUpdate.getNewValue('lastUpdated');

         */

        timeTable.onItemUpdate = function( item, itemUpdate, itemName ) {
            //console.log('clock update');
             if (itemUpdate.isValueChanged('dateTime')) {

                var serverTime = new Number(itemUpdate.getNewValue('dateTime'));
             	
                var d=new Date();
               
            
               General.dateTime = new Date(serverTime + AppData.timeZoneOffset);
                

				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;

				//Used in BugReport page
				$('#userTime').val(General.timeString);
				$('#userTZOffset').val(General.browserOffset / 60000);
				$('#submitBugReport').attr('disabled', false);
                
                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()).substring(2);

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

               // var date = '<strong>' + 'GMT time' + '</strong>' + '<br/>' +AppData.daysLang[General.dateTime.getDay()] + '<br />' +  day + '.' + month + '.' + year;
               var date =  AppData.daysLang[General.dateTime.getDay()] + ' ' + day + '.' + month + '.' + year;


                if (dateLi.html() != date)  {
                      dateLi.html(date);
                }
            }
        } // end timeTable.onItemUpdate

    },
    openAccount: function ( ) {
    	if(AppData.openAccount.isAllowed){
	    	if (typeof(openAccount) !== "undefined"){
	    		openAccount.init();
	    	}else{
	    		alert('error: missing files needed for OpenAccount');
	    	}
    	}else{
    		//user apperantly not allowed by country
			$.flashMessage(AppData.langOpenAccount.notAllowedRegion, 
					{msgType:"warning", displayType: 'dialog'});
    	}
    },
    /*
     * 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;
	},

    onClickLiveChat: function(event) {
        event.preventDefault();
        window.open($("div#live_chat_link_script a").attr('href'),'','height=475,width=400');
    },

    onClickCallmenow: function(event) {
        event.preventDefault();
        window.open($("div#callmenow_link_script a").attr('href'),'','height=475,width=400');
    },
    fixSidebarNavigation: function(){
       //fix for selelected page for sidebar navigation
       //make sure pageGroupNavigation box on this page, and that none are selected
       if(General.container.find('#pageGroupNavigation').size()==0
                || General.container.find('#pageGroupNavigation ul li.selected').size()==1)
           return;

           var mySelectedPage = null;
               /*special cases*/
        //homepage
        if(AppData.pageId === 'home' && AppData.pageOp === 'index' )
            mySelectedPage =  AppData.url+'home/pro';
        //deposit subpages
        if(AppData.isLoggedIn){
            var regexS = "^MyAccount/deposit.+";
            var regex = new RegExp( regexS );
            if(regex.test( AppData.pageId+'/'+AppData.pageOp ,'i' )){
                mySelectedPage =  AppData.url+'MyAccount/depositFunds';
            }
        }
        //console.log(mySelectedPage);
       //figure out what page we're on
       if(! mySelectedPage){
           mySelectedPage = AppData.url+AppData.pageId;
           if(AppData.pageOp !== 'index')
                mySelectedPage +='/'+AppData.pageOp
       }
        General.container.find('#pageGroupNavigation ul li a[href*="'+mySelectedPage+'"]:first')
            .parent('li').addClass('selected');

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

           var defaults = {
                autoOpen: true,
                width: 502,
                height: 220,
                modal:true,
                dialogClass: 'bbinary_dialog',
                title: title,
                buttons: {"Ok": function() {$(this).dialog("close");}} ,
                closeText: 'X', //TODO:this will need to be tanslatable,
                open: function() { $('div.ui-widget-overlay').addClass('ui-widget-overlay_bbinary_dialog') },
                close: function(event, ui) {$(this).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;
       },
       

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

       loginDialog: function(sInstructions){
            var loginDialog = $('#loginDialog');
            loginDialog.dialog({
                autoOpen: true,
                width: 270,
                height: 276,
                modal:true,
                dialogClass: 'bbinary_dialog',
                title: AppData.generalLang.startTrading,
                closeText: 'close X', //TODO:this will need to be translatable,
                close: function() {loginDialog.dialog('destroy');},
                resizable: false,
                open: function() { $('div.ui-widget-overlay').addClass('ui-widget-overlay_bbinary_dialog') },
                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();
	if (!console) var console;
    
});

