var General = {
	container: null,

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


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

    // @var PushPage Lightstrearer page
    lsPage: null,

	init: function() {
        General.startClock();
		General.container = $('div.container')
			//login fields
		General.container.find('li.text 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);

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


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

	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 = General.container.find(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 = General.container.find(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 (!$('.header .time .hour').size()) {
            return;
        }
        
        var hoursDiv = $('.header .time .hour');
        var minutesDiv = $('.header .time .minute');
        var secondsDiv = $('.header .time .seconds');
        var dateLi     = $('.header .time .date');
        
        var page = General.initLightstreamer();
        //console.log(page);
        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();
                if (AppData.domain.indexOf('server') === -1) {
                    General.dateTime = new Date(serverTime + d.getTimezoneOffset()*60*1000);
                } else {
                    General.dateTime = new Date(serverTime);
                    
                }
                

				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 GraphsCompact !== 'undefined' ) {
                    GraphsCompact.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();
                }
                //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;
                
                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;
	}
}

$(document).ready(function() {
	General.init();
	if (!console) var console;
});
