function TwoDigit(x){
if(typeof(x)!='number')return x;
if(x<10)x='0'+x;
return x;
}

var General = {
serverDate:null,
    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;

        if(document.domain.match(/www/i)) document.domain = document.domain.replace("www.", "");
        
        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){
            if (!AppData.accountCurrencyCode) AppData.accountCurrencyCode = 'USD';
            if(!AppData.localizedData)AppData.localizedData = {currencies:{}};
            if(!AppData.localizedData.currencies) AppData.localizedData.currencies[AppData.accountCurrencyCode] = {symbol:'$'};
            if (!AppData.accountCurrency) {
                        AppData.accountCurrency = AppData.localizedData.currencies[AppData.accountCurrencyCode].symbol;
            }
}

		
		String.prototype.capitalize = function() {
			return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
		};

                General.changMarquee();
		/*
		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
			}
		);		
		*/
		General.SetClassByBrowser();
		
    },
	SetClassByBrowser:function(){ 
         
         var Browser = navigator.userAgent; 
          
         if(Browser.indexOf('Opera')>= 0){ 
            $('body').addClass('Opera');  
         } 
         if(Browser.indexOf('Firefox')>= 0){ 
             $('body').addClass('Firefox');  
         } 
         if(Browser.indexOf('Chrome')>= 0){ 
             $('body').addClass('Chrome');  
         } 
         if(Browser.indexOf('MSIE')>= 0){ 
             $('body').addClass('Explorer');  
         } 
         if(Browser.indexOf('Safari')>= 0){ 
             $('body').addClass('Safari');  
         } 
    },
    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();
            page.onClientError = function(msg) {
                if (console) {
                    console.log(msg);
                }
            }

            page.onClientAlert = page.onClientError;
            
            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);
				General.serverDate=TwoDigit(General.dateTime.getMonth()+1)+'/'+TwoDigit(General.dateTime.getDate())+'/'+General.dateTime.getFullYear();
                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')}
				}
			});
                      $("button:contains('deposit')").text(AppData.generalLang.deposit);
		}
		/* 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');
                      generalErrorDialog.find("button:contains('deposit')").text(AppData.generalLang.deposit);
		}
		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(AppData.generalLang.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);
	},
	/* new marquee fix */
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;
            });
 //alert(objTop.parent().width());
            if( $(obj).children('*').length > 0 ){
                obj.replaceWith('<div id="marqueeParent" style="position: relative; height: 249px; 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: 817px;float: left; top: 0;left:50%; margin-left:-479px;color: white" ><div  id="marqueeTop" style="position: absolute; top: 5px; 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);
			});
		}
	}
	

}


$(document).ready(function () {
    General.init();

		var ulHTT = $('.NavPanel div.how_to_trade ul li');
		ulHTT.click(function(){
			if($(this).hasClass('binaryOptions')) {$(this).parent().attr('class','howToTradeTabs1')};
			if($(this).hasClass('optionsBuilder')) {$(this).parent().attr('class','howToTradeTabs2')};
			if($(this).hasClass('oneTouch')) {$(this).parent().attr('class','howToTradeTabs3')};
		});
		
		// var depositTabs = $('.Container .contentContainer ul#paymentMethods li');
		// depositTabs.click(function(){
			// alert('qwe');
			// alert($(this).parent().attr('class'));
			// if ($(this).text().match('Card')){$(this).parent().attr('class','payment1')};
			// if ($(this).text().match('Debit')){$(this).parent().attr('class','payment2')};
			// if ($(this).text().match('Money bookers')){$(this).parent().attr('class','payment3')};
			// if ($(this).text().match('Wire transfer')){$(this).parent().attr('class','payment4')};
			// if ($(this).text().match('cash')){$(this).parent().attr('class','payment5')};
			// if ($(this).attr('id') = 'creditCard') {$(this).parent().attr('class','payment1')};        
			// if ($(this).attr('id') = 'wire') {$(this).parent().attr('class','payment2')};        
			// if ($(this).attr('id') = 'cashU') {$(this).parent().attr('class','payment3')};       
			// if ($(this).attr('id') = 'moneybookers'){$(this).parent().attr('class','payment4')};        
			// if ($(this).attr('id') = 'ewallet')  {$(this).parent().attr('class','payment5')};       
		// });
		
});

