var google_channel = '';
var google_type = '';

function afns_drawPersonals( source_id, target_id ){
	if( source_id == null ){
		source_id = "personals_content";
	}
	if( target_id == null ){
		target_id = "personals";
	}
	//make this work on pages w no target in markup wout browser error
	try {
		var afns_personals_content = document.getElementById( source_id );
		afns_personals_content.parentNode.removeChild(afns_personals_content);
		document.getElementById( target_id ).appendChild(afns_personals_content);
		}
	catch(err) {
		jserror = 1;
	}
    //swap out the male/female icons on select box change
    $("#" + source_id + " select").change( function(){
        if ( $(this).val() == 2 ) {
            $(this).parent().css( "backgroundPosition", "0px 0px" );
        } else {
            $(this).parent().css( "backgroundPosition", "0px -41px" );
        }
    });

}

function afns_getByTagAndClass( tagName, className, root ){
	if( root == null ){
		root = document;
	}
	var nodeList = root.getElementsByTagName( tagName );
	return afns_getByClass( nodeList, className );
}
function afns_getByClass( nodeList, className ){
	for( var i=0; i < nodeList.length; i++){
		var node = nodeList[i];
		if( node.className.indexOf(className) > -1){
			return node;
		}
	}
	return null;
}

function afns_getMetaTag( tagName ){
	var metaTags = document.getElementsByTagName("meta");
	for (i=0;i < metaTags.length;i++){
		if( metaTags[i].getAttribute("name") == tagName ){
			return metaTags[i];
		}
	}
	return null;
}
function email_popup(nid,base_url){
	if(base_url){
		base_url+="/";
	}
	email = open(base_url+"email_page/"+nid,"email_page_window", "width=425px, height=550px, scrollbars=auto, left=20px, top=20px")
}

function most_bla_popup(type, nid, base_url){
	if(base_url){
		base_url+="/";
	}
	email = open(base_url + type,"mostbla_window", "width=602px, height=360px, scrollbars=auto, left=20px, top=20px")
}

function email_close(){
	try{
		email.close();
	}
    catch(err) {

    }
}


function afns_track_click(action){
    //reserved function for metrics event
}
function empty(){}
function getHTTPObj(){var _req=null;if(window.ActiveXObject){_req=new ActiveXObject("Msxml2.XMLHTTP");if(!_req){_req=new ActiveXObject("Microsoft.XMLHTTP")}}else if(window.XMLHttpRequest){_req=new XMLHttpRequest}return _req}
function placeFragment(fromUrl,target){
	var httpObj = getHTTPObj();
	httpObj.onreadystatechange = function() {
        if (httpObj.readyState == 4) {
        	alert(httpObj.responseText);
            document.getElementById(target).innerHTML = httpObj.responseText;
        }
    };
    httpObj.open('GET', fromUrl, true);
    httpObj.send(null);
}

function afns_createCookie(name,value,days){
	var expires = "";
	if (days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function afns_readCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++){
		var c = ca[i];
		while (c.charAt(0)==' '){
			c = c.substring(1,c.length);
		}
		if (c.indexOf(nameEQ) == 0){
			return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}

function afns_eraseCookie(name){
	afns_createCookie(name,"",-1);
}

function show_element(name)
{
        document.getElementById(name).className = (document.getElementById(name).className == 'Show') ? 'Hide' : 'Show';
}

function afns_moveDiv(fromId,toId){
	var fromDiv = document.getElementById(fromId);
	var toDiv = document.getElementById(toId);
	if(fromDiv && toDiv){
		toDiv.appendChild(fromDiv);
	}
}

function generic_popup(url, w, h, features) {
	if(!features) features = 'location=0,scrollbars=0,statusbar=1,menubar=0,resizable=1';
	winprops = 'height='+h+',width='+w+','+features;
	win = window.open(url,'newwin',winprops);
	if (win && win.focus) {
        win.focus();
    }
}

shuffle = function(o){
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

function check_subscrip(theForm) {
    var re_mail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+$/;
    var from_email = $(theForm).find(".email").val();
    if(!re_mail.test(from_email)) {
	alert('Please check the email addresses.');
	return false;
    }
}

function jsonify_forplayer(file,title,id,date,slug) {
    title = title.replace(/\'/g,'\\\'');
    file = file.replace(/\'/g,'\\\''); //there are 's in file names, grrrrrr
    file = file.replace(/\+/g,' '); //there are spaces in file names, grrrrrr
    var json = "{soundFile:'"+file+"', title:'"+title+"', id:'"+id+"', date:'"+date+"', slug:'"+slug+"'}";
    return json;
}

function onion_mostpopular() {
    $("#mostpopular").load(afns_base_path+"ajax/mostpopular", function(){
        var current = 1;
        var newtabs = $("#mostpopular > ul").tabs();
        newtabs.tabs("select",Math.floor(Math.random()*4));
        try {
            var current = parseInt(afns_readCookie('onion_lastseen'));
        }
        catch(err) {
        }
        if(isNaN(current) == true) {
            var current = 1;
        }
        $("#mostpopular ul").children().each(function() {
            var ts = $(".timestamp",this).text();
            if(ts > current) {
                $("a",this).css("color","#14517B");
            }
        });
        //set a cookie for having last seen this, to create hilites
        afns_createCookie('onion_lastseen',parseInt(new Date().getTime().toString().substring(0, 10)),30);
    });
}

function onion_article_init() {
    onion_mostpopular();
}

function onion_landing_init() {
    onion_mostpopular();
	//force the column heights above the fold to be equal
	/* needs further testing
	var elemList = new Array ("#sidebar", "#news_main", "#brief_area");
	afns_forceHeight(elemList);
	//$("#bottom").css( { top: $("#content").css('top') + $("#content").height() + 15 } );
	*/
}

function nnh_init(current_id, next_id, prev_id) {
    $("#nnh_entry .teaser").fadeIn(150);
    $('.map_image').hover(
        //onhover
        function(){
            if(next_id !== "") {
                $("#nnh_right").show();
            }
            if(prev_id !== "") {
                $("#nnh_left").show();
            }
        },
        //offhover
		function(){
        }
    );
    $("#nnh_right").click(function () {
        if(next_id !== "" && next_id != undefined) {
            display_nnh_entry(next_id);
        }
    });
    $("#nnh_left").click(function () {
        if(prev_id !== "" && prev_id != undefined) {
            display_nnh_entry(prev_id);
        }
    });
}

function display_nnh_entry(id) {
    $(".ajax_loader").fadeIn("slow");
    $("#features").load(afns_base_path+"ajax/nnh/"+id,function(){
	    $(".ajax_loader").hide();
    });
}

function genericpager_init(id) {
    var current = $(".inline_pager .active").attr("rel");
    $("#"+id+" .elem"+current).show();
    $(".inline_pager .pagenum").click(function () {
        genericpager_activate(this, id, $(this).attr("rel"));
    });
    $(".inline_pager .previous").click(function () {
        var pagenum = genericpager_pagenum(id, "previous");
        genericpager_activate($(".inline_pager .active").prev(), id, pagenum);
    });
    $(".inline_pager .next").click(function () {
        var pagenum = genericpager_pagenum(id, "next");
        genericpager_activate($(".inline_pager .active").next(), id, pagenum);
    });
}

function genericpager_activate(obj, id, pagenum) {
    try {
        var max = parseInt(pager_max)+1;
        var min = parseInt(pager_min)-1;
    }
    catch(err) {
        var max = 4;
        var min = 0;
    }
    if(pagenum > min && pagenum < max) {
		$("#"+id+" li").hide();
        $("#"+id+" .elem"+pagenum).fadeIn(500);
		$(".inline_pager a").removeClass("active");
        $(obj).addClass("active");
    }
    else {
        try {
            if(pagenum == min) {
                $.get(pager_ajax_prev, function(data){
                    if(data !== "") {
                        $("#features").html(data);
                    }
                });
            }
            else {
                $.get(pager_ajax_next, function(data){
                    if(data !== "") {
                        $("#features").html(data);
                    }
                });
            }
        }
        catch(err) {
        }
    }
}

function genericpager_pagenum(id, prevnext) {
        var currentpagenum = $(".inline_pager .active").attr("rel");
        var pagenum = parseInt(currentpagenum);
        if(prevnext == "next") {
            pagenum = pagenum + 1;
        }
        else {
            pagenum = pagenum - 1;
        }
        return pagenum;
}

function orn_smallplayer_track(title) {
    pageTracker._trackEvent("radionews", "SmallPlay", title); //the google tracking code call
}

function jumpPage(s, urlbase) {
    var newloc = s.selectlist.value;
    if(newloc != "#" && newloc != "-- select --"){
        document.location.href = urlbase + newloc;
    }
    return false;
}

function togglePremercial(state) {
    if(state == "show") {
        $("#premercial").show();
    }
    else {
        $("#premercial").hide();
        $("#wrapper").show();
    }
}

function afns_allow_premercial(adname) {
    if(navigator.cookieEnabled) {
        if(!afns_readCookie('premercial')) {
            return true;
        }
    }
    return false;
}

function afns_show_premercial(adname) {
    var premercial = false;
    if(navigator.cookieEnabled) {
        if(!afns_readCookie('premercial')) {
            try {
                var premercial = $("#google_ads_div_"+adname).html();
            }
            catch(err) {
            }
            if(premercial) {
                togglePremercial("show");
                $("#closepremercial").click(function () {
                    togglePremercial("hide");
                });
                setTimeout('togglePremercial("hide")', 19000);
                //theyve seen the premercial, set the cookie
                //always just do a single permercial per person per day
                afns_createCookie('premercial', adname, 1);
            }
            else {
                $("#wrapper").show();
            }
        }
        else {
            $("#wrapper").show();
        }
    }
    else {
        $("#wrapper").show();
    }
}

function onion_ad_hide(id, name) {
      $("#"+id).fadeOut('slow');
}

function onion_ad(id, name, fade) {
    var impact_ad = false;
    try {
        var impact_ad = $("#google_ads_div_"+name).html();
    }
    catch(err) {
    }
    if(impact_ad) {
        $("#"+id).show();
        if(fade) {
            setTimeout('onion_ad_hide("'+id+'","'+name+'")', 10000);
        }
    }
}


function checkdate(when) {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var day = date.getDate();
    var check = year+""+(month+1)+""+day;
    if(check == when) {
 		return true;
    }
    return false;
}
function StoreProduct(image, link){
	this.image=image;
	this.link=link;
}
function afns_placeOnionStoreAd(page){
	var featured_products = new Array();
    var images = new Array(
        '300x130_FP_AreaMan1.jpg',
        '300x130_FP_decoy.jpg',
        'Mugs-Feat-Prod_group.jpg',
        'T-SHIRTSaug09-300x130-2.jpg',
        '300x130_FP_pints.jpg',
        'Mugs-Feat-Prod_newstyle.jpg',
        'T-SHIRTSaug09-300x130-4.jpg',
        '300x130_WaterBottle1.jpg',
        'Store_300x100_Giftbox.jpg',
        '300x130_FP_CorpTee.jpg',
        'Magnets_Feat-Prod_300x130.jpg',
        'Store_300x100_Prints.jpg',
        'Featured-Products_BookCombo.jpg',
        'Featured-Products_Doormat.jpg'
    );

    var current = new Date().getTime();
    var start = new Date("2010/02/06 EST").getTime();
    var end = new Date("2010/02/11 EST").getTime();
    if(current > start && current < end) {
        images = new Array('Valentine_FeatredProduct_1.jpg',
                          'Valentine_FeatredProduct_2.jpg');
    }
    for(k in images) {
	    featured_products.push(
            new StoreProduct(
		        images[k],
		        'http://store.theonion.com/?utm_source=FPQ4')
        );
    }
	var prodNum = Math.round((featured_products.length-1)*Math.random());
    var product = featured_products[prodNum];
    if(page == "home") {
	    $("#onionstore_ad").html( '<a target="_blank" href="'+product.link+'">'+'<img src="'+afns_base_path+'themes/onion/assets/store/'+product.image+'?k=2" /></a>' );
    }
    else {
	    $('#store_callout').html( '<h6><a href="http://store.theonion.com">Onion Store</a></h6><a class="image" target="_blank" href="'+product.link+'"><img src="'+afns_base_path+'themes/onion/assets/store/'+product.image+'" width="300" alt="-" /></a>' );
    }
}

