var decorated_selects = [];


var scroll_to, scrolled;
var scrollBox;
var divs;
var current_div = 0;
var console;

/**
  * Gives facade to all combolists with class .decorated
  **/
function decorate_selects()
{
        jQuery('select').
        filter(function()
               {return this.className.match(/decorated/) || this.parentNode.className.match(/decorated-select-parent/)}).
        map(function() {decorate_select(this)});
}

/**
  * decorates a select
  * params: a select object
  **/
function decorate_select(combo, fixed_width)
{
    var combo_span = document.createElement('span');
    combo_span.innerHTML = combo.options[combo.selectedIndex].text || 'Select a value';
    var combo_list = document.createElement('ul');
    combo_list.className = 'combo_list';
    var combo_div = document.createElement('div');
     combo_div.className = 'comboo';

    combo_div.appendChild(combo_span);
    combo_div.appendChild(combo_list);

    // callback functions for 'combo->onmousedown' event of various combos (select-boxes)
    var languagecombo_callback_function = function(combo) {
            loc = combo.options[combo.selectedIndex].value;
            if(loc)
                window.location=loc;
    };
    var id_category_callback_function = function(combo) {
        var val = combo.options[combo.selectedIndex].value;
        var objects = jQuery('#username_text,#username_input,#support_error');

        if(val == 'DATA FILE SUPPORT' || val == 'ONLINE SUPPORT' || val == 'PASSPORT-CHECK SUPPORT') {
            objects.removeClass('defaulthidden');
        } else {
            objects.addClass('defaulthidden');
        }
    };
    var homecategorycombo_callback_function = function(combo) {
        var category  = combo.options[combo.selectedIndex].value;
        var url = '/json/latestarticles/'+category;
        if (category != '')
            url += '/';
        jQuery.getJSON(url, handle_article_categories_response);
    };
    var bncategorycombo_callback_function = function(combo) {
        stories = null;
    };
    var bnGenre_callback_function = function(combo) {
        stories = null;
    };
    var categorycombo_yearcombo_callback_function = function(combo) {
        window.location=combo.options[combo.selectedIndex].value;
    };
    var categorycombo_callback_function = categorycombo_yearcombo_callback_function;
    var yearcombo_callback_function = categorycombo_yearcombo_callback_function;
    // end of callback_functions definition

    combo.parentNode.appendChild(combo_div);

    combo.style.visibility = 'hidden';
    combo_list.style.display = 'none';

	if (fixed_width)
	{
		var w1 = fixed_width;
		var w2 = fixed_width;
	}
	else
	{
		var w1 = jQuery(combo).width()+5;
		var w2 = (combo.offsetWidth);
	}

    combo_list.style.width = w1+"px" ;

    combo_span.style.width = w2+"px";
    combo_span.onmousedown = combo_button_on_mouse_down;

    combo_list.style.visibility = 'hidden';
    combo_list.style.display = 'block';
    var combo_list_cw = combo_list.clientWidth;


    //the line below is to allow clicking on the scrollbar
    jQuery(combo_list).mousedown(function() {return false;});

    for (var i = 0; i < combo.options.length; i++) {
        var item = document.createElement('li');
        item.id = combo.id + 'id_' + i;
        item.innerHTML = combo.options[i].text
        jQuery(item).mouseover(function () {this.className += " hover"}).
                        mouseout(function () {this.className = "" }).
                        mousedown(function () {
                            var j = this.id.match(/id_(\d+)$/)[1];

                            combo.selectedIndex = j;
                            combo_span.innerHTML = combo.options[j].text;
                            var function_name = combo.id+'_callback_function';

                            if(eval('typeof '+function_name) != 'undefined') {
                                eval(function_name+'(combo)');
                            }
                           hide_combo_lists();
                            return false;
                        }).
                        css({padding:'0', margin:'0'}).
                        width((combo_list_cw - 2)  + 'px');
        combo_list.appendChild(item);
    }
    jQuery(combo_list).css({display:'none',visibility:'visible'});

    //after all the calculations are done, hide the original select-box completely
     combo.style.display='none';
}

function handle_article_categories_response(data)
{
    var new_html = '';

    if (! jQuery('boxdaac'))
        return;

    jQuery('boxdaac').hide().css('cursor', 'auto');

    for (var i = 0; i < data.length && i < 5; i++) {
        var elem = data[i];

        md = '<dt>' + elem.short_header + '</dt>';
        md += '<dd style="display: hidden">' +
            '<p>' + elem.date + ' - ' + elem.short_summary  +
            '<a href="' + elem.link +'">' + '&nbsp;...more'  + '</a>' +
            '</p></dd>';
        new_html += md;
    }

    jQuery("#boxdaac dl").html(new_html);
    jQuery('#boxdaac dd').hide();
    jQuery('#boxdaac dd:first').show();
    jQuery('#boxdaac dt:first').addClass('selected');
    jQuery('#boxdaac dl').accordion('destroy');
    jQuery("#boxdaac dl").accordion({ header: 'dt', fillSpace: true, active: '.selected' });
    jQuery("#boxdaac").show();
}

function combo_button_on_mouse_down(e)
{
//    console.value += "combo.mousedown\n";
    if (!e) e = window.event;

    var combo_div = this.parentNode;
    var combo_list = combo_div.getElementsByTagName('ul')[0];
    var show = true;
    if (combo_list.style.display != 'none')
        show = false;
    hide_combo_lists(e);

    if (show)
        combo_list.style.display = 'block';

    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();

    //to hide the combo-boxes when we click outside of them
    jQuery(document).mousedown(hide_combo_lists);

    return false;
}

function hide_combo_lists(e) {
//    console.value += "document.onmousedown\n";
    var list = document.getElementsByTagName('ul');
    for (var i = 0; i < list.length; i++) {
        if (jQuery(list[i]).hasClass('combo_list')) {
            list[i].style.display = 'none';
        }
	}

    //we unregister ourself (if we were registered at all)
    jQuery(document).unbind('mousedown',hide_combo_lists);
    return true;
}


function handle_senditem_response(data)
{
    data = utils.evalJSON(data);

    var fields = ['from_name', 'to_name', 'from_address', 'to_address', 'slug'];
    if (! data.error)
    {
        document.getElementById("popup_senditem").style.display = 'none';
        for(i = 0; i < fields.length; i++)
        {
            if(fields[i] != 'slug')
            {
                document.getElementById('id_'+fields[i]).value='';
            }
        }
        /* Clean up previous captcha errors and value */
        captcha.cleanup("#id_captcha");
    }
    else
    {
        /* check for field errors */
        for(i = 0; i < fields.length; i++)
        {
            var key = fields[i];
            var field = document.getElementById('id_'+key);
            if (! field)
                continue;
            if (data.error[key]) {
                $(field).val(data.error[key]);
                $(field).addClass('error-data');
            }
            else {
                $(field).removeClass('error-data');
            }
        }
        /* check for captcha errors */
        if (data.error['captcha']) {
            captcha.displayError('#id_captcha', data.error['captcha']);
        } else {
            captcha.cleanup("#id_captcha");
        }
        /* Redisplay the new captcha */
        captcha.redisplayCaptcha("#captcha-img", "/captcha-image/friend/");

        /* check for general errors */
        if (data.error['general']) {
            alert(data.error['general'].join('\n'));
        }
    }
}

function send_item() {
    var url = '/json/friendmail/';
    var data = {};
    $.each($('#popup-form').serializeArray(), function() {
        if ($('#id_' + this.name).hasClass('error-data')) {
            data[this.name] = '';
        } else {
            data[this.name] = this.value;
        }
    });
    jQuery.post(url, data, handle_senditem_response);
}

function on_load()
{
   try {
       jQuery("dd:first").show();
       jQuery(".accordion dt").hover(function () { jQuery(this).addClass("hover") }, function () { jQuery(this).removeClass("hover") } );
       jQuery("#boxdaac dl").accordion( { header: "dt" , fillSpace: true }  );
   } catch(e) {
   }
   //debugger;
   //   genres('bncategorycombo');

   try {
       genres('#bnGenre , #bncategorycombo');
   } catch(e) {
   }

   decorate_selects();
}

function on_home_load()
{
    register_vtab();
    start_switcher('testimonial-block','testimonial-item', 8000, 8000);
}

var defaultGenre = 'a20061207143423266665203';
var newGenre = {
 "Arms Dealing":"a2006120714263405312006",
 "Banking Regulatory":"a2006120714271703836481",
 "Bankruptcies":"a200612071427550298443",
 "Bribery":"a2006120714282206111719",
 "Corruption":"a2006120714292508576319",
 "Fraud Report":"a20061207143019066383",
 "Front Page Crime":"a2006120714311507638971",
 "Homeland Security":"a2006120714320708203089",
 "Human Trafficking":"a2006120714324105445673",
 "International Terrorism":"a2006120714334507629053",
 "Money Laundering":"a20061207143423266665203",
 "Narcotics":"a2006120715122404341852",
 "Organized Crime":"a2006120715150506648828",
 "Political Risk":"a20061207151629697748102",
 "Smuggling":"a2006120715182707464105"
};

var months = [' January ', ' February ', ' March ', ' April ', ' May ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December ' ];

var stories;

function switcher(entries, initial_delay, timeout)
{
    worker = function(entries, index, timeout)
	{
	    var i = index;
	    var k = index + 1;

	    var l = entries.length;
	    i = i % l;
	    k = k % l;

	    var effect_duration = 2000;

	    jQuery(entries[i]).fadeOut(effect_duration);
	    jQuery(entries[k]).fadeIn(effect_duration);

	    var fun = arguments.callee;
	    setTimeout(function() {fun(entries, index + 1, timeout)}, timeout);
	}

    setTimeout(function() {worker(entries, 0, timeout)},initial_delay);
}

function start_switcher(parent_id, class_name, initial_delay, timeout)
{
    var parent_node = jQuery('#'+parent_id);
    if (parent_node)
    {
	var entries = jQuery('#'+parent_id + ' div.'+class_name);
 	if (entries.length > 0)
	    {
		jQuery(entries[0]).show();
		switcher(entries, initial_delay, timeout);
	    }
    }

}

// **************** VTAB FUNCTIONS ****** //


var currently_open_vtab = null;

function get_vtab_content(menu_item)
{
    return jQuery('#'+menu_item.id.replace('-menu-','-'));
}

function show_vtab()
{
    if (this != currently_open_vtab)
    {
        jQuery(this).toggleClass('on').toggleClass('off')
        jQuery(currently_open_vtab).toggleClass('on').toggleClass('off')

        get_vtab_content(currently_open_vtab).addClass('dontdisplay');
        get_vtab_content(this).removeClass('dontdisplay');

        currently_open_vtab = this;
    }
}

function register_vtab()
{
    currently_open_vtab = jQuery('#vertical-tabs-nav > div.on')[0];
    jQuery('#vertical-tabs-nav > div.tab').mouseover(show_vtab);
}

// ****************  VTAB FUNCTIONS END ** //

var tickers;
var stop_ticker = 0;

function start_ticker()
{
    tickers = jQuery('div.tacker');

    tickers.hover(function(e) { stop_ticker = 1 },
                  function(e) { stop_ticker = 0 });
    tick_ers();
}

function tick_ers()
{
    if (! stop_ticker ) {
        tickers[0].scrollLeft += 1 ;

        if (tickers[0].scrollLeft >= tickers[0].scrollWidth - tickers[0].offsetWidth)
            tickers[0].scrollLeft = 0;
    }

    setTimeout('tick_ers()', 30);
}

//temporary logging function. later we will switch to something better
function log(text)
{
    text = text + ''; //i force it to string
    if (typeof(window) != "undefined" && window.console && window.console.log)
    {
        // Workaround for some Safari-crashing-bug (FIXME: check which one exactly)
        text = text.replace(/%/g, '\uFF05');
        window.console.log(text);
    }
}

jQuery(document).ready(function() {
    if (!utils.cookies_enabled()) {
        jQuery('#error-message').show();
    }
});
