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 = $('div.container'); SLOW!!!*/
        General.container = $('div.headerMain');
        General.container.find('#langSelect').sSelect();
        General.container.find('#langSelect').change(General.changeLang);
                      
            //$('#langSelect').sSelect();
		//events
			//login fields
                        
		$('li.text input[name="email"], #loginForm 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);

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

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




                $('form.loginForm input[name="email"], #loginForm input[name="email"]').focus(General.onFocusEmail).blur(General.onBlurEmail);
		General.container.find('form.loginForm input[name="passwordFake"]').bind('focus', {container: 'form.loginForm'}, General.onFocusPassword);
		General.container.find('form.loginForm input[name="password"]').bind('blur', {container: 'form.loginForm'}, General.onBlurPassword);

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

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


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

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


            //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();
           General.selectedTab();

	},
        
        selectedTab : function(){
            var url = window.location;
            var urlparts = url.pathname.split('/');
            var path = urlparts[1].toLowerCase();
            var tabs = $('.topNav').find('li');
            var linkUri = null;
            for(var i = 0; i < tabs.length; i++){      
                linkUri = $(tabs[i]).find('a').attr('href').split('/')[1].toLowerCase();
                if(path == linkUri){
                    tabs.removeClass('selected');
                    $(tabs[i]).addClass('selected');
                }
                
                //console.log(linkUri);
            }
            

        },

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

	/* changeLang: function(btnId){
		var lang = btnId;
        //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;
        } 
	},*/

    /**
     * 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;
                
                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

    },
    /*
     * 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
        */
        
        /* 
			 live chat cource :
			 <script type="text/javascript" charset="UTF-8" src="https://server.iad.liveperson.net/hc/50508565/?cmd=mTagRepstate&site=50508565&buttonID=1&divID=lpButDivID-1294246890176&bt=1&c=1"></script> 
        */
        
       onclickLiveChat: function(){
          lpButtonCTTUrl = 'https://server.iad.liveperson.net/hc/50508565/?cmd=file&file=visitorWantsToChat&site=50508565&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,'chat50508565','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();
       },

       loginDialog: function(sInstructions){
            var loginDialog = $('#loginDialog');
            loginDialog.dialog({
                autoOpen: true,
                width: '393',
                height: '250',
                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: {"a": function() {General.redirect('A')}
                }
            });
            /*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();
	var regEx = /^(https)/;
	if (!regEx.test(document.URL)){
		
		/*var fbTw = $('.sslBugy');
		for(i=0; i < fbTw.length; i++){
			fbTw[i].innerHTML = '';
		}*/
 }
        else{
            //    document.getElementById('LStime').css('display','none');
$("#LStime").hide();
}
});

