
var loading;
var tabQuery = '#tab_init > ul';

var warDlg  = null;
var errDlg  = null;
var ok_css = {
    border: '1px solid #49c24f',
    background: '#bcffbf'
};
var error_css = {
    border: '1px solid #c24949',
    background: '#ffbcbc'
};
var default_css = {
    border: '',
    background: '#FFFFFF'
};

var tlTip = {
    track: true,
    delay: 200,
    showURL: false,
    opacity: 0.5,
    fixPNG: true,
    showBody: " - ",
    extraClass: "pretty fancy"
};
var $tabs;
var loginFormIsVisible = 1;

var tooltips = ['Stop loss price(title) - Stop loss price is a ....(text)','',
'\"Bid\" is the highest buying price. <br>\"Ask\" is the lowest selling price.',
'Choose: - <br>"Limit" to set the maximum price you are willing to pay for shares you are purchasing, or the minimum price you are willing to accept for shares you are selling. The order will remain open until/unless .'];

function setCompaniesTitles(txt)
{
    setTitles2(txt)
}

function setTitles2(txt)
{
    $('#content_small > div.box > h3').html(txt);
    title(txt);
}
function setTitles(txt)
{

    $('#content_small > div.box > h3').html(txt);
    title(txt);
}

function init()
{
    loading = '<div style="padding:2px"><img src="'+BASE_URL+'/design/images/loading.gif"></div>';
    loadingWithHeight = '<div style="padding:2px;height:300px"><img src="'+BASE_URL+'/design/images/loading.gif"></div>';
    //	autocomplete();
    // add informer
    swfobject.embedSWF(BASE_URL+"/flash/informer/build/pex_informer.swf", 'line', 775, 30, "9.0.0",BASE_URL+"/flash/expressInstall.swf" ,{
        'data_uri':BASE_URL+'/default/ajax/informer/'
    },{
        allowScriptAccess:'sameDomain'
    },{
        wmode:'opaque'
    },false);

    //warDlg = $('#warning');
    errDlg = $('#error');
    //$(warDlg).jqm();
    $(errDlg).jqm();
    $('.tooltip').tooltip(tlTip);
    
    $('#fish_menu').superfish().find('ul').bgIframe();
    autocomplete("input#getQuotes2");
    $(this).find("a[@rel='history']").click(history);
}


function flash_content(url)
{
    document.location = BASE_URL+'/'+url;
}

function leftColUpdate()
{
    $('#left_col').html(loading).load(BASE_URL+'/default/ajax/leftcol', { 
        'ifModified':true
    }, function(){
        $(this).find("[@rel='history']").click(history);
    });
}

function refreshTopNavigation()
{
    $('#top_nav').html(loading).load(BASE_URL+'/default/ajax/topNavigation',{},
        function (){
            $('#fish_menu').superfish().find('ul').bgIframe();
            autocomplete("input#getQuotes2");
            $(this).find("a[@rel='history']").click(history);
        }
        );
}

function search(name)
{
    var search_url = BASE_URL+'/search/companies/query/';
    name = name.value;
    document.location = search_url+name;
    return false;
}

function _a() // callback function (for login)
{
}

function contentSmall(url)
{
    $(idContentSmall).html(loading).load(BASE_URL+url)
}

function watchList()
{
    $(idContent).html(loading).load(BASE_URL+'/user/watchList')
}

function activeStock()
{
    $(idContent).html(loading).load(BASE_URL+'/ajax/activeStockFull')
}

function loc(url)
{
    document.location.replace(url);
}

function roundPriceForInput(price)
{
    var tmp = Math.round(price*100);
    price = tmp/100;
    return price;
}

function roundPrice(price)
{
    var tmp = price*100%100;
    if(tmp!=0) {
        if((tmp%10)==0) {
            price +='0';
        }
    } else  price+='.00';
    return price;
}

function checkAccess()
{
    //if(checkIsLoggedIn())return true;
    //else
    showError("You must be logged in to access this functionality.");
    return false;
}

function showMessage(txt)
{
    warDlg = $('#warning');
    jQuery('div.alert_body > span',warDlg).html(txt)
    $(warDlg).jqm().jqmShow()
}
function showError(txt)
{
    jQuery('div.alert_body > span',errDlg).html(txt)
    errDlg.jqmShow()
}

$().ajaxError(function(ev,xhr,o,err) {
    error(err);
});

function error(err)
{
    if (window.console && window.console.error) console.error(err);
}

function log(t)
{
    if (window.console && window.console.log)console.log(t);
}

function addChart(id, width, height, url)
{
    swfobject.embedSWF(BASE_URL+"/flash/open-flash-chart.swf", id, width, height, "9.0.0",
        BASE_URL+"/flash/expressInstall.swf" ,
        { 
            data: BASE_URL+url
        },

        {
            wmode:"transparent",
            allowScriptAccess:'sameDomain'
        },
        false
        );
}

function autocomplete(quotesQuery)
{
    var data = {
        minChars: 0,
        delay: 200,
        mouseDownOnSelect : true,
        scrollHeight: 220,
        formatItem: function (row) {
            /*
            if(row[1]=="USERS"){
                return row[0];
            }*/
            return "<strong>" + row[0] + "<\/strong>";
        },
        formatResult: function (row) {
            return row[0].replace(/(<.+?>)/gi, '');
        }
    };
    $(quotesQuery).autocomplete(BASE_URL+'/ajax/suggest/', data);
    $(quotesQuery).result(function(event, data, formatted) {
        if (data) {
            search(this);
        }
    });
}

function changeRangeMarket(range, parent)
{
    swfobject.getObjectById('marketChart').reload(BASE_URL+'/chart/marketHistory2/t/'+range);
    refresh_range_menu(range, parent, 'changeRangeMarket');
    return false;
}

function changeRangeDetailedMarket(range, parent)
{
    swfobject.getObjectById('detailedMarketChart').reload(BASE_URL+'/chart/marketDetailedHistory2/t/'+range);
    refresh_range_menu(range, parent, 'changeRangeDetailedMarket');
    return false;
}

function changeRangeGraphOfPerfomance(range, parent, id)
{
    swfobject.getObjectById('graphOfPerfomance').reload(BASE_URL+'/chart/graphOfPerfomance2/t/'+range+'/id/'+id);
    refresh_range_menu(range, parent, 'changeRangeGraphOfPerfomance', id);
    return false;
}
function changeRangeCompany(range, parent, id)
{
    swfobject.getObjectById('companyChart').reload(BASE_URL+'/chart/company2/id/'+id+'/t/'+range);
    refresh_range_menu(range, parent, 'changeRangeCompany', id);
    return false;
}

function changeRangeDetailedCompany(range, parent, id)
{
    swfobject.getObjectById('detailedCompanyChart').reload(BASE_URL+'/chart/companyDetailed2/id/'+id+'/t/'+range);
    refresh_range_menu(range, parent, 'changeRangeDetailedCompany', id);
    return false;
}

var ranges = ['1d','5d','3m','6m', '1y', '2y', '5y'];
function refresh_range_menu(range, p, nameFunc, id)
{
    var html = [];
    for (var i in ranges) {
        if(range==ranges[i]) {
            html.push('<b>'+ranges[i]+'</b>&nbsp;');
        } else {
            html.push('<a onclick="return '+nameFunc+'(\''+ranges[i]+'\', this');
            if(id){
                html.push(','+id);
            }
            html.push(');return false;" href="javascript:;">'+ranges[i]+'</a>&nbsp;');
        }
    }
    $(p.parentNode).html(html.join(''));
}

function lgn(form)
{
    $(form).ajaxSubmit({
        dataType:  'json',
        success: function  (j) {
            if(j.error) {
                var url = "" + document.location;
                var hashIndex = url.indexOf('auth');
                if(hashIndex < 0){
                    locate('auth')
                    content('/auth/');
                    $('#login').hide();
                    _a = function (){
                        $('#login').show(); _a = function(){}
                    };
                }
                showError(j.error)
            }
            if(typeof j.url != 'undefined'){
                document.location = j.url;
            }
            if( typeof j.ok != 'undefined'){
                var url = "" + document.location;
                var hashIndex = url.indexOf('auth');
                if(hashIndex > 0){
                    locate('');
                }
                refreshPage();
            }
            return false;
        }
    });
    return false;
}




function homepage()
{
    content('/index/summary/ajax/1');
    locate('');
}

function titleForBox(txt)
{
    $('#content_big > div.box > h3').html(txt);
    title(txt);
}


function updateMessageBoardBox(url)
{
    $('#messagesBoardBox').load(BASE_URL+'/messages/leftbox/');
}

function parseAnswer(json)
{
    if(json.error) {
        showError(json.error)
    }
    if(json.url) {
    }
    if(json.ok && json.message){
        showMessage(json.message)
    }
}



