/************************************************************************
 * New JS
 ************************************************************************/




$(function() {

    // This is used to truncate the text returned by our feedburner-based DAP widgets and callouts
    $('.feedburnerFeedBlock li div').truncate({max_length: 450});

    // Why does this execute on every page?
    toggle_slide(3);


    // Open all external links in a new window
    (function() {
        var links = $('a');
        for (var i = links.length; i != 0; i--) {
            var a = links[i-1];
            if (!a.href) continue;
            if (a.href.indexOf('http') != -1 &&
                a.href.indexOf('localhost') == -1 &&
                a.href.indexOf(window.location.hostname) == -1 &&
                a.href.indexOf('.cfr.org') == -1 &&
                a.href.indexOf('.foreignaffairs.com') == -1 &&
				a.href.indexOf('feedproxy') == -1) {
                a.target = '_blank';
            }
        }
    })();

    // Left navigation
    $('#lnav li.lnava,li.lnavb,li.lnavc').hover(function() {
        $(this).addClass('lnavover');
    },function() {
        $(this).removeClass('lnavover');
    }).click(function() {
		if (!($(this).hasClass('searchoption'))) {
	        var url = $(this).find('a').attr('href');
    	    if (url) window.location.href = url;
		}
    });

    $('#lnav li.lnavmore').click(function(e) {
        e.stopPropagation();
	var div = $(this).prevAll('.lnavhidden').first();
        if (div) {
            if (div.is(':visible')) {
                div.slideUp();
                $(this).html('Show more...');
            } else {
                div.slideDown();
                $(this).html('Show less...');
            }
        }
    })

	// Search page filtering navigation functionality

	$('.lnav-for-search .lnavoption').each(function() {
		$(this)
			.addClass('search-collapsed searchoption')
			.children('ul:first').hide();
	});

	$('.lnav-for-search .search-collapsed').click(function(e) {
		e.preventDefault();
		if($(this).hasClass('search-collapsed')) {
			$(this)
				.removeClass('search-collapsed')
				.children('ul:first').show();
		} else {
			$(this)
	            .addClass('search-collapsed')
    	        .children('ul:first').hide();
		}
	});

    // Search box
    var search_default = 'Keyword search';
    $('#search #go').click(function() {
        var q = $('#search #q');
        if (q.val() == search_default) return false;
        omniture_click('search','top_nav');
        return true;
    });
    $('#search #q').focus(function() {
        if ($(this).val() == search_default) $(this).val('');
    }).val(search_default);

});



/************************************************************************
 * Old JS
 ************************************************************************/

function omniture_click(name,section,event) {
    var page = s.prop1; // Page title, set by Omniture javascript in each page

    
    // Link name
    name = name.toLowerCase().replace(/\s+/g,' ').replace(/[^\w\d]/g,'_');

    // Page section
    if (!section) section = 'none';
    section = section.toLowerCase().replace(/\s+/g,' ').replace(/[^\w\d]/g,'_');
    if (event) {
        if (!s.linkTrackEvents) {
            s.linkTrackEvents = '';
        } else {
            s.linkTrackEvents += ',';
        }
        if (!s.events) {
            s.events = '';
        } else {
            s.events += ',';
        }

        s.linkTrackEvents += 'event'+event;
        s.events += 'event'+event;
    }

    s.linkTrackVars='prop20,prop21,prop22,prop23,prop24,evar20,evar21,evar22,evar23,evar24';
    s.linkTrackEvents='event1';
    s.prop20=s.evar20=name;
    s.prop21=s.evar21=section;
    s.prop22=s.evar22=(section + '|' + name);
    s.prop23=s.evar23=(page +'|' + section);
    s.prop24=s.evar24=(page +'|' + section + '|' + name);
    s.tl(this,'o',name);
//alert('Omniture click on '+page+'|'+section+'|'+name + ' with ' + (event? 'event '+event:' no event'));
}

function omniture_track_child_links(elem,section,prefix) {
    if (!prefix) prefix = '' 
    elem.find('a').each(function() {
        var link = $(this);	
        // $('body').append(link.text()+':'+section+"<br />");
        var name = link.text();
        if (name) link.click(function() {
            omniture_click(prefix+name,section);
        })
    })

}

$(document).ready(function() {

	// TK: Functionality for ajax-based newsletter subscriptions across the site

	if ($('form.ajaxsignup').length !=0) {
		$('.ajaxcheck').hide();
		$('form.ajaxsignup').submit(function(e) {
			e.preventDefault();
			var ajaxp = $('p:first',this);
			var emailfield = $("input[name='email']",this);
			if ($('p.ajaxstatus',this).length == 0) {
				ajaxp.after("<p class='ajaxstatus'></p>");
			}
			var ajaxstatus = $('p.ajaxstatus',this);
			ajaxstatus.html("<span><img src='/i/ajaxloader.gif' width='12' height='12' /> Subscribing to newsletter... please wait a moment.</span>");
			$.post('/about/newsletters/onthefly.php', $(this).serialize(), function(data) {
				if (data.message) {
					if (!data.success) {
						ajaxstatus.html("<span style='color:red;'>" + data.message + "</span>");
					} else {
						ajaxstatus.html("<span style='color:green;'>" + data.message + "</span>");
						emailfield.val("");
					}
				} else {
					ajaxstatus.text("There has been an error. Please reload the page and try again.");
				}
			}, "json");
		});
	}

	$('.refine-widget select').chosen();

    // Easily add omniture tracking based on class names of links - saves writing Javascript and avoids JS errors
    // Add to any link: class="omniture omniture_section:top_nav omniture_name:home" and click tracking will be
    // automatically enabled
    $('a.omniture').each(function() {
        var link = $(this);
        var classNames = link.attr('class').split(/\s+/);
        var classVars = {};
        $.each(classNames,function(i,n) {
            var elem = n.split(/:/)
            classVars[elem[0]] = elem[1];
        });
        var name = classVars['omniture_name'];
        var section = classVars['omniture_section'];
        if (name && section) {
            link.click(function(e) {
                omniture_click(name,section);
                e.stopPropagation();
                return true;
            })
        }
    })


    // Adds omniture tracking to all the left nav links on the page
    $('#lnav').find('a').each(function() {
        var link = $(this);
        var name = link.text();
        var prefix = '';
        var section = 'left_nav';
        if (name) {
            link.click(function(e) {
                omniture_click(prefix+name,section);
                e.stopPropagation();
            });
            link.parent().click(function() {
                omniture_click(prefix+name,section);
            });
        }
    });
    

    // Adds omniture tracking to the bottom index
    omniture_track_child_links($('.site-index-footer'),'homepage','index_footer_');
    omniture_track_child_links($('.site-index'),'homepage','index_top_');

    if ($('a.corp_login')) {
        if ($('body').hasClass('is_not_corporate')) {
            var initialtext = $('a.corp_login').text();
            initialtext = initialtext + ' (Login is required to view this material)';
            $('a.corp_login').text(initialtext);
        }
    }

});

// New header, footer and homepage



function toggle_slide(item)
{
    $(".desc").each(function(jQuery){
        if ($(this).css("display") == "block")
            $(this).toggle(300);
    });
	
    $(".item").each(function(jQuery){
        $(this).css("background-image", "url('/i/resources-inactive.gif')");
        $(".item a").css("color", "#4a542c");
    });
	
    if (jQuery(".desc."+item).css("display") == "none")
    {
        $(".item."+item).css("background-image", "url('/i/resources-active.gif')");
        $(".item."+item+" a").css("color", "#ffffff");
        $(".desc."+item+" a").css("color", "#4a542c");
    }
    else
    {
        jQuery(".item."+item).css("background-image", "url('/i/resources-inactive.gif')");
        jQuery(".item."+item+" a").css("color", "#4a542c");
    }

    jQuery(".desc."+item).toggle(200);

    return false;
}



function cleanUpDS(){
    //eliminates a result if your on the page
    var t=(document.title).substring(0,(document.title).indexOf("-"));

    jQuery('.searchG p').not(jQuery('.pubinfo').parent()).hide();

    jQuery("#callouts #gSearch span .l").each(function(index) {
        if (jQuery(this).text().indexOf(t.substring(0,5))>=0)
            console.log(jQuery(this).parent().parent());
    });


    if ( (jQuery("#callouts #gSearch span .pubinfo").length) == 0)
        jQuery('.dynamicCallout').html(cRep);
    else {
        jQuery('.searchG').show();
        GAtrackEvent('Search Term Callout', 'Populates',"For: "+ query + " on " + document.location.href );
    }

}

function dynamicSearchCalloutClickLink() {
    GAtrackEvent('Search Term Callout', 'Link Clicked', "Searched on "+query+" and went to "+jQuery(this).attr('href'));
    console.log('ST Click');


    if(typeof(_gat)!='object')document.write('<sc'+'ript src="http'+
        (document.location.protocol=='https:'?'s://ssl':'://www')+
        '.google-analytics.com/ga.js"></sc'+'ript>')

    try {
        var gwoTracker=_gat._getTracker("UA-5985951-1");
        gwoTracker._trackPageview("/0649303862/goal");
    }catch(err){}


}





function presslist_signupSetState(){
    if(document.getElementById){
        country = document.getElementById('country');
        state   = document.getElementById('state');
        if(country.value != 'United States'){
            state.value = '';
        }
    }
}

flipper_cur = null;
function flipper_rotate(max) {
    setTimeout('_flipper_rotate('+max+')',4000);
}
function flipper_current(max) {
    var set = null;
    for (var i=0; i<max; i++) {
        elem=document.getElementById('flipper'+i);
        if (elem.className == 'highlight') {
            set = i;
        }
    }
    return set;
}
function flipper_set(set,max) {
    for (var i=0;i<max; i++) {
        elem=document.getElementById('flipper'+i);
        elem.className = (i==set?"highlight":"");
    }
    img = document.getElementById('flipper-image');
    img.src = document.getElementById('flipper-image' + set).src;
    url = document.getElementById('flipper-link' + set).href;
    image_url = document.getElementById('flipper-image-link');
    image_url.href = url;
}
function _flipper_rotate(max) {
    if (!document.getElementById) return;
    if (flipper_cur == null) {
        set = flipper_current(max);
        if (set == null) set = 0;
        else set = (1+set)%max;
        flipper_set(set,max);
    }
    flipper_rotate(max);

}
function flipper_over(set,max) {
    flipper_cur = flipper_current(max); 
    flipper_set(set,max);
}
function flipper_out(set,max) {
    flipper_set(flipper_cur,max);
    flipper_cur = null;
}



/// <name>insertMotionGraph</name>
/// <param name="spreadsheetID">takes the googledoc spreadsheet id found in the url after "key"</param>
/// <param name="topLeftCell">the starting cell of the selection for the motion graph</param>
/// <param name="bottomRightCell">the ending cell of the selection for the motion graph</param>
/// <param name="stateString">the state of the motion graph from the advanced tab in the graph</param>
function insertMotionGraph(spreadsheetID,topLeftCell,bottomRightCell,stateString) {
    jQuery('#interactive').html('<img class="inline" src="/i/ajax-loader.gif"></img><p class="inline">Loading Google  Motion Chart</p>');
    jQuery('#interactive').height(502);
    google.load('visualization', '1', {
        packages: ['motionchart']
    });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        var options = {};
        options['width'] = 860;
        options['height'] = 502;
        if (stateString!=''){
            options['state'] = stateString;
        }
        new google.visualization.Query( 'http://spreadsheets.google.com/tq?key='+spreadsheetID+'&range='+topLeftCell+':'+bottomRightCell+'&pub=1').send(
            function(response) {
                new google.visualization.MotionChart(
                    document.getElementById('interactive')).
                draw(response.getDataTable(), options  );
            });
    }

}

function showNewsAlert(area){
    $.ajax({
        type: "GET",
        url: "/util/news-alert.php",
        data: "area="+area,
        success: function(msg){
            if(msg){
                $("#news-alert-container").attr("innerHTML", msg);
                $("#news-alert-container").show();
            }
        }
    });
}

function setNewsAlertCookie(name, value){
    var options = {
        path: '/',
        expires: 7
    };
    $.cookie(name, value, options);
    $("#news-alert-container").hide();
}

