var changeCache = '';

jQuery.fn.clearForm = function() {
  return this.each(function() {
 var type = this.type, tag = this.tagName.toLowerCase();
 if (tag == 'form')
   return jQuery(':input',this).clearForm();
 if (type == 'text' || type == 'password' || tag == 'textarea')
   this.value = '';
 else if (type == 'checkbox' || type == 'checkbox'){
   this.checked = false;
   jQuery("input[checkedme='checkedme']").attr("checked","checked");
 }
 else if (tag == 'select')
   this.selectedIndex = 0;
  });
};

jQuery(document).ready(function($){
	
	
	/*jQuery("body").bind("mouseover",function(){
		if(!mouseEnter){
			jQuery("#right-navigation-ul applet").show();
		} else {
			jQuery("#right-navigation-ul applet").hide();
			mouseEnter=0;
		}
	});*/
	
	/*
	jQuery("body").bind("click",function(){
		if(divDisplayed) {
			jQuery("#right-navigation-ul applet").hide();
		} else {
			jQuery("#right-navigation-ul applet").show();
		}
	});*/

    if (typeof pageHeader != 'undefined' && jQuery('.streamTitle').length) 
        jQuery('.streamTitle').text(pageHeader);
    
    /** lazy loading for sign-in, register and profile dialog */
    if (jQuery('#sign-in').length) 
        jQuery('#sign-in').click(LoginStatus.signIn);
    
    LeftMenu.init();
    MessageDialog.init();
    WatchList.init();
    People.init();
    SymbolRealTime.init();
    Calendar.init();
	
});

var SymbolRealTime = {
    init: function(){
        this.perc = null;
        if (jQuery('#real-time-update').length) {
            SymbolRealTime.updateStockInfo();
            SymbolRealTime.pollRealTimeUpdate();
        }
        if (jQuery('#stock-price-additional-more').length) {
            jQuery('#stock-price-additional-more').click(function(){
                if (jQuery('#stock-price-additional-tab').is(':hidden')) {
                    jQuery(this).text('hide');
                    jQuery('#stock-price-additional-tab').attr('style', 'display:block');
                    SymbolRealTime.updateStockMoreInfo();
                }
                else {
                    jQuery(this).text('more..');
                    jQuery('#stock-price-additional-tab').attr('style', 'display:none');
                }
            });
        }
    },
    updateStockMoreInfo: function(){
        if (jQuery('#stock-price-additional-tab').length && jQuery('#stock-price-additional-tab').is(':visible')) {
            var symbolParameter = Parameter.get('search');
            if (symbolParameter != null && symbolParameter != undefined) {
                var url = Properties.STOCK_ADDITONAL_INFO + symbolParameter;
                jQuery.getJSON(url, function(data){
                    if (data.DATA) {
                        jQuery('#stock-price-additional-tab').children().remove();
                        for (var i = 0; i < data.DATA.length; i++) {
                            var name = data.DATA[i][0];
                            var value = data.DATA[i][1];
                            var span = jQuery('<div></div>');
                            span.html(name + ': <b>' + value + '</b>');
                            jQuery('#stock-price-additional-tab').append(span);
                        }
						jQuery('#stock-price-additional-tab div:last').attr("style","border-bottom:none;width:100%; float:none; clear:both;");
                    }
                    setTimeout(SymbolRealTime.updateStockMoreInfo, 20000);
                });
            }
        }
    },
    updateStockInfo: function(){
        var symbolParameter = Parameter.get('search');
        if (symbolParameter != null && symbolParameter != undefined) {
            var url = Properties.SYMBOL_NAME + symbolParameter;
            jQuery.getJSON(url, function(data){
                if (data.NAMESYMBOL) {
                
                    var symbolname = jQuery.trim(data.NAMESYMBOL + '');
                    var marketsymbol = jQuery.trim(data.MARKETSYMBOL + '');
                    
                    if (jQuery('.streamTitle').length) 
                        jQuery('.streamTitle').text(symbolname);
                    if (jQuery('#stock-info').length) 
                        jQuery('#stock-info').text(marketsymbol);
                }
            });
        }
    },
    pollRealTimeUpdate: function(){
    
        var symbolParameter = Parameter.get('search');
        if (symbolParameter != null && symbolParameter != undefined) {
        
            var url = Properties.SYMBOL_REAL_TIME_INFO + symbolParameter;
				
            jQuery.getJSON(url, function(data){
				
                if (data.MESSAGE && data.MESSAGE == 'OK') {
                
                    var price = jQuery.trim(data.PRICE + '');
                    var perc = jQuery.trim(data.PERC + '');
                    var change = jQuery.trim(data.CHANGE + '') + '';
                    var date = jQuery.trim(data.DATA + '');
                    
                    if (jQuery('#real-time-price').length) 
                        jQuery('#real-time-price').text(price);
                    
                    if (jQuery('#real-time-date').length) 
                        jQuery('#real-time-date').text(date);
                    
                    if (jQuery('#real-time-change').length && change != '' && change != null) {
						
						//alert("Change: "+change+' | Cache: '+changeCache);
						
                        //if positive = green, negative = red, 0 = black
                        if (change.charAt(0) == '-' && changeCache != change) {
							//alert("basso");
                            change = change.replace('-', '');
                            perc = perc.replace('-', '');
                            jQuery('#real-time-change').removeClass("change-green");
                            jQuery('#real-time-change').removeClass("change-black");
                            jQuery('#real-time-change').addClass("change-red");
							
							jQuery('#real-time-stock').jPush({
								bgcolor : '#FFE6E6'
							});
							
                        }
                        else 
                            if (change == '0.00' || changeCache == change) {
                                jQuery('#real-time-change').removeClass("change-red");
                                jQuery('#real-time-change').removeClass("change-green");
                                jQuery('#real-time-change').addClass("change-black");							
                            }
                            else {
                                jQuery('#real-time-change').removeClass("change-black");
                                jQuery('#real-time-change').removeClass("change-red");
                                jQuery('#real-time-change').addClass("change-green");
								
								jQuery('#real-time-stock').jPush({
									bgcolor : '#E6FFE8'
								});
																
                            }
							
                        jQuery('#real-time-change').text(change + perc + '');
					
						changeCache = change;
						
                    }
                    //market close
                    if (SymbolRealTime.perc != null && perc != SymbolRealTime.perc) {
                        jQuery('#real-time-stock').addClass("market-close");
                    }
                    else {
                        jQuery('#real-time-stock').removeClass("market-close");
                    }
                }
                setTimeout(SymbolRealTime.pollRealTimeUpdate, 30000);
            });
        }
    }
};

var MessageDialog = {
    init: function(){
        jQuery(window).scroll(function(){
            jQuery('.common-message').css('top', jQuery(window).scrollTop() + 'px');
        });
        
    },
    show: function(header, message, type){
        if (jQuery('.common-message').length) {
            jQuery('.common-message').slideDown('slow');
            jQuery('.common-message-header').text(header);
            jQuery('.common-message-msg').text(message);
            
            if (type == 'ERROR') {
                jQuery('.common-message').css('background-color', '#FF0000');
                jQuery('.common-message').css('color', '#FFF');
            }
            else {
                jQuery('.common-message').css('background-color', '#90EE90');
                jQuery('.common-message').css('color', '#000');
            }
            clearTimeout(this.t);
            this.t = setTimeout(function(){
                jQuery('.common-message').hide(1000)
            }, 5000);
        }
    }
};

var LeftMenu = {
    init: function(){
    
        if (LoginStatus.authenticate()) {
            if (jQuery('#friend-li').length) 
                jQuery('#friend-li').css('display', 'block');
            if (jQuery('#mention-li').length) 
                jQuery('#mention-li').css('display', 'block');
            if (jQuery('#direct-message-li').length) 
                jQuery('#direct-message-li').css('display', 'block');
        }
        else {
            if (jQuery('#friend-li').length) 
                jQuery('#friend-li').css('display', 'none');
            if (jQuery('#mention-li').length) 
                jQuery('#mention-li').css('display', 'none');
            if (jQuery('#direct-message-li').length) 
                jQuery('#direct-message-li').css('display', 'none');
        }
        
        /*if (jQuery('#trend-submenu-link').length) {
         jQuery('#trend-submenu-link').click(function(){
         if (jQuery('#trending-popup').length) {
         if (jQuery('#trending-popup').is(':hidden')) {
         jQuery('#trending-popup').slideDown('slow');
         jQuery(this).removeClass('trend-submenu-link-up');
         jQuery(this).addClass('trend-submenu-link-down');
         }
         else {
         jQuery('#trending-popup').slideUp('slow');
         jQuery(this).removeClass('trend-submenu-link-down');
         jQuery(this).addClass('trend-submenu-link-up');
         }
         }
         });
         }*/
    }
};

var TwitterStream = {
    start: function(options){
        var options = options ||
        {};
        var self = this;
        this.queue = [];
        this.delay = 15000;
        this.animating = false;
        this.paused = false;
        this.max_id = options.max_id || null;
        this.since_id = options.since_id || null;
        this.logged_in = options.logged_in || false;
        this.poll_id = options.poll_id || null;
        this.last_poll_id = options.last_poll_id || null;
        this.symbol = options.symbol || null;
        this.max_messages = 10; //this.max_messages = 30;//default
        this.url = options.url;
		
        this.animationdelay = 0;
        
        this.init();		
		
        MessageTools.init();
        FinvizCharts.init();
		
    },
    init: function(){
    
        var self = this;
		
		
		setTimeout(function(){
			self.animationdelay = 600;
		},(self.delay-2000));		
		
        /* System starting point */
        jQuery(document).ready(function(){
            self.poll();//initial load
            self.timeout = setTimeout(function(){
                this.animate = true;
                self.update();
            }, self.delay);
            
            if (jQuery('#pause').length) {
                jQuery('#pause').click(function(){
                    TwitterStream.togglePause();
                });
            }
            if (jQuery('#moreBtn').length) {
                jQuery('#moreBtn').click(function(){
                    TwitterStream.more();
                });
            }
        });
        
    },
    push: function(item){

        this.queue.unshift(item);
    },
    pop: function(){
        return this.queue.pop();
    },
    update: function(){
        var self = this;
        self.poll();
        if (self.timeout) {
            clearTimeout(this.timeout);
        }
        this.timeout = setTimeout(function(){
            self.update();
        }, self.delay);
    },
    poll: function(){
        var self = this;
        jQuery.getJSON(self.pollUrl(), function(data){
            if (data.DATA) {
                var maxTweets = data.DATA.length > TwitterStream.max_messages ? TwitterStream.max_messages : data.DATA.length;
                for (var i = (maxTweets - 1); i >= 0; i--) {
                    var statusid = data.DATA[i][0];
                    var twittid = data.DATA[i][1];
                    var tweettext = data.DATA[i][2];
                    var tweetdate = data.DATA[i][3];
                    var username = data.DATA[i][4];
                    var avatarurl = data.DATA[i][5];
					var idfavorite = data.DATA[i][6];
                    var li = Twitts.createMessage(statusid, tweettext, tweetdate, username, avatarurl, idfavorite);
                    TwitterStream.poll_id = statusid
                    self.push(li);
                }
                self.animate();
            }
        });
    },
    update_pause_button: function(text){
        if (jQuery('#pause').length) {
            jQuery('#pause').text(text);
        }
    },
    togglePause: function(){
        var self = this;
        if (self.paused) {
            self.resume();
            self.update_pause_button('Pause');
        }
        else {
            self.pause();
            self.update_pause_button('Resume');
        }
    },
    pause: function(){
        this.paused = true;
        this.animate();
    },
    resume: function(){
        this.paused = false;
        this.animate();
    },
    animate: function(){
        var self = this;
        if (this.animating) {
            return false;
        }
        self.updateWaitMessage();
		
        if (!this.paused && this.queue.length > 0) {
            this.animating = true;
            var item = this.pop();
            item.prependTo('#streams');
            item.css('margin-top', "-" + item.attr('offsetHeight') + "px");
            item.animate({
                marginTop: "0px"
            }, self.animationdelay, "linear", function(){
                self.animating = false;
                self.chop();
                self.animate();
                self.twittsAdded(item);
            });
            return true;
        }
        else {
			
            this.animating = false;
            return false;
        }
    },
    chop: function(){
        if (jQuery('#streams').children().length > this.max_messages) {
            jQuery('#streams li:last').remove();
        }
    },
    more: function(){
        var self = this;
        STHelper.loading('#moreloading');
        jQuery.getJSON(self.lastPollUrl(), function(data){
            if (data.DATA) {
                var maxTweets = data.DATA.length > self.max_messages ? self.max_messages : data.DATA.length;
                for (var i = 0; i < maxTweets; i++) {
                
                    var statusid = data.DATA[i][0];
                    var twittid = data.DATA[i][1];
                    var tweettext = data.DATA[i][2];
                    var tweetdate = data.DATA[i][3];
                    var username = data.DATA[i][4];
                    var avatarurl = data.DATA[i][5];
					var idfavorite = data.DATA[i][6];
                    
                    var li = Twitts.createMessage(statusid, tweettext, tweetdate, username, avatarurl, idfavorite);
                    
                    if (jQuery('#morestreams').length) {
                        jQuery('#morestreams').append(li);
                        self.twittsAdded(li);
                    }
                }
                STHelper.clearloading('#moreloading');
            }
        });
    },
    twittsAdded: function(li){
        FinvizCharts.mouseover(li);
    },
    updateWaitMessage: function(){
        if (this.queue.length > 0) {
            jQuery('#pausemsg').attr('style', 'display:block;');
            jQuery('#waitcounter').text(this.queue.length);
        }
        else {
            jQuery('#pausemsg').attr('style', 'display:none;');
        }
    },
    getJSONURL: function(url){
        return url + '&callback=?';
    },
    pollUrl: function(){
        var url = TwitterStream.url;
        if (TwitterStream.poll_id != null) 
            url = TwitterStream.url + '&poll_id=' + TwitterStream.poll_id;
        url = TwitterStream.getJSONURL(url);
        return url;
    },
    lastPollId: function(){
        last_poll_id = null;
        
        if (jQuery('#morestreams li:last').length) {
            last_poll_id = jQuery('#morestreams li:last').attr('id');
        }
        else {
            if (jQuery('#streams li:last').length) 
                last_poll_id = jQuery('#streams li:last').attr('id');
        }
        
        return last_poll_id;
    },
    lastPollUrl: function(){
        var url = TwitterStream.url;
        if (TwitterStream.lastPollId() != null) 
            url = TwitterStream.url + '&poll_id=' + TwitterStream.lastPollId() + '&mode=morerequest';
        url = TwitterStream.getJSONURL(url);
        return url;
    }
};

var YAHOO = {
    callback: function(data){
        alert(data);
    }
};

/* Dom creator */
var Twitts = {
    createMessage: function(statusid, tweettext, tweetdate, username, avatarurl, idfavorite){
        var avatar = this.avatar(avatarurl);
        var content = this.content(statusid, username, tweettext, tweetdate);
        var li = this.twitt(statusid);
        li.append(avatar);
        li.append(content);
		if(idfavorite!=''){
			var classFav = 'favorite_on favorite_on_tiny';
		} else {
			var classFav = 'favorite_off favorite_off_tiny';
		}
		if(idfavorite!=undefined){
			
			var onclickTradingRoom = "jQuery('#header-signin').click()";
			var onclickChart = "jQuery('#header-signin').click()";

			if(jsLoginStatus!='203'){
				onclickChart='Twitts.userActive=\''+username+'\';jQuery(\'#link-chart-btn\').click()';
				onclickTradingRoom='Twitts.userActive=\''+username+'\';jQuery(\'#event-btn\').click()';
			}
			
			var htmlStreamAction = '<div class="action_stream" style="display:none; position:absolute; right:193px; bottom:26px;">'
				+'<a href="javascript:;" title="'+calendarLocale.FAVORITE_STREAM+'" style="display:block; position:absolute; top:8px; right:123px; width:15px; height:15px" onclick="Favorite.call(\''+statusid+'\',\'2\', jQuery(this));" class="'+classFav+'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>'
				+'<a href="javascript:;" title="'+calendarLocale.ADD_CHART_STREAM+'" style="background:url(\'/trade-project/images/message/link-chart.png\') no-repeat scroll center center transparent; display:block; position:absolute; top:8px; right:105px; width:18px; height:15px" onclick="'+onclickChart+'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>'
				+'<a href="javascript:;" title="'+calendarLocale.ADD_EVENT_STREAM+'" style="background:url(\'/images/message/events_icon_big.png\') no-repeat scroll center center transparent; display:block; position:absolute; top:8px; right:83px; width:18px; height:15px" onclick="'+onclickTradingRoom+'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>'
			+'</div>';
			
			li.find(".msgDate").append(htmlStreamAction);
			li.append(content);
			
		}
        MessageTools.initMouseenter(li);
        MessageTools.initMouseleave(li);
        return li;
    },
    twitt: function(statusid){
        var tr = jQuery('<li>');
        tr.attr('id', statusid);
        return tr;
    },
    avatar: function(avatarurl){
        var img = jQuery('<img>');
        img.attr('src', avatarurl);
        img.attr('alt', 'Avatar');
        var span = jQuery('<span>');
        span.attr('class', 'avatar');
        span.append(img);
        return span;
    },
    content: function(statusid, username, tweettext, date){
    
        var href = jQuery('<a></a>');
        href.attr('href', '/user/user?user=' + username);
        href.attr('class', 'username');
        href.html('@' + username);
        href.attr('onclick', 'Search.userPage(\'' + username + '\'); return false;');
        
        var body = jQuery('<span>');
        body.attr('class', 'body');
        
        var formattedText = FinvizCharts.replaceSymbol(tweettext);
        formattedText = FinvizCharts.replaceUser(formattedText);
        formattedText = FinvizCharts.replaceURL(formattedText);
        body.html(formattedText);
        
        body.append(this.msgDate(statusid, username, date));
        
        var content = jQuery('<span>');
        content.attr('class', 'content');
        content.append(href);
        content.append(body);
        
        return content;
    },
    msgDate: function(statusid, username, date){
        var href = jQuery('<a></a>');
        href.attr('href', '/' + username + '/message/' + statusid);
        href.html(date);
        
        //new Date(eval(jQuery(this).attr('data')));
        var msgDate = jQuery('<span>');
        msgDate.attr('class', 'msgDate');
        msgDate.append(href);
        return msgDate;
    },
    urlClicked: function(url){
        window.open(url);
    }
};

var FinvizCharts = {
    init: function(){
        var chartPopupHTML = '<img id="chart-popup-img" alt="loading..." src="/trade-project/images/loading3.gif"></img>';
        var chartPopup = document.createElement('div');
        jQuery(chartPopup).attr('style', 'display:none');
        jQuery(chartPopup).attr('id', 'chart-popup');
        jQuery(chartPopup).attr('class', 'chart-popup');
        jQuery(document.body).append(jQuery(chartPopup));
        chartPopup.innerHTML = chartPopupHTML;
        this.chart = jQuery(chartPopup);
        
        if (jQuery('#finvix-symbol-graph').length) {
            var symbolParameter = Parameter.get('search');
            var chart_url = FinvizCharts.getChartURL(symbolParameter);
            jQuery('#finvix-symbol-graph').attr('src', chart_url);
        }
    },
    replaceSymbol: function(text){
        var regexp = /\${1}[a-zA-Z]+[a-zA-Z0-9_.]*[\s\0]?/g;
        var hrefExp = '<a class="charts" href="#" onclick="Search.symbolPage(\'#1\');" rel="#1">$#1</a>';
        var symbols = text.match(regexp);
        if (symbols != undefined && symbols != null) {
            for (var i = 0; i < symbols.length; i++) {
                var symbol = symbols[i].replace(/s/g, '').replace(/\$/g, '');
                symbol = jQuery.trim(symbol);
                var href = hrefExp.replace(/#1/g, symbol);
                text = text.replace('$' + symbol, href);
            }
        }
        return text;
    },
    replaceUser: function(text){
        var regexp = /\@{1}[\w]{1,}[\W\s\0]?/gi;
        var hrefExp = '<a class="users" href="#" onclick="Search.userPage(\'#1\');">@#1</a>';
        var users = text.match(regexp);
        if (users != undefined && users != null) {
            for (var i = 0; i < users.length; i++) {
                var user = users[i].replace(/\W/g, '').replace(/\s/, '');
                var href = hrefExp.replace(/#1/g, user.toUpperCase());
                text = text.replace('\@' + user, href);
            }
        }
        return text;
    },
    replaceURL: function(text){
        var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
        text = text.replace(exp, '<a href="#" onclick="Twitts.urlClicked(\'$1\');" class="url">$1</a>');
        return text;
    },
    getChartURL: function(symbol){
        var chart_url = '';
        if (/_F$/.test(symbol)) {
            chart_url = "http://finviz.com/fut_chart.ashx?t=" + symbol.replace('_F', '') + "&p=d1&s=m";
        }
        else {
            if (/(AUD|CAD|CHF|EUR|GBP|NZD|USD|JPY){2}/.test(symbol)) {
                chart_url = "http://finviz.com/fx_image.ashx?" + symbol + "_m5_s.png";
            }
            else {
                chart_url = "http://finviz.com/chart.ashx?t=" + symbol + "&p=d&s=m";
            }
        }
        return chart_url;
    },
    mouseover: function(obj){
        var self = this;
        var id = jQuery(obj).attr('id');
        
        jQuery('#' + id + ' .charts').mouseenter(function(e){
            var href = this;
            var symbol = jQuery(href).attr('rel');
            symbol = jQuery.trim(symbol);
            
            var chart_url = FinvizCharts.getChartURL(symbol);
            
           /* var offsettop = jQuery(href).offset().top + 20;
            var viewportHeight = jQuery(window).height();
            if (viewportHeight < (e.clientY + 200)) {
                offsettop = offsettop - ((e.clientY + 260) - viewportHeight);
            }*/
			var offsettop = jQuery(href).offset().top + 20;
			var viewportHeight = jQuery(window).height();
			var meHeight = 200;
			
			//alert("OffsetTop: "+offsettop+"\n"+"viewportHeight: "+viewportHeight+"\n"+"meHeight: "+meHeight);
			
			if((e.clientY+meHeight)>viewportHeight){
				offsettop = ((offsettop-meHeight)-20);
			}
			
            self.chart.attr('style', 'display:block;');
            self.chart.css({
                'top': (offsettop) + 'px',
                'left': (jQuery(href).offset().left - 290) + 'px'
            });
            jQuery('#chart-popup-img').attr('src', chart_url);
        });
        jQuery('#' + id + ' .charts').mouseleave(function(){
            self.chart.attr('style', 'display:none;');
            //jQuery('#chart-popup-img').attr('src', '/trade-project/images/loading3.gif');
        });
    },
    openSymbol: function(value, type){
    },
    addSymbolFinviz: function(){
    
    }
};

/* Helper class */
var STHelper = {
    format_date: function(date){
        var hour = (date.getHours() + 12) % 12;
        if (hour === 0) {
            hour = 12;
        }
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        var formatted_date = months[date.getMonth()] + ". " + date.getDate() +
        " at " +
        hour +
        ":";
        formatted_date += ((date.getMinutes() > 9) ? date.getMinutes() : "0" +
        date.getMinutes());
        formatted_date += " " + ((date.getHours() < 12) ? 'AM' : 'PM');
        return formatted_date;
    },
    loading: function(loadObj){
        if (jQuery(loadObj).length) {
            jQuery(loadObj).attr('style', 'display:block');
        }
    },
    clearloading: function(loadObj){
        if (jQuery(loadObj).length) {
            jQuery(loadObj).attr('style', 'display:none');
        }
    }
};

jQuery.fn.st_date = function(){
    return jQuery(this).each(function(){
        var local_date = new Date(eval(jQuery(this).attr('data')));
        jQuery(this).find('a').html(STHelper.format_date(local_date));
    });
};

var DialogUtil = {
    showPopup: function(id){
        var popup = jQuery(id);
		jQuery("#calendar_edit_message").hide();
        if (popup.length) {
            DialogUtil.mask();
            popup.css('display', 'block');
            popup.centerInClient({
                container: window,
				forceAbsolute: true
            });
			popup.css("-moz-border-radius","5px");
			popup.append('<img style="position:absolute; right:-20px; top:-20px; cursor:pointer; z-index:999999" onclick="DialogUtil.hidePopup(\''+id+'\')" src="/lib/jquery/close_x.png">');
        }
    },
    hidePopup: function(id){
        var popup = jQuery(id);
		jQuery("#calendar_edit_message").hide();
        if (popup.length) {
			Applet.hidden=0;
            DialogUtil.unmask();
            popup.css('display', 'none');
			setTimeout(function(){
				jQuery("#right-navigation-ul applet").show();
			},30);
        }
		jQuery(".details_tooltip").remove();
		jQuery("#quoteContainer").hide();
    },
    mask: function(){
        if (jQuery('#mask').length == 0) {
            var maskDiv = jQuery('<div>');
            maskDiv.attr('id', 'mask');
            jQuery(document.body).append(maskDiv);
        }
        var mask = jQuery('#mask');
        mask.attr('style', 'display:block;');
        mask.css({
            'height': jQuery(window).height() + 'px',
            'width': jQuery(window).width() + 'px'
        });
    },
    unmask: function(){
        var mask = jQuery('#mask');
        mask.attr('style', 'display:none;');
    }
};

var Parameter = {
    get: 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];
    }
};

var People = {
    init: function(){
    
        //people link header
        jQuery('#people-link').click(function(){
            if (LoginStatus.forceLogin()) {
                DialogUtil.showPopup('#people-dialog');
				jQuery("#primary_tab").click();
				
            }
        });
        
        var peoplesearch = jQuery('#people-list-text');
        if (peoplesearch.length) {
            peoplesearch.attr('autocomplete', 'off');
            peoplesearch.keydown(function(e){
				var e;
				var kkk=e.keyCode;
				if(kkk=='13'){
					return false;
				}
				SuggestBox.keylistener(kkk,'none');
            });
            peoplesearch.focus(function(){
                SuggestBox.setWidget(this, 'user', 'compaq');
            });
        }
        
        //tab events
        jQuery('.people-tabs-view .tab').click(function(){
            var tab = jQuery(this);
            var ref = jQuery(this).attr('ref');
            
            jQuery(this).parent().siblings().removeClass('selected');
            jQuery(this).parent().addClass('selected');
            
            if (jQuery('#people-' + ref + '-tab').length) {
                jQuery('.people-content').attr('style', 'display:none;');
                jQuery('#people-' + ref + '-tab').attr('style', 'display:block;');
            }
            if (ref == 'blocked') {
                People.blockedUsers();
            }
            if (ref == 'watch') {
                People.peopleList();
            }
        });
        
        //people find user
        jQuery('#people-search-btn').click(function(){
            People.searchUser();
        });
        //people find user search field
        jQuery('#people-list-text').keyup(function(e){
            if (e.keyCode == 13) // enter key
                People.searchUser();
        });
        //Close Button
        jQuery('#people-list-close').click(function(){
            DialogUtil.hidePopup('#people-dialog');
        });
    },
    peopleList: function(){
        if (LoginStatus.forceLogin()) {
            //DialogUtil.hidePopup('#people-dialog');
            PeopleList.showPeopleList('user');
        }
    },
    blockedUsers: function(){
        jQuery('#people-blocked-users').children().remove();
        jQuery.getJSON(Properties.PEOPLE_BLOCKED_USER, function(data){
            if (data) {
                if (data.DATA.length != 0) {
                    jQuery(data.DATA).each(function(){
                        var id = this[0];
                        var name = this[1];
                        var photoid = this[2];
                        var avatar = this[3];
                        People.addBlockedUser(id, name, avatar);
                    });
                }
                else {
                    People.noBlockedUserFound('There were no people found.');
                }
            }
        });
    },
    searchUser: function(){
        jQuery('#people-search-users').children().remove();
        var inputtextD = jQuery('#people-list-text').val();
        if (inputtextD.length > 2) {
            jQuery.getJSON(Properties.SEARCH_SUGGEST_USER + inputtext, function(data){
                if (data) {
                    if (data.DATA.length != 0) {
                        jQuery(data.DATA).each(function(){
                            var id = this[0];
                            var name = this[1];
                            var avatar = this[2];
                            People.addUser(id, name, avatar);
                        });
                    }
                    else {
                        People.noUserFound('No user matched found');
                    }
                }
            });
        }
    },
    addUser: function(id, user, avatar){
        var row = '<tr><td width="60px" class="symbol"><img src="' + avatar + '"></img></td><td class="user-text"><a href="#" onclick="Search.userPage(\'' + user + '\');">' + user + '</a></td><td>' + '</td></tr>';
        jQuery('#people-search-users').append(row);
    },
    noUserFound: function(user){
        var row = '<tr><td class="user-text" align="center">' + user + '</td></tr>';
        jQuery('#people-search-users').append(row);
    },
    addBlockedUser: function(userid, user, avatar){
        var row = '<tr><td width="60px" class="symbol"><img src="' + avatar + '"></img></td><td class="user-text"><a href="#" onclick="Search.userPage(\'' + user + '\');">' + user + '</a></td><td align="center"><a o href="#" onclick="People.unblock(\'' + user + '\', this);" class="people-unblock-option">Unblock</a></td></tr>';
        jQuery('#people-blocked-users').append(row);
    },
    noBlockedUserFound: function(user){
        var row = '<tr><td class="user-text" align="center">' + user + '</td></tr>';
        jQuery('#people-blocked-users').append(row);
    },
    unblock: function(user, obj){
        var url = Properties.PEOPLE_UNBLOCK_USER + user;
        jQuery.getJSON(url, function(data){
            if (data != null) {
                if (data.statusCode == '101') {
                    jQuery(obj).parent().parent().remove();
                }
            }
        });
    }
};



var PeopleList = {

    init: function(){
    
        this.type = 'user';//values=symbol/user
        this.currentListId = '';
        
        //PeopleList link
        jQuery('#people-list-link').click(function(){
            if (LoginStatus.forceLogin()) {
                PeopleList.showPeopleList('user');
            }
        });
        
        //Close Button
        jQuery('#people-list-close').click(function(){
            DialogUtil.hidePopup('#people-list-dialog');
            if (PeopleList.type == 'user') {
                DialogUtil.showPopup('#people-dialog');
            }
        });
        //ADD LIST BUTTON
        jQuery('#add-people-list-btn').click(function(){
            PeopleList.addList();
        });
        
        //ADD Symbol BUTTON
        jQuery('#people-list-edit-symbol-btn').click(function(){
            PeopleList.addSymbol();
        });
        
        //Symbol Done Button 
        jQuery('#people-list-back').click(function(){
            PeopleList.displayList();
        });
        
        var watchsearch = jQuery('#people-list-edit-symbol-text');
        if (watchsearch.length) {
            watchsearch.attr('autocomplete', 'off');
            watchsearch.keydown(function(e){
				var e;
				var kkk=e.keyCode;
				if(kkk=='13'){
					return false;
				}
				setTimeout(function(){
					SuggestBox.keylistener(kkk,'none');
				},100);
            });
            watchsearch.focus(function(){
                SuggestBox.setWidget(this, PeopleList.type, 'compaq');
            });
        }
    },
    showPeopleList: function(val){
        PeopleList.displayList();
        PeopleList.getList();
		jQuery("#people-list-tab").show();
		jQuery('#people-list-add-new-entry').text('Add New User');
    },
    getList: function(){
        PeopleList.showMessage('loading...');
        jQuery('#people-list-table').children().remove();
        var url = Properties.WATCH_LIST_VIEW + '&flag=' + PeopleList.type;
        jQuery.getJSON(url, function(data){
            if (data.DATA) {
                for (var i = 0; i < data.DATA.length; i++) {
                    var listid = data.DATA[i][0];
                    var listname = data.DATA[i][1];
                    var userid = data.DATA[i][2];
                    
                    PeopleList.addListNode(listid, listname);
                }
            }
            PeopleList.loadedlist = 'true';//load only once
            PeopleList.hideMessage();
        });
    },
    addList: function(){
        if (LoginStatus.forceLogin()) {
            var listvalue = jQuery('#add-people-list-text').val();
            if (listvalue != undefined && jQuery.trim(listvalue) != '') {
                PeopleList.showMessage('saving...');
                var url = Properties.WATCH_LIST_ADD + listvalue + '&flag=' + PeopleList.type;
                jQuery.getJSON(url, function(data){
                    if (data != null) {
                        if (data.statusCode != undefined && data.statusCode == '101') {
                            var listid = data.Id;
                            var listname = data.Name;
                            PeopleList.addListNode(listid, listname);
                        }
                        else {
                            PeopleList.showMessage('Error while saving');
                        }
                    }
                    else {
                        PeopleList.showMessage('Error while saving');
                    }
                    PeopleList.hideMessage();
                });
            }
        }
    },
    addListNode: function(listid, listname){
        if (listid != undefined && jQuery.trim(listid + '') != '' && listname != undefined && jQuery.trim(listname) != '') {
        
            var tr = jQuery('<tr></tr>');
            var html = '<td class="people-list-entry"><a href="#" rel="#1" id="people-list-entry-#1" class="people-list-entry">#2</a>' +
            '</td><td class="people-list-link"><a href="#" id="people-list-entry-view-#1" rel="#1" class="people-list-entry-view"></a> </td>' +
            '</td><td class="people-list-link"><a href="#" id="people-list-entry-edit-#1" rel="#1" class="people-list-entry-edit"></a> </td>' +
            ' <td class="people-list-link"><a href="#" rel="#1" id="people-list-entry-delete-#1" title="Delete" class="people-list-entry-delete"> </a></td>';
            html = html.replace(/#1/g, listid);
            html = html.replace(/#2/g, listname);
            
            jQuery('#people-list-table').append(tr);
            jQuery(tr).html(html);
            jQuery('#add-people-list-text').val('');
            
            jQuery('#people-list-entry-view-' + listid).click(function(){
                var list = jQuery(this).attr('rel');
                var listnam = 'undefined';
                if (jQuery('#people-list-entry-' + list).length) {
                    listnam = jQuery('#people-list-entry-' + list).text();
                }
                PeopleList.redirect(listid, listnam);
            });
            
            jQuery('#people-list-entry-delete-' + listid).click(function(){
                var link = this;
                PeopleList.deleteList(link);
            });
            
            jQuery('#people-list-entry-edit-' + listid).click(function(){
                var list = jQuery(this).attr('rel');
                var listnam = 'undefined';
                if (jQuery('#people-list-entry-' + list).length) {
                    listnam = jQuery('#people-list-entry-' + list).text();
                }
                PeopleList.editList(list, listnam);
            });
            
            jQuery('#people-list-entry-' + listid).click(function(){
                var list = jQuery(this).attr('rel');
                var listnam = jQuery(this).text();
                PeopleList.redirect(listid, listnam);
            });
        }
    },
    redirect: function(value, listnam){
        var encodeUrl = Properties.WATCH_LIST_SEARCH + jQuery.URLEncode(value) + '&name=' + jQuery.URLEncode(listnam);
        jQuery(location).attr('href', encodeUrl);
    },
    editList: function(listid, listname){
        PeopleList.currentListId = listid;
        PeopleList.displaySymbols(listid, listname);
        PeopleList.getSymbols(listid);
    },
    deleteList: function(listnode){
        if (LoginStatus.forceLogin()) {
            var listid = jQuery(listnode).attr('rel');
            if (listid != undefined && jQuery.trim(listid) != '') {
                PeopleList.showMessage('saving...');
                var url = Properties.WATCH_LIST_DELETE + listid + "&callback=?" + '&flag=' + PeopleList.type;
                ;
                jQuery.getJSON(url, function(data){
                    if (data != null) {
                        if (data.statusCode != undefined && data.statusCode == '101') {
                            jQuery(listnode).parent().parent().remove();
                        }
                        else {
                            PeopleList.showMessage('Error while saving');
                        }
                    }
                    else {
                        PeopleList.showMessage('Error while saving');
                    }
                    PeopleList.hideMessage();
                });
            }
        }
    },
    getSymbols: function(listid){
        var url = Properties.WATCH_LIST_SYMBOL_VIEW;
        url = url.replace('#1', listid);
        PeopleList.showMessage('loading...');
        jQuery.getJSON(url, function(data){
            if (data.DATA) {
                for (var i = 0; i < data.DATA.length; i++) {
                    var symbolid = data.DATA[i][0];
                    //var listid = data.DATA[i][1];
                    var symbolname = data.DATA[i][2];
                    
                    PeopleList.addSymbolNode(symbolid, symbolname);
                }
            }
            else {
                PeopleList.showMessage('Error while getting symbols');
            }
            this.loadedlist = 'true';//load only once
            PeopleList.hideMessage();
        });
    },
    addSymbol: function(listid){
        if (LoginStatus.forceLogin()) {
            var symbol = jQuery('#people-list-edit-symbol-text').val();
            if (symbol != undefined && jQuery.trim(symbol) != '' && PeopleList.currentListId != '') {
                PeopleList.showMessage('saving...');
                var url = Properties.WATCH_LIST_SYMBOL_ADD;
				//alert(url);
                url = url.replace('#1', PeopleList.currentListId);
                url = url.replace('#2', symbol);
				setTimeout(function(){
					jQuery.getJSON(url, function(data){
						if (data != null) {
							if (data.statusCode != undefined && data.statusCode == '101') {
								var symbolid = data.Id;
								var symbolname = data.Symbol;
								PeopleList.addSymbolNode(symbolid, symbolname);
							}
							else {
								PeopleList.showMessage('Error while saving');
							}
						}
						else {
							PeopleList.showMessage('Error while saving');
						}
						PeopleList.hideMessage();
					});
				},100);
            }
        }
    },
    addSymbolNode: function(symbolid, symbolname){
        if (symbolid != undefined && jQuery.trim(symbolid + '') != '' && symbolname != undefined && jQuery.trim(symbolname + '') != '') {
            var tr = jQuery('<tr></tr>');
            var html = '<td class="people-list-entry"><a href="#" rel="#1" class="people-list-entry">#2</a></td>' +
            ' <td class="people-list-link"><a href="#" id="people-list-entry-symbol-delete-#1" rel="#1" title="Delete" class="people-list-entry-symbol-delete">  </a></td>';
            html = html.replace(/#1/g, symbolid);
            html = html.replace(/#2/g, symbolname);
            
            jQuery('#people-list-edit-table').append(tr);
            jQuery(tr).html(html);
            
            jQuery('#people-list-edit-symbol-text').val('');
            jQuery('#people-list-entry-symbol-delete-' + symbolid).click(function(){
                var symbol = this;
                PeopleList.deleteSymbol(symbol);
            });
        }
    },
    deleteSymbol: function(symbolnode){
        if (LoginStatus.forceLogin()) {
            var symbolid = jQuery(symbolnode).attr('rel');
            if (symbolid != undefined && jQuery.trim(symbolid) != '') {
                PeopleList.showMessage('saving...');
                var url = Properties.WATCH_LIST_SYMBOL_DELETE;
                url = url.replace('#1', symbolid);
                jQuery.getJSON(url, function(data){
                    if (data != null) {
                        if (data.statusCode != undefined && data.statusCode == '101') {
                            jQuery(symbolnode).parent().parent().remove();
                        }
                        else {
                            PeopleList.showMessage('Error while saving');
                        }
                    }
                    else {
                        PeopleList.showMessage('Error while saving');
                    }
                    PeopleList.hideMessage();
                });
            }
        }
    },
    showMessage: function(txt){
        jQuery('#people-list-display-msg').text(txt);
        jQuery('#people-list-display-msg').attr('style', 'display:block;');
    },
    hideMessage: function(){
        jQuery('#people-list-display-msg').text('');
        jQuery('#people-list-display-msg').attr('style', 'display:none;');
    },
    displaySymbols: function(listid, listname){
        jQuery('#people-list-edit').attr('style', 'display: block');
        jQuery('#people-list-close').attr('style', 'display: none');
        jQuery('#people-list-back').attr('style', 'display: block');
        jQuery('#people-list-view').attr('style', 'display: none');
        jQuery('#people-list-display-text').attr('style', 'display: none');
        jQuery('#people-list-header-title').text(listname);
		jQuery('.people-tabs-view .back_to_search').show();
    },
    displayList: function(){
        jQuery('#people-list-edit-table').children().remove();
        jQuery('#people-list-edit').attr('style', 'display: none');
        jQuery('#people-list-back').attr('style', 'display: none');
        jQuery('#people-list-close').attr('style', 'display: block');
        jQuery('#people-list-view').attr('style', 'display: block');
        jQuery('#people-list-display-text').attr('style', 'display: block');
        
        
        if (jQuery('#people-list-header-title').length) {
            if (PeopleList.type == 'user') {
                jQuery('#people-list-header-title').text('People List');
            }
            else {
                jQuery('#people-list-header-title').text('Watch List');
            }
        }
    }
};




var WatchList = {

    init: function(){
    
        this.type = 'symbol';//values=symbol/user
        this.currentListId = '';
        
        //Watchlist link
        jQuery('#watch-list-link').click(function(){
            if (LoginStatus.forceLogin()) {
                WatchList.showWatchList('symbol');
            }
        });
        
        //Close Button
        jQuery('#watch-list-close').click(function(){
            DialogUtil.hidePopup('#watch-list-dialog');
            if (WatchList.type == 'user') {
                DialogUtil.showPopup('#people-dialog');
            }
        });
        //ADD LIST BUTTON
        jQuery('#add-watch-list-btn').click(function(){
            WatchList.addList();
        });
        
        //ADD Symbol BUTTON
        jQuery('#watch-list-edit-symbol-btn').click(function(){
            WatchList.addSymbol();
        });
        
        //Symbol Done Button 
        jQuery('#watch-list-back').click(function(){
            WatchList.displayList();
        });
        
        var watchsearch = jQuery('#watch-list-edit-symbol-text');
        if (watchsearch.length) {
            watchsearch.attr('autocomplete', 'off');
            watchsearch.keydown(function(e){
				var e;
				var kkk=e.keyCode;
				if(kkk=='13'){
					return false;
				}
				setTimeout(function(){
					SuggestBox.keylistener(kkk,'none');
				},100);
            });
            watchsearch.focus(function(){
                SuggestBox.setWidget(this, WatchList.type, 'compaq');
            });
        }
    },
    showWatchList: function(val){
        WatchList.type = val;
		if(!val){
			WatchList.type = 'symbol';
		}
        if (jQuery('#watch-list-add-new-entry').length) {
            if (WatchList.type == 'user') {
                jQuery('#watch-list-add-new-entry').text('Add New User');
            }
            else {
                jQuery('#watch-list-add-new-entry').text('Add New Symbol');
            }
        }
        DialogUtil.showPopup('#watch-list-dialog');
        WatchList.displayList();
        WatchList.getList();
		jQuery('.back_to_search_watch').hide();
    },
    getList: function(){
        WatchList.showMessage('loading...');
        jQuery('#watch-list-table').children().remove();
        var url = Properties.WATCH_LIST_VIEW + '&flag=' + WatchList.type;
        jQuery.getJSON(url, function(data){
            if (data.DATA) {
                for (var i = 0; i < data.DATA.length; i++) {
                    var listid = data.DATA[i][0];
                    var listname = data.DATA[i][1];
                    var userid = data.DATA[i][2];
                    
                    WatchList.addListNode(listid, listname);
                }
            }
            WatchList.loadedlist = 'true';//load only once
            WatchList.hideMessage();
        });
    },
    addList: function(){
        if (LoginStatus.forceLogin()) {
            var listvalue = jQuery('#add-watch-list-text').val();
            if (listvalue != undefined && jQuery.trim(listvalue) != '') {
                WatchList.showMessage('saving...');
                var url = Properties.WATCH_LIST_ADD + listvalue + '&flag=' + WatchList.type;
                jQuery.getJSON(url, function(data){
                    if (data != null) {
                        if (data.statusCode != undefined && data.statusCode == '101') {
                            var listid = data.Id;
                            var listname = data.Name;
                            WatchList.addListNode(listid, listname);
                        }
                        else {
                            WatchList.showMessage('Error while saving');
                        }
                    }
                    else {
                        WatchList.showMessage('Error while saving');
                    }
                    WatchList.hideMessage();
                });
            }
        }
    },
    addListNode: function(listid, listname){
        if (listid != undefined && jQuery.trim(listid + '') != '' && listname != undefined && jQuery.trim(listname) != '') {
        
            var tr = jQuery('<tr></tr>');
            var html = '<td class="watch-list-entry"><a href="#" rel="#1" id="watch-list-entry-#1" class="watch-list-entry">#2</a>' +
            '</td><td class="watch-list-link"><a href="#" id="watch-list-entry-view-#1" rel="#1" class="watch-list-entry-view"></a> </td>' +
            '</td><td class="watch-list-link"><a href="#" id="watch-list-entry-edit-#1" rel="#1" class="watch-list-entry-edit"></a> </td>' +
            ' <td class="watch-list-link"><a href="#" rel="#1" id="watch-list-entry-delete-#1" title="Delete" class="watch-list-entry-delete"> </a></td>';
            html = html.replace(/#1/g, listid);
            html = html.replace(/#2/g, listname);
            
            jQuery('#watch-list-table').append(tr);
            jQuery(tr).html(html);
            jQuery('#add-watch-list-text').val('');
            
            jQuery('#watch-list-entry-view-' + listid).click(function(){
                var list = jQuery(this).attr('rel');
                var listnam = 'undefined';
                if (jQuery('#watch-list-entry-' + list).length) {
                    listnam = jQuery('#watch-list-entry-' + list).text();
                }
                WatchList.redirect(listid, listnam);
            });
            
            jQuery('#watch-list-entry-delete-' + listid).click(function(){
                var link = this;
                WatchList.deleteList(link);
            });
            
            jQuery('#watch-list-entry-edit-' + listid).click(function(){
                var list = jQuery(this).attr('rel');
                var listnam = 'undefined';
                if (jQuery('#watch-list-entry-' + list).length) {
                    listnam = jQuery('#watch-list-entry-' + list).text();
                }
                WatchList.editList(list, listnam);
            });
            
            jQuery('#watch-list-entry-' + listid).click(function(){
                var list = jQuery(this).attr('rel');
                var listnam = jQuery(this).text();
                WatchList.redirect(listid, listnam);
            });
        }
    },
    redirect: function(value, listnam){
        var encodeUrl = Properties.WATCH_LIST_SEARCH + jQuery.URLEncode(value) + '&name=' + jQuery.URLEncode(listnam);
        jQuery(location).attr('href', encodeUrl);
    },
    editList: function(listid, listname){
        WatchList.currentListId = listid;
        WatchList.displaySymbols(listid, listname);
        WatchList.getSymbols(listid);
    },
    deleteList: function(listnode){
        if (LoginStatus.forceLogin()) {
            var listid = jQuery(listnode).attr('rel');
            if (listid != undefined && jQuery.trim(listid) != '') {
                WatchList.showMessage('saving...');
                var url = Properties.WATCH_LIST_DELETE + listid + "&callback=?" + '&flag=' + WatchList.type;
                ;
                jQuery.getJSON(url, function(data){
                    if (data != null) {
                        if (data.statusCode != undefined && data.statusCode == '101') {
                            jQuery(listnode).parent().parent().remove();
                        }
                        else {
                            WatchList.showMessage('Error while saving');
                        }
                    }
                    else {
                        WatchList.showMessage('Error while saving');
                    }
                    WatchList.hideMessage();
                });
            }
        }
    },
    getSymbols: function(listid){
        var url = Properties.WATCH_LIST_SYMBOL_VIEW;
        url = url.replace('#1', listid);
        WatchList.showMessage('loading...');
        jQuery.getJSON(url, function(data){
            if (data.DATA) {
                for (var i = 0; i < data.DATA.length; i++) {
                    var symbolid = data.DATA[i][0];
                    //var listid = data.DATA[i][1];
                    var symbolname = data.DATA[i][2];
                    
                    WatchList.addSymbolNode(symbolid, symbolname);
                }
            }
            else {
                WatchList.showMessage('Error while getting symbols');
            }
            this.loadedlist = 'true';//load only once
            WatchList.hideMessage();
        });
    },
    addSymbol: function(listid){
        if (LoginStatus.forceLogin()) {
            var symbol = jQuery('#watch-list-edit-symbol-text').val();
            if (symbol != undefined && jQuery.trim(symbol) != '' && WatchList.currentListId != '') {
                WatchList.showMessage('saving...');
                var url = Properties.WATCH_LIST_SYMBOL_ADD;
                url = url.replace('#1', WatchList.currentListId);
                url = url.replace('#2', symbol);
                jQuery.getJSON(url, function(data){
                    if (data != null) {
                        if (data.statusCode != undefined && data.statusCode == '101') {
                            var symbolid = data.Id;
                            var symbolname = data.Symbol;
                            WatchList.addSymbolNode(symbolid, symbolname);
                        }
                        else {
                            WatchList.showMessage('Error while saving');
                        }
                    }
                    else {
                        WatchList.showMessage('Error while saving');
                    }
                    WatchList.hideMessage();
                });
            }
        }
    },
    addSymbolNode: function(symbolid, symbolname){
        if (symbolid != undefined && jQuery.trim(symbolid + '') != '' && symbolname != undefined && jQuery.trim(symbolname + '') != '') {
            var tr = jQuery('<tr></tr>');
            var html = '<td class="watch-list-entry"><a href="#" rel="#1" class="watch-list-entry">#2</a></td>' +
            ' <td class="watch-list-link"><a href="#" id="watch-list-entry-symbol-delete-#1" rel="#1" title="Delete" class="watch-list-entry-symbol-delete">  </a></td>';
            html = html.replace(/#1/g, symbolid);
            html = html.replace(/#2/g, symbolname);
            
            jQuery('#watch-list-edit-table').append(tr);
            jQuery(tr).html(html);
            
            jQuery('#watch-list-edit-symbol-text').val('');
            jQuery('#watch-list-entry-symbol-delete-' + symbolid).click(function(){
                var symbol = this;
                WatchList.deleteSymbol(symbol);
            });
        }
    },
    deleteSymbol: function(symbolnode){
        if (LoginStatus.forceLogin()) {
            var symbolid = jQuery(symbolnode).attr('rel');
            if (symbolid != undefined && jQuery.trim(symbolid) != '') {
                WatchList.showMessage('saving...');
                var url = Properties.WATCH_LIST_SYMBOL_DELETE;
                url = url.replace('#1', symbolid);
                jQuery.getJSON(url, function(data){
                    if (data != null) {
                        if (data.statusCode != undefined && data.statusCode == '101') {
                            jQuery(symbolnode).parent().parent().remove();
                        }
                        else {
                            WatchList.showMessage('Error while saving');
                        }
                    }
                    else {
                        WatchList.showMessage('Error while saving');
                    }
                    WatchList.hideMessage();
                });
            }
        }
    },
    showMessage: function(txt){
        jQuery('#watch-list-display-msg').text(txt);
        jQuery('#watch-list-display-msg').attr('style', 'display:block;');
    },
    hideMessage: function(){
        jQuery('#watch-list-display-msg').text('');
        jQuery('#watch-list-display-msg').attr('style', 'display:none;');
    },
    displaySymbols: function(listid, listname){
        jQuery('#watch-list-edit').attr('style', 'display: block');
        jQuery('#watch-list-close').attr('style', 'display: none');
        jQuery('#watch-list-back').attr('style', 'display: block');
        jQuery('#watch-list-view').attr('style', 'display: none');
        jQuery('#watch-list-display-text').attr('style', 'display: none');
        jQuery('#watch-list-header-title').text(listname);
		jQuery('.back_to_search_watch').show();
    },
    displayList: function(){
        jQuery('#watch-list-edit-table').children().remove();
        jQuery('#watch-list-edit').attr('style', 'display: none');
        jQuery('#watch-list-back').attr('style', 'display: none');
        jQuery('#watch-list-close').attr('style', 'display: block');
        jQuery('#watch-list-view').attr('style', 'display: block');
        jQuery('#watch-list-display-text').attr('style', 'display: block');
        
        
        if (jQuery('#watch-list-header-title').length) {
            if (WatchList.type == 'user') {
                jQuery('#watch-list-header-title').text('People List');
            }
            else {
                jQuery('#watch-list-header-title').text('Watch List');
            }
        }
    }
};

var Followers = {
    init: function(options){
    
        var options = options ||
        {};
        this.url = options.url + user;
        MessageTools.init();
        
        if (jQuery('#moreBtn').length) {
            jQuery('#moreBtn').click(function(){
                var last = jQuery('#streams li:last');
                if (last.length) {
                
                    var user = last.find('a.username');
                    if (user.length) {
                        var username = user.text().replace('@', '');
                        var moreurl = Followers.url + '&mode=1&lastusername=' + username;
                        
                        jQuery('#moreloading').attr('style', 'display:block');
                        jQuery.getJSON(moreurl, function(data){
                            jQuery('#moreloading').attr('style', 'display:none');
                            if (data.DATA) {
                                if (data.DATA != undefined) {
                                    for (var i = 0; i < data.DATA.length; i++) {
                                        var username = data.DATA[i][0];
                                        var biodata = data.DATA[i][1];
                                        var avatar = data.DATA[i][2];
                                        Followers.createMessage(username, biodata, avatar);
                                    }
                                }
                            }
                        });
                    }
                }
            });
        }
        
        jQuery.getJSON(this.url, function(data){
            if (data.DATA) {
                if (data.DATA != undefined) {
                    for (var i = 0; i < data.DATA.length; i++) {
                        var username = data.DATA[i][0];
                        var biodata = data.DATA[i][1];
                        var avatar = data.DATA[i][2];
                        Followers.createMessage(username, biodata, avatar);
                    }
                }
            }
        });
        
        
    },
    createMessage: function(username, biodata, avatar){
    
        var html = '<span class="avatar"><img src="#avatar" alt="Avatar"/></span>' +
        '<span class="content">' +
        '<a href="http://www.wetradetogether.com/user/user?user=#username" class="username" onclick="Search.userPage(\'#username\');return false;">@#username</a>' +
        '<span class="body">#body</span></span>';
        
        if (username != null && username != 'null') 
            html = html.replace(/#username/g, username);
        
        if (biodata != null && biodata != 'null') 
            html = html.replace(/#body/g, biodata);
        else {
            html = html.replace(/#body/g, '');
        }
        
        html = html.replace(/#avatar/g, avatar);
        
        
        var li = jQuery('<li></li>');
        li.html(html);
        jQuery('#streams').append(li);
        
        MessageTools.initMouseenter(li);
        MessageTools.initMouseleave(li);
    }
};

var Calendar = {
    init: function(){
        var self = this;
        this.renderFirst = true;
		jQuery("#main-menu_menu_menu_tradingrooms span").removeAttr("onclick");
        jQuery('#event-btn, #main-menu_menu_menu_tradingrooms span').click(self.showCalendar);
		
		jQuery(".calendar-tab a").click(function(){
			if(jQuery(this).attr("ref")!='add'&&jQuery(this).attr("ref")!='search'){
				return;
			}
			Calendar.switchClass(".calendar-tab a",this,"selected");
			if(jQuery(this).attr("ref")=='search'){
				jQuery("#calendar_widget, #calendar_adv_search, #calendar_attendee_details, #calendar-accept, #calendar_upphoto").hide();
				jQuery("#calendar_search").show();
				Calendar.makeSearchForm();
				SearchUser.type="edit";
				SearchUser.init();
			}
			if(jQuery(this).attr("ref")=='add'){
				
				jQuery("#calendarForm").clearForm();
				
				jQuery("#calendar_upphoto").hide();
				
				jQuery("#calendarForm input[name='twitter_me']").removeAttr("checked");
				jQuery("#calendarForm input[name='calendarOptionPrivacy']").removeAttr("checked");	
					
				jQuery("#calendarForm input[name='twitter_me']:first").attr("checked","checked");
				jQuery("#calendarForm input[name='calendarOptionPrivacy']:first").attr("checked","checked");
				
				if(jsLoginStatus=='203'){
					SearchGrid.showMessage("KO",CalendarLocalization.NO_LOGIN_FOR_ADD_MESSAGE);
					return false;
				}
				jQuery("#calendar_widget, #calendar_adv_search, #calendar_search, #calendar_attendee_details, #calendar-accept").hide();
				jQuery("#calendarForm").show();
				if (Calendar.renderFirst) {
					// Use default settings
					jQuery("#calendarStartTime, #calendarEndTime").timePicker({
						show24Hours: CalendarLocalization.TIME_24_HOURS,
						separator: ':'
					});
					Calendar.renderFirst = false;
				}
				SearchUser.type="create";
				SearchUser.init();
			}
			jQuery("#labels_calendar span").hide();
			jQuery(".label_text_for_"+jQuery(this).attr("ref")).show();
		});		
    },
	switchClass: function(element1, element2, newClass){
		jQuery(element1).removeClass(newClass);
		jQuery(element2).addClass(newClass);
	},
	makeSearchForm: function(){
		
		//Form search + Adv Form
		var htmlForm='';
		htmlForm+='<form action="javascript:;" style="position:relative" onsubmit="Calendar.normalSearchSubmit()">';
			htmlForm+='<div><div style="float:left;"><input style="width:270px; padding:5px; color:#999999; " onfocus="jQuery(this).css(\'color\',\'\').val(\'\');" type="text" value="'+CalendarLocalization.LABEL_BOX_BASIC_SEARCH+'" name="text"></div><div style="float:left; margin-left:20px; "><input type="submit" value="Search" class="button"></div><div style="clear:both"></div><input type="hidden" value="fulltext" name="type"><a href="javascript:;" style="font-size:14px; text-decoration:underline" onclick="jQuery(\'#calendar_adv_search\').fadeIn(500); jQuery(\'.label_text_for_search\').hide(); jQuery(\'.label_return_to_search\').show(); ">show more search options</a></div>';
			htmlForm+='<div class="cancel_and_return_event" style="display:none; position: absolute; top: 34px; right: 7px;"><a href="javascript:;" onclick="jQuery(\'.calendar-tab a:first\').click()">cancel and return</a></div>';
		htmlForm+='</form>';
		jQuery("#calendar_search_form").html(htmlForm);
		//Grid
		SearchGrid.appendTo="#calendar_search_grid";
		SearchGrid.urlTo="/event/room/";
		SearchGrid.makeGrid();
		
		jQuery("#calendar_adv_search").load("/event/adv_search", function(){
			//alert( jQuery("#calendar_adv_search input[name=date_'after']").attr("name") );
			jQuery("#calendar_adv_search input[name='date_after'], #calendar_adv_search input[name='date_before'], ").datepicker();
			//jQuery("#calendar_adv_search #date_after, #calendar_adv_search #date_before").datepicker();
		});
	},
	normalSearchSubmit: function(){
		var dataForm = jQuery("#calendar_search_form form").serialize();
		SearchGrid.urlTo="/event/room/?"+dataForm;
		SearchGrid.makeGrid();
		
		jQuery(".cancel_and_return_event").show();
		
	},
	sendAdvForm: function(){
		if(jQuery("#calendar_adv_form #text").val()=='' && jQuery("#select_search_events").val()=='1'){
			
			if(
				jQuery("#calendar_adv_form input[name='symbol']").val()=='' &&
				jQuery("#calendar_adv_form input[name='tags']").val()==''
										
			){
				SearchGrid.showMessage("KO", CalendarLocalization.NO_VALUE_ADV_FORMS);
				return;	
			}
		}
		
		if(jQuery("#select_search_events").val()=='2' && jQuery("#select_search_events_value").val()==''){
			SearchGrid.showMessage("KO", CalendarLocalization.NO_VALUE_ADV_FORMS);
			return;
		}
				
		jQuery("#calendar_adv_search").fadeOut(500);
		var data = jQuery("#calendar_adv_form").serialize();
		SearchGrid.urlTo='/event/room/?'+data;
		SearchGrid.makeGrid();
		
		jQuery(".cancel_and_return_event, .label_text_for_search").show();
		
		jQuery(".label_return_to_search").hide();
		
	},
	toggleInputText: function(val){
		var sInput = jQuery(".adv_form_events #exclude");
		if(val!=''){
			sInput.removeAttr("disabled");
		} else {
			sInput.attr("disabled","disabled");
		}
	},	
	toggleInput2: function(){
		var sInput = jQuery("#select_search_events_value");
		if(sInput.val()==CalendarLocalization.TITLE_INPUT_NO_TEXT){
			sInput.val("");
			sInput.css("color","");
		} else if(sInput.val()=='') {
			sInput.val(CalendarLocalization.TITLE_INPUT_NO_TEXT);
			sInput.css("color","#BBBBBB");
		}
	},
	toggleSelect: function(){
		
		var val = jQuery("#select_search_events option:selected").val();
		var sInput = jQuery("#select_search_events_value");
		
		if(val=='2'){
			sInput.removeAttr("disabled");
			sInput.val(CalendarLocalization.TITLE_INPUT_NO_TEXT);
			sInput.css("color","#BBBBBB");
		} else {
			sInput.attr("disabled","disabled");
			sInput.val("");
		}
	},	
    showCalendar: function(){
		SearchUser.type='create';
		SearchUser.caseSearchUser();	
		jQuery("#calendarForm").hide();
        if (jQuery('#calendar-dialog').length) {
			Applet.hidden=1;
			if (1==2) {
				LoginStatus.signIn();
			}
			else {
				
				/*var popup = jQuery('#calendar-dialog').html();
				jQuery('#calendar-dialog').remove();
				GlobalModal.appendHtml('<div id="calendar-dialog" style="display:block">'+popup+'</div>');
				GlobalModal.showWindow();*/
				DialogUtil.showPopup('#calendar-dialog');
				
				jQuery("#calendar_widget").hide();
				
				Calendar.renderFirst=true;
				
				jQuery("#calendarForm").clearForm();
				
				Calendar.switchClass(".calendar-tab a",".calendar-tab a:first","selected");
								
				jQuery("#calendar_search").show();		
				
				jQuery(".calendar-tab a:first").click();
	
				SearchGrid.clearFormEdit();
				
			}
			
			
			jQuery('#calendarAllDay').click(function(){
				if (jQuery(this).is(':checked')) {
					jQuery('#calendarStartTime, #calendarEndTime').css('display', 'none');
				}
				else {
	
					jQuery('#calendarStartTime, #calendarEndTime').css('display', 'inline');
				}
			});
			
			jQuery('#calendarFromDate, #calendarToDate').datepicker({minDate:0});
			
			jQuery('input[name=calendarOptionPrivacy]').change(function(){
				var curoption = jQuery('#calendarOptionPrivacy:checked').val();
				if ( curoption == "DEFAULT" ) {
					//jQuery('#optionForm').attr('disabled','disabled');
					//jQuery('.optionsmask').show();
				} else { 
					//jQuery('.optionsmask').hide();
					//jQuery('#optionForm').attr('disabled','');
				}
			});
			
		}
	}
};

var SearchUser = {
	init: function(){
		SearchUser.timeout='';
		SearchUser.urlJson='http://www.wetradetogether.com/stream/ajaxUserNameRequest.cfm?username=';
		SearchUser.clearAll();
		SearchUser.caseSearchUser();
		SearchUser.bindElement();
		SearchUser.appendSearchWindow();
	},
	caseSearchUser: function (){
		if(SearchUser.type=='create' || !SearchUser.type){
			SearchUser.idResult='search_user_results';
			SearchUser.toAppendInput=jQuery("#selected_user_calendar");
			SearchUser.toAppendView=jQuery("#selected_users_view");	
			SearchUser.element=jQuery("#user_to_search");
		}
		if(SearchUser.type=='edit'){
			SearchUser.idResult='search_user_results_edit';
			SearchUser.toAppendInput=jQuery("#selected_user_edit");
			SearchUser.toAppendView=jQuery("#selected_users_view_edit");	
			SearchUser.element=jQuery("#user_to_search_edit");
		}		
	},
	clearAll: function(){
		if(SearchUser.element){
			SearchUser.element.val("");
		}
		if(SearchUser.idResult){
			jQuery("#"+SearchUser.idResult).remove();
		}
		if(SearchUser.toAppendInput){
			SearchUser.toAppendInput.empty();
		}
		if(SearchUser.toAppendView){
			SearchUser.toAppendView.empty();
		}
	},
	bindElement: function(){
		SearchUser.element.attr("autocomplete","off");
		SearchUser.element.bind("keyup", function(){
			clearTimeout(SearchUser.timeout);
			SearchUser.timeout=setTimeout(function(){
				SearchUser.goSearch();
			},700);					 
		});
	},
	goSearch: function(){
		jQuery('#'+SearchUser.idResult).show();
		var val = SearchUser.element.val();
		var toAppend = jQuery('#'+SearchUser.idResult+' .container');
		toAppend.css("overflow-y","auto");
		if(val.length>2){
			toAppend.show();
			toAppend.html('<center><img align="absmiddle" src="/trade-project/images/loading2.gif"></center>');
			jQuery.getJSON(SearchUser.urlJson+val+'&callback=?', function(dataJSON){
				if(dataJSON){
					toAppend.text("");
					jQuery.each(dataJSON.DATA, function(i, val){
						toAppend.append('<a id="suggest_user_'+val[0]+'" href="javascript:;" style="display:block; font-size:11px;float:left; height:70px; width:90px; margin:0px 5px" onclick="SearchUser.selectUser(\''+val[0]+'\', \''+val[1]+'\', \''+val[2]+'\')"><center><img style="border:none;width:48px; height:48px" src="'+val[2]+'"><br>'+val[1]+'</center></a>');
					});
				}
				toAppend.append('<div style="clear:both"></div>');
				jQuery(".close_search_user").remove();
				toAppend.after('<a class="close_search_user button" style="color: white; padding:0 5px; position: absolute; z-index: 1000000; display: block; right: 20px; bottom: -20px;" href="javascript:;" onclick="jQuery(\'#'+SearchUser.idResult+' .container\').hide(200); jQuery(this).hide();">Close</a>');				
			});
		} else {
			toAppend.hide();
		}
	},
	appendSearchWindow: function(){
		
		SearchUser.element.parent().append('<div style="position:relative; display:none;" id="'+SearchUser.idResult+'"><div class="container" style="position:absolute; width:93.4%; top:-9px; left:0px; z-index:999999; border:1px solid #E9E9E9; padding:10px;background:white; display:none; line-height:27px; height:199px"></div></div>');
		
		var thisElement = jQuery(SearchUser.element.parent().find(".container"));
		var timeOutElement;
		
		thisElement.bind("mouseenter", function(){
			clearTimeout(timeOutElement);
			thisElement.fadeIn(500);	
			jQuery(".close_search_user").fadeIn(500);		
		});
		
		thisElement.bind("mouseleave", function(){
			timeOutElement = setTimeout(function(){
				thisElement.fadeOut(500);
				jQuery(".close_search_user").fadeOut(500);
				setTimeout(function(){
					SearchUser.element.val("");
				},500);
			},1000);		
		});		
		
	},
	selectUser: function(id, user, urlImg){
		if(!jQuery('.selected_user_view_'+id).length){
			var messageAdded = CalendarLocalization.ADD_USER_SUGGEST_MESSAGE.replace("[USER]",user);
			jQuery("#suggest_user_"+id).fadeOut(250);
			SearchGrid.showMessage("OK",messageAdded);
		} else {
			var messageAdded = CalendarLocalization.ADD_USER_SUGGEST_MESSAGE_KO.replace("[USER]",user);			
			SearchGrid.showMessage("KO",messageAdded);
			return;
		}
				
		SearchUser.toAppendView.find(".container").css("background","#FFFFCC");
		SearchUser.toAppendInput.find(".selected_user_"+id).remove();
		SearchUser.toAppendInput.append('<input type="hidden" class="selected_user_'+id+'" name="selected_users" class="selected_users" value="'+id+'">');
		SearchUser.toAppendView.find('.selected_user_view_'+id).remove();
		SearchUser.toAppendView.append('<div class="selected_user_view_'+id+'"><div style="display:block; font-size:11px;float:left; height:70px; width:97px; margin:0px 5px"><center><img style="border:none;width:48px; height:48px" src="'+urlImg+'"><br>'+user+'&nbsp;<img alt="remove" style="cursor:pointer; vertical-align:top;" src="/images/remove.gif" onclick="SearchUser.removeUser('+id+')"></center></div></div>');
		//jQuery('#'+SearchUser.idResult+' .container').slideUp(100);
		SearchGrid.controlTypedInput();
		
	},
	removeUser: function(id){
		SearchUser.toAppendInput.find(".selected_user_"+id).remove();
		SearchUser.toAppendView.find('.selected_user_view_'+id).remove();
		jQuery('#'+SearchUser.idResult+' .container').slideUp(100);
		SearchGrid.controlTypedInput();
	}
}

var Widget = {
	init: function(){
		if(!Widget.ID){
			Widget.ID = Math.round(Math.random()*1200);
		}
		Widget.src='/widget/?id='+Widget.ID;
		Widget.controlOwner();
		Widget.bindCheckbox();
		Widget.generateIframe();
	},
	controlOwner: function(){
		jQuery.getJSON("/event/act/?type=widget&id="+Widget.ID+'&callback=?', function(dataJSON){
			if(dataJSON.IS_OWNERW){
				
			} else {
				
			}
		});
	},
	bindCheckbox: function(){
		jQuery("#calendar_widget input").bind("change", function(){
			Widget.generateIframe();
		});
	},
	generateIframe: function(){
		var widgetOptions = jQuery("#calendar_widget form").serialize();
		var iframe ='';
		iframe+='<iframe src="http://www.wetradetogether.com/widget/?id='+Widget.ID+'&'+widgetOptions+'" style="width: 100%; height: 390px; border: medium none;"></iframe>';
		jQuery("#calendar_widget .widget_content").text("");
		jQuery("#calendar_widget .widget_content").html(iframe);
		jQuery("#calendar_widget textarea").text(iframe);
	}
}

WatchList.details ={
	
	showWatchList: function(flag, value){
		
		if(jsLoginStatus =='203'){
			
			LoginStatus.signIn();
			
			return;
			
			
		}
		
		var urlTo = '/list/addValue/?flag='+flag+'&value='+value;
		jQuery("<div></div>").load(urlTo, function(html){
			GlobalModal.init(300,150);
			GlobalModal.appendHtml(html);
			GlobalModal.showWindow();
			WatchList.details.bindForm();
		});
	},
	bindForm: function(){
		
		var form = jQuery(".j_modal_charts form");
		var formAction = form.attr("action")+'?callback=?';
		form.attr("action","javascript:;");
		
		form.bind("submit", function(){
			var data = form.serialize();
			jQuery.ajax({
				url: formAction,
				type: 'POST',
				data: data,
				dataType:'jsonp',
				success: function(dataJSON){
					SearchGrid.showMessageHome(dataJSON.status,dataJSON.message);
					GlobalModal.hideWindow();
				}
			});
		});
	}
	
};

jQuery(document).ready(function(){
	PeopleList.init();
});
