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');

       //General.container.find('#langSelect').change(General.changeLang);
       General.container.find('#langSelect').selectbox(
			{
				inputClass: 'selectboxLanguage ' + AppData.langId,
				containerClass: 'selectbox-wrapperLanguage',
				chainTitle: true,
				onChange : General.changeLang
			}
		);

        $('input[name="email"], #loginDialog input[name="email"]').focus(General.onFocusEmail).blur(General.onBlurEmail);

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

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

        //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 select fixes ie bug in which design goes wild when the site was open in small window
        **/
        $('div#selectLangPane').css('visibility', 'visible')
		
		// Fix design changing behavior of faq.js
		if (typeof FAQ != "undefined"){
	        FAQ.correctTabView = function(){};
		}
		
		//Add defaut currency for not logged in users
		if (AppData && !AppData.accountCurrency) {
			AppData.accountCurrency = unescape("%u20AC");
		}
		
		String.prototype.capitalize = function() {
			return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
		};
		
		/*
		var dialogDiv =  $('#dialog2').clone(true).attr('id', 'rolloverDialog').show();
		expirySelect = $('<select><option>15:15</option><option>16:16</option></select>').addClass('expirySelect');
		dialogDiv.find('div.firstRow div.right').html("12:15").end().find('div.secondRow  div.right').html(expirySelect).end().find('div.thirdRow div.right').html(45);
		
		dialogDiv.dialog({
            title: AppData.langHome.rollOverTitle,
			autoOpen: true,
			width: 383,
			height: 200,
			modal:true,
			resizable: false,
			dialogClass: 'baseTheme platformDialog',
			closeText: 'close'
		});	
		
	   $('#rolloverDialog').find('select').selectbox(
			{
				inputClass: 'selectboxTime',
				containerClass: 'selectbox-wrapperTime',
				scrollBar: true,
				chainTitle: true
			}
		);		
		*/

               setInterval(setSize,500);

var sizeSent = 0;
function setSize(){
if(parent.resizeMe != undefined){
  var newSize = getHeight();
  if(sizeSent != newSize){
parent.resizeMe(window.location,newSize);
   sizeSent = newSize;
  }
  }
}

function getHeight(){
var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

    },

    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 fakeField = $(event.target);
        var realField = fakeField.parent().find('input[name="password"]');

        fakeField.hide();
        realField.show().focus();
    },

    onBlurPassword: function (event) {
        var realField = $(event.target);
        var fakeField = realField.parent().find('input[name="passwordFake"]');
        var value = $.trim(realField.val());

        if (value == '') {
            realField.hide();
            fakeField.show();
        }
    },

    changeLang: function (event) {
        var lang = $('select#langSelect :selected').val();
		if (AppData.langId != lang) {
			$("#Header .selectboxLanguage").attr("class","selectboxLanguage " + lang);
			//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.bind();
            page.createEngine("SpotOption", "appProxy", "SHARE_SESSION", true);
        } // 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 (!$('#LShour').size()) {
            return;
        }
        var hoursDiv = $('#LShour');
        var minutesDiv = $('#LSminute');
        var secondsDiv = $('#LSseconds');
        var dateLi = $('#LSdate');

        var page = General.initLightstreamer();
        var timeTable = new NonVisualTable(['time'], ['dateTime'], "MERGE");
        page.addTable(timeTable, "timeTable");

        timeTable.onItemUpdate = function (item, itemUpdate, itemName) {
			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();
                }
				
                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 = 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
    */
    onclickLiveChat: function () {
        lpButtonCTTUrl = 'https://server.iad.liveperson.net/hc/76280277/?cmd=file&file=visitorWantsToChat&site=76280277&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, 'chat76280277', '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: 320,
            height: 200,
            modal: true,
            dialogClass: 'baseTheme generalDialog',
            title: title,
			resizable: false,
            buttons: { "Ok": function () { $(this).dialog("close"); } },
            closeText: ' ',
            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;
    },

	/* error popup - all the error popups are created here */
	generalErrorDialog: function(popupTitle, popupFirstLine, popupSecondLine, showDeposit){
		var generalErrorDialog = $('#generalErrorDialog');
		/* if there is a button of deposit - create this popup */
		/* the only different between this and the next function is the button of deposit\OK */

		if(showDeposit) {
			generalErrorDialog.dialog({
				autoOpen: true,
				width: 320,
				height: 200,
				modal:true,
				dialogClass: 'baseTheme',
				title: popupTitle,
				closeText: ' ',
				close: function() {generalErrorDialog.dialog('destroy');},
				resizable: false,
				buttons: { 
					"deposit": function() {General.redirect('MyAccount/depositFunds')}
				}
			});
		}
		/* this is the same function with a different button */
		else {
			generalErrorDialog.dialog({
				autoOpen: true,
				width: 320,
				height: 200,
				modal:true,
				dialogClass: 'baseTheme', 
				title: popupTitle,
				closeText: 'close x', //TODO:this will need to be translatable,
				close: function() {generalErrorDialog.dialog('destroy');},
				resizable: false,
				buttons: { "OK": function() {
										generalErrorDialog.dialog('destroy');
									}
				}
		});
		}
		var boxList= $('#generalErrorDialog');
		if(showDeposit) {
			boxList.find('div.generalErrorDialogContent a#depositLink').removeClass('hidden');
		}
		var popup = boxList.find('div.generalErrorDialogContent');
		popup.find('span.popupWarning').text(popupFirstLine);
	   

		popup.find('span.popupSum span').text(popupSecondLine);
		popup.removeClass('hidden');
		popup.find('div.popupMessageContainer').removeClass('hidden');
   },

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

    loginDialog: function (sInstructions) {
        var loginDialog = $('#loginDialog');
        loginDialog.dialog({
            autoOpen: true,
            width: 313,
            height: 320,	
            modal: true,
            dialogClass: 'baseTheme loginPopup',
            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:contains('openAccount')").text(AppData.generalLang.openAccount).addClass("OpenAccount");
        dialogBaseDiv.find("button:contains('forgotPassword')").text("forgotPassword").addClass("forgetPas");
        loginDialog.find("input[name='email']").blur();


        if (typeof sInstructions != 'undefined') {
            loginDialog.find('div.instructions').html(sInstructions);
        }
        //loginDialog.find('input:submit').button();
    },
    /*
    * 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);
                }
            }
        }
    },
	
	capitalize : function (str) {
		return str.charAt(0).toUpperCase() + str.slice(1);
	}
}


$(document).ready(function () {

    General.init();

});

