addDOMLoadEvent = (function(){
    // create event function stack
    var load_events = [],
        load_timer,
        script,
        done,
        exec,
        old_onload,
        init = function () {
            done = true;

            // kill the timer
            clearInterval(load_timer);

            // execute each function in the stack in the order they were added
            while (exec = load_events.shift())
                exec();

            if (script) script.onreadystatechange = '';
        };

    return function (func) {
        // if the init function was already ran, just run this function now and stop
        if (done) return func();

        if (!load_events[0]) {
            // for Mozilla/Opera9
            if (document.addEventListener)
                document.addEventListener("DOMContentLoaded", init, false);

            // for Internet Explorer
            /*@cc_on @*/
            /*@if (@_win32)
            	//alert('yip');
                document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
                script = document.getElementById("__ie_onload");
                script.onreadystatechange = function() {
                    if (this.readyState == "complete")
                        init(); // call the onload handler
                };
            /*@end @*/

            // for Safari
            if (/WebKit/i.test(navigator.userAgent)) { // sniff
                load_timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState))
                        init(); // call the onload handler
                }, 10);
            }

            // for other browsers set the window.onload, but also execute the old window.onload
            old_onload = window.onload;
            window.onload = function() {
                init();
                if (old_onload) old_onload();
            };
        }

        load_events.push(func); 
    }
})();

//jsonp func//
(function(){
  var id = 0, head = document.getElementsByTagName('head')[0], global = this;
  global.getJSON = function(url, callback) {
    var script = document.createElement('script'), token = '__jsonp' + id;
    
    // callback should be a global function
    global[token] = callback;
    
    // url should have "?" parameter which is to be replaced with a global callback name
    script.src = url.replace(/\?(&|$)/, '__jsonp' + id + '$1');
    
    // clean up on load: remove script tag, null script variable and delete global callback function
    script.onload = function() {
      script.parentNode.removeChild(script);
      script = null;
      delete global[token];
    };
    head.appendChild(script);
    
    // callback name should be unique
    id++;
  }
})();






var Poll = function(widgetId, serviceUrl, votingTimeout) {
            var ajax = function(params, callback) {
                var timeouted = false;
                var timer = setTimeout(function() {
                    timeouted = true;
                    alert("Poll TIMEOUT "+params.url)
                    if (callback) callback();
                }, votingTimeout==null ? 5000 : votingTimeout);
            
                var success = function(response) {
                    if (timeouted) return;
                    if (timer) {
                        clearTimeout(timer);
                        timer = null;
                    }
                    if (callback) callback(response);
                };
 
                var error = function(e) {
                    var s="";
                    for (var p in e)
                    	s+=p+"="+e[p]+" ";
                    alert("Poll ERROR: "+s);
                    if (timeouted) return;
                    if (timer) {
                        clearTimeout(timer);
                        timer = null;
                    }
                    if (callback) callback();
                };
                
                //params.type= "POST";
                params.dataType = "jsonp";
                params.success = success;
                params.error = error;
               
                if (params.url.indexOf("?")!=-1)
            		params.url += "&callback=?"
            	else
            		params.url += "?callback=?"
                params.url += "&method="+ params.type;
                params.type = "GET";
//                $.ajax(params);
                getJSON(params.url, success);
                
//                document.getElementById("status").innerHTML += params.type+" "+params.url+"<br/>";
            };

            this.sendVote = function(name, callback) {
                ajax({
                    type: 'POST',
                    url: serviceUrl+'/'+widgetId+'/'+name
                }, callback);
            };
            
            this.requestStats = function(callback) {
                ajax({
                    type: 'GET',
                    url: serviceUrl+'/'+widgetId
                }, callback);
            };
            
            this.requestStatsWithPrefix = function(pre, callback) {
                ajax({
                    type: 'GET',
                    url: serviceUrl+'/'+widgetId+"?prefix="+pre
                }, callback);
            };
 
            this.requestCounter = function(name, callback) {
                ajax({
                    type: 'GET',
                    url: serviceUrl+'/'+widgetId+'/'+name
                }, callback);
            };
 
            this.setCounter = function(name, value, callback) {
                ajax({
                    type: 'PUT',
                    data: { value: value },
                    url: serviceUrl+'/'+widgetId+'/'+name
                }, callback);
            };
 
            this.removeCounter = function(name, callback) {
                ajax({
                    type: 'DELETE',
                    url: serviceUrl+'/'+widgetId+'/'+name
                }, callback);
            };
 
            this.removeAllCounters = function(callback) {
                ajax({
                    type: 'DELETE',
                    url: serviceUrl+'/'+widgetId
                }, callback);
            };
};
















var img_base = config.script_base;

function set_html_if_fb_connected(html_if_connected,html_if_not_connected,div)
{	
	FB.Connect.ifUserConnected
	(
	      function() {div.innerHTML = html_if_connected;}, 
	      function() {div.innerHTML = html_if_not_connected;}
	);

}



function fp_build_page(tab)
{
	if(GET_COOKIE('internal_reload') == null)
		SET_COOKIE('fp_time_idx',0);
	else
		ERASE_COOKIE('internal_reload');	

	
	var day_idx = GET_URL_PARAM('d');
	if(day_idx != null)
		SET_COOKIE('fp_day_idx',day_idx);

	if(tab != null)
	{
		SET_COOKIE('fp_day_idx',tab);
	}
	
	
	day_idx = GET_COOKIE('fp_day_idx');
	if(day_idx == null)
	{
		day_idx = 0;
		SET_COOKIE('fp_day_idx',day_idx);
	}
	
	
	for(var i = 0;i < 7;i++)
	{
		var day_tab = document.getElementById('fp_tab_'+day_idx);	
		if(day_tab == null)
			continue;
		if(i == day_idx)
		{
			day_tab.className = 'on';
			day_tab.style.backgroundColor = '#fff';
		}
		var tab_link  = document.getElementById('fp_tab_'+i+'_link');
		if(tab_link == null)
			continue;
		tab_link.href = 'javascript:select_day('+i+');'
	}
	
		
	var p_div = document.getElementById('fp_content');
	p_div.innerHTML = "<span style='font-size:24px;font-family:arial;line-height:64px;'>Loading Poll&nbsp;&nbsp;&nbsp;<img src='"+config.BASE_INSTALL_URL+"img/loading.gif'/></span>";
	addDOMLoadEvent(function(){do_build_page('fp_content')});
}


function do_build_page(host_div)
{

	FB.ensureInit(function()
		{
			var p_div = document.getElementById(host_div);
			p_div.innerHTML = '';
			p_div.appendChild(ANCHOR('the_top'));
			//g_genre_idx  = GET_COOKIE('genre_idx'); 
			//g_cat_idx    = GET_COOKIE('cat_idx'); 
			//if(g_genre_idx==null)
			//	g_genre_idx=0;
			//if(g_cat_idx==null)
			//	g_cat_idx=0;


			build_fall_premiere(p_div);	
		
			
			var pending_anchor = GET_COOKIE('fp_pending_anchor');
			if(pending_anchor != null)
			{
				document.location.hash = pending_anchor;
				ERASE_COOKIE('fp_pending_anchor');
			}
		});	
}


function select_day(day_idx)
{
	SET_COOKIE('fp_day_idx',day_idx);
	SET_COOKIE('fp_time_idx',0);
	RELOAD('the_top');
}


function select_time(idx)
{
	SET_COOKIE('fp_time_idx',idx);
	RELOAD('the_top');
}

function submit_poll(ctx)
{
	//var error_div = document.getElementById('submit_error_div_'+genre+'_'+cat);	
	//error_div.innerHTML='';	

	var day_idx  = ctx.d;
	var time_idx = ctx.t;
	var show_idx = ctx.s;
	var vote 	 = ctx.v;
	//alert('vote is '+day_idx+'-'+time_idx+'-'+show_idx+' '+vote);	

	vote_transpond(day_idx,time_idx,show_idx,vote,function()
		{
			SET_COOKIE(day_idx+'-'+time_idx+'-'+show_idx,vote);
			handle_facebook_connect_share(day_idx,time_idx,show_idx,(vote=='iw'));		
		}
	);

	//moved reload from here to below//
}

function handle_facebook_connect_share(day,time,show,will_watch)
{	
		FB.Connect.ifUserConnected (
			function(){
				var c = document.getElementById("fb_share_check_"+day+"_"+time+"_"+show);
            	if(c!=null && c.checked)
            	{
            		var uid = FB.Connect.get_loggedInUser();
            		 publish_to_stream(uid,day,time,show,will_watch);
            	}
            	else	
					RELOAD('the_top');
			},
			function()
				{
            		RELOAD('the_top');
            	}
		);
}

var poll_genre_fb_display_map = {"Comedy":"comedy",
                                 "Drama":"drama",
                                 "Reality & Variety":"reality & variety show",
                                 "Animation":"animated show",
                                 "Miniseries":"miniseries"};
function publish_to_stream(fbuser,day,time,show,will_watch)
{
	var show = config.days[day].times[time].shows[show];
	var show_title  = show.title;
	var show_img    = config.BASE_RESOURCE_URL+show.thumbnail;
	var title = 'TV.com 2009 Fall Premieres';
	var link_url = "http://www.tv.com/fall-premieres2009/";
	var msg = (will_watch)?"Count me in for the season premiere of "+show_title+". Which fall shows will you watch? Which ones will you skip? Vote in TV.com's poll, and find out when all your favorite shows are premiering this fall.":
							"I'm skipping the season premiere of "+show_title+". Which fall shows will you watch? Which ones will you take a pass on? Vote in TV.com's poll, and find out when all your favorite shows are premiering this fall.";

	var attachment = {'name':'TV.com Fall Premieres 2009 Poll',
					  'href':link_url,
					  'caption':'',
					  'description':'',	  
					  'media':[{'type':'image','src':show_img,
						        'href':link_url}
						       ]
					  };
	FB.Connect.streamPublish(msg, attachment,null,null,null,function(){RELOAD('the_top')});
}



function vote_transpond(tab,sub,poll,vote,f)
{

	var asset_id = 'fp-'+tab+'-'+sub+'-'+poll;
	
	if (config.USE_SERVICE_VERSION==0)
	{
		var jsonp_url = config.VOTE_SERVICE_URL_0+"?callback=?&action=save&widgetId="+config.TRANSPOND_WIDGET_ID+"&componentId="+config.TRANSPOND_COMPONENT_ID+"&tally=true&allowDuplicateVotes=true&platform=standalone&assetId="+asset_id+"&vote=1&voteValue="+vote+"&average=true";
		
		getJSON(
		jsonp_url,
			function(data)
			{
				if(f != null)
					f();
			}
		);
		
	}
	else if (config.USE_SERVICE_VERSION==1)
	{
		var poll = new Poll(config.TRANSPOND_WIDGET_ID, config.VOTE_SERVICE_URL_1);
		poll.sendVote(asset_id+"-"+vote, function(data)
				{
					if(f != null)
						f();
				});
	}
}


function load_transpond(tab,sub,poll,percent_divs,totals_divs,bar_divs)
{
	
	var asset_id = 'fp-'+tab+'-'+sub+'-'+poll;
	if (config.USE_SERVICE_VERSION==0)
	{
		
		// alert("wid: "+config.TRANSPOND_WIDGET_ID);
		// alert("cid: "+config.TRANSPOND_COMPONENT_ID);
		var jsonp_url = config.VOTE_SERVICE_URL_0+"?callback=?&action=load&widgetId="+config.TRANSPOND_WIDGET_ID+"&componentId="+config.TRANSPOND_COMPONENT_ID+"&tally=true&allowDuplicateVotes=true&platform=standalone&assetId="+asset_id+"&average=true";
		getJSON(
			jsonp_url,
			function(t_obj)
			{
				for(var i = 0;i < percent_divs.length;i++)
		    	{
					var key;
					if(i==0)
						key = 'iw';
					else
						key = 'ip';
					
		    		var p_v = t_obj.keyedTally[key].percentage;
		    		var t_v = t_obj.keyedTally[key].count;
		    		//alert(percent_divs[i]+" : "+totals_divs[i]+" : "+bar_divs[i]);
		    		//alert(ss);
		    		percent_divs[i].innerHTML = p_v;
		    		totals_divs[i].innerHTML  = add_commas(t_v)+' votes';
		    		var bar_id = tab+'-'+sub+'-'+poll+'-'+key+'bar'
		    		var bar = document.getElementById(bar_id);
		    		bar.style.width = p_v;
		    	}	
			}
			
		);		
	
	}
	else if (config.USE_SERVICE_VERSION==1)
	{
		var pollservice = new Poll(config.TRANSPOND_WIDGET_ID, config.VOTE_SERVICE_URL_1);
		pollservice.requestStatsWithPrefix(asset_id+"-", function (t_obj)
		{
			var ip = t_obj.data.counters[0];
			var iw = t_obj.data.counters[1];
			if (ip.name.indexOf("-iw")!=-1)
			{
				var t = ip;
				ip = iw;
				iw = t;
			}
			var total = parseInt(ip.counter)+parseInt(iw.counter);
			
			for(var i = 0;i < percent_divs.length;i++)
	    	{
				var o;
				var key;
				if(i==0)
				{
					o = iw;
					key = "iw";
				}
				else
				{
					o = ip;
					key = "ip";
				}
	    		var p_v = parseInt(o.counter)/total;
	    		var t_v = o.counter;
	    		percent_divs[i].innerHTML = Math.round(p_v*100)+"%";
	    		totals_divs[i].innerHTML  = add_commas(t_v)+' votes';
	    		var bar_id = tab+'-'+sub+'-'+poll+'-'+key+'bar'
	    		var bar = document.getElementById(bar_id);
	    		bar.style.width = Math.round(p_v*100)+"%";
	    	}
			
		});
		
	}
}


function add_commas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}



function build_fall_premiere(parent_div)
{

	var day_idx = GET_COOKIE('fp_day_idx');
	var time_idx = GET_COOKIE('fp_time_idx');
	if(time_idx == null)
	{
		time_idx = 0;
		SET_COOKIE('fp_time_idx',0);
	}
	var times_menu = generate_premiere_times_menu(day_idx,time_idx);
	parent_div.appendChild(times_menu);

	var shows = config.days[day_idx].times[time_idx].shows;
	for(var i = 0;i < shows.length;i++)
	{
		var show = shows[i];
	
		var show_totals = false;
		var existing_vote_val =  GET_COOKIE(day_idx+'-'+time_idx+'-'+i);
		if(config.TEST_RESULTS || existing_vote_val != null)
			show_totals = true;
		
		var s = generate_premiere_container(parent_div,
										    day_idx,
											time_idx,
											i,
											show.title,
											show.thumbnail,
											show.url,
											show.date,
											show.network,
											show.description,
											show_totals,
											(existing_vote_val == 'iw'),
											12000,
											"18%",
											150394,
											"82%");

	}

}

function generate_premiere_container(parent_div,
                                     day_idx,
                                     time_idx,
                                     show_idx,
                                     title,
                                     image,
                                     url,
                                     date,
                                     network,
                                     description,
                                     show_results,
                                     ill_watch,//boolean for this user
                                     ill_watch_total_votes,
                                     ill_watch_percentage,
                                     ill_pass_total_votes,
                                     ill_pass_percentage)
{

	var premiere_container = MAKE_DIV('premiere_container');
	var premiere_image = MAKE_SIZED_HREF_IMG_DIV(120,80,url,config.BASE_RESOURCE_URL+image,'premiere_image');
	premiere_container.appendChild(premiere_image);
	
	var premiere_info 		 = MAKE_DIV('premiere_info');
	var premiere_header 	 = MAKE_HREF_DIV(url,title,'premiere_header');
	var premiere_sub_header  = MAKE_TEXT_DIV(date+' - '+network,'premiere_sub_header'); 
	var premiere_description = MAKE_TEXT_DIV(description,'premiere_description');
	var premiere_share_bar 	 = MAKE_TEXT_DIV(share_html,'premiere_share_bar');	
	var share_html;
	if(show_results)
	{
		var fb_share_link   	  = "javascript:open_fb_sharer_window("+day_idx+","+time_idx+","+show_idx+","+new String((ill_watch)?1:0)+");";
		var twitter_share_link    = "javascript:open_twitter_sharer_window("+day_idx+","+time_idx+","+show_idx+","+new String((ill_watch)?1:0)+");";
		share_html 				  = "SHARE ON &nbsp;&nbsp;<a href='"+fb_share_link+"'><img src='"+config.BASE_INSTALL_URL+"img/fb-icon.png'/> FACEBOOK</a> <a href='"+twitter_share_link+"'><img src='"+config.BASE_INSTALL_URL+"img/twitter-icon.png'/> TWITTER</a>";
		set_html_if_fb_connected('',share_html,premiere_share_bar);	
	}
	else
	{
		share_html = "<input type='checkbox' id='fb_share_check_"+day_idx+"_"+time_idx+"_"+show_idx+"' checked='on'/> Publish to Facebook";
		set_html_if_fb_connected(share_html,'',premiere_share_bar);	
	}
	

	
	//var share_html = "<input type='checkbox' id='fb_share_check_"+poll_genre+"_"+poll_category+"' checked='on'/> Publish to Facebook";
	//set_html_if_fb_connected(share_html,'',poll_submit_bar_share);
	
	
	premiere_info.appendChild(premiere_header);
	premiere_info.appendChild(premiere_sub_header);
	premiere_info.appendChild(premiere_description);
	premiere_info.appendChild(premiere_share_bar);
	premiere_container.appendChild(premiere_info);

    var percent_divs = new Array();
    var totals_divs  = new Array();
    var bar_divs	 = new Array();
	var result_percentage1;
	var result_check1;
	var result_total_bar1_html;
	var result_total_bar1;
	var result_total_votes1;
	
	
	var ill_watch_cell 			= MAKE_DIV('ill_watch_cell');
	var	results_container1 		= MAKE_DIV('results_container');
	if(show_results)
	{
		result_percentage1 		= MAKE_IMG_DIV(config.BASE_INSTALL_URL+'img/loading.gif','result_percentage');
		if(ill_watch)
			result_check1      	= MAKE_IMG_DIV(config.BASE_INSTALL_URL+'img/green_check.png','result_check');
		else
			result_check1      	= MAKE_DIV('result_check');
		
		//result_total_bar1_html 	= "<div style='background-color:#699800;width:0%;height:8px;'></div>";
		result_total_bar1   	= MAKE_DIV('result_total_bar');
		//alert('iw bar is '+day_idx+'-'+time_idx+'-'+show_idx+'-iwbar');
		var the_bar1 = MAKE_DIV('result_real_bar',day_idx+'-'+time_idx+'-'+show_idx+'-iwbar');
		the_bar1.style.backgroundColor = '#699800';
		the_bar1.style.width = '0%';
		the_bar1.style.height = '8px';
		result_total_bar1.appendChild(the_bar1);
		result_total_votes1 	= MAKE_TEXT_DIV('','result_total_votes');
		percent_divs.push(result_percentage1);
		totals_divs.push(result_total_votes1);
		bar_divs.push(result_total_bar1);
	
	}
	var result_vote_button1;
	if(show_results)
		result_vote_button1 = MAKE_TEXT_DIV("<img src='"+config.BASE_INSTALL_URL+"img/vote-again-green.png' onmouseover=\"this.src='"+config.BASE_INSTALL_URL+"img/vote-again-green-on.png';\" onmouseout=\"this.src='"+config.BASE_INSTALL_URL+"img/vote-again-green.png';\"/>",'result_vote_button');
	else
		result_vote_button1 = MAKE_TEXT_DIV("<img src='"+config.BASE_INSTALL_URL+"img/ill_watch.png' onmouseover=\"this.src='"+config.BASE_INSTALL_URL+"img/ill_watch_on.png';\" onmouseout=\"this.src='"+config.BASE_INSTALL_URL+"img/ill_watch.png';\"/>",'result_vote_button');
	
	result_vote_button1.d 	 = day_idx;
	result_vote_button1.t 	 = time_idx;
	result_vote_button1.s 	 = show_idx;
	result_vote_button1.v 	 = 'iw';
	result_vote_button1.onclick = function(){submit_poll(this);}

	if(show_results)
	{
		results_container1.appendChild(result_percentage1);
		results_container1.appendChild(result_check1);
		results_container1.appendChild(CLEAR_BOTH());
		results_container1.appendChild(result_total_bar1);
		results_container1.appendChild(result_total_votes1);

	}
		results_container1.appendChild(result_vote_button1);
		ill_watch_cell.appendChild(results_container1);
		premiere_container.appendChild(ill_watch_cell);
	
		
	var result_percentage2;
	var result_check2;
	var result_total_bar2_html;
	var result_total_bar2;
	var result_total_votes2;
	
	var ill_pass_cell 			= MAKE_DIV('ill_pass_cell');
	var results_container2 		= MAKE_DIV('results_container');
	if(show_results)
	{
		result_percentage2 		= MAKE_IMG_DIV(config.BASE_INSTALL_URL+'img/loading.gif','result_percentage');
		if(!ill_watch)
			result_check2      		= MAKE_IMG_DIV(config.BASE_INSTALL_URL+'img/red_check.png','result_check');
		else
			result_check2      		= MAKE_DIV('result_check');
		//result_total_bar2_html 	= "<div style='background-color:#c63434;width:10%;height:8px;'></div>";
		result_total_bar2   	= MAKE_DIV('result_total_bar');
		var the_bar2 = MAKE_DIV('real_bar',day_idx+'-'+time_idx+'-'+show_idx+'-ipbar');
		the_bar2.style.backgroundColor = '#c63434';
		the_bar2.style.width = '0%';
		the_bar2.style.height = '8px';
		result_total_bar2.appendChild(the_bar2);
		result_total_votes2 	= MAKE_TEXT_DIV('','result_total_votes');
		percent_divs.push(result_percentage2);
		totals_divs.push(result_total_votes2);
		bar_divs.push(result_total_bar2);
	}
	var result_vote_button2;
	if(show_results)
		result_vote_button2 	= MAKE_TEXT_DIV("<img src='"+config.BASE_INSTALL_URL+"img/vote-again-red.png' onmouseover=\"this.src='"+config.BASE_INSTALL_URL+"img/vote-again-red-on.png';\" onmouseout=\"this.src='"+config.BASE_INSTALL_URL+"img/vote-again-red.png';\"/>",'result_vote_button');
	else
		result_vote_button2 	= MAKE_TEXT_DIV("<img src='"+config.BASE_INSTALL_URL+"img/ill_pass.png' onmouseover=\"this.src='"+config.BASE_INSTALL_URL+"img/ill_pass_on.png';\" onmouseout=\"this.src='"+config.BASE_INSTALL_URL+"img/ill_pass.png';\"/>",'result_vote_button');
	
	result_vote_button2.d 	 	= day_idx;
	result_vote_button2.t 	 	= time_idx;
	result_vote_button2.s 	 	= show_idx;
	result_vote_button2.v 	 	= 'ip';
	result_vote_button2.onclick = function(){submit_poll(this);}
	
	if(show_results)
	{
		results_container2.appendChild(result_percentage2);

		results_container2.appendChild(result_check2);
		results_container2.appendChild(CLEAR_BOTH());
		results_container2.appendChild(result_total_bar2);
		results_container2.appendChild(result_total_votes2);
	}
	
	results_container2.appendChild(result_vote_button2);
	ill_pass_cell.appendChild(results_container2);
	premiere_container.appendChild(ill_pass_cell);

	parent_div.appendChild(premiere_container);
	if(show_results)
		load_transpond(day_idx,time_idx,show_idx,percent_divs,totals_divs,bar_divs);

}



function generate_premiere_times_menu(day_idx,selected_time_idx)
{
	var times = config.days[day_idx].times;
	
	var menu = MAKE_DIV('premiere_times_menu');
	var header = MAKE_TEXT_DIV('Show Premieres','premiere_times_header');
	menu.appendChild(header);
	for(var i = 0;i < times.length;i++)
	{
		var item;
		if(i == selected_time_idx)
			item = MAKE_TEXT_DIV(times[i].time,'premiere_times_menu_item_selected')	
		else
		{
			var title = times[i].time;
			var url = 'javascript:select_time('+i+')';
			var link = '<a href='+url+'>'+title+'</a>';
			item = MAKE_TEXT_DIV(link,'premiere_times_menu_item');	
		}
		menu.appendChild(item);
	
	}
	var ill_watch = MAKE_TEXT_DIV("I'll Watch",'ill_watch_header');
	var ill_pass  = MAKE_TEXT_DIV("I'll Pass",'ill_pass_header');
	menu.appendChild(ill_pass);
	menu.appendChild(ill_watch);
	menu.appendChild(CLEAR_BOTH());
	return menu;
}


function generate_back_to_top()
{
	var url = "<a href='javascript:GOTO_TOP()'>Back To Top</a>";
	var div = MAKE_TEXT_DIV(url,'back_to_top')
	return div;
}

function generate_genre_menu(selected_genre)
{
	var genre_menu = document.createElement('div');
	genre_menu.setAttribute('class','genre_menu');
	var awards = config.awards;
	
	for(var i = 0;i < awards.length;i++)
	{
		var award = awards[i];
		var genre = award.genre;		
		var genre_menu_item;	
		if(i == selected_genre)
		{
			genre_menu_item = document.createElement('div');
			genre_menu_item.className = 'genre_menu_item genre_menu_item_selected';
			genre_menu_item.setAttribute('class','genre_menu_item genre_menu_item_selected');
			genre_menu_item.innerHTML = genre;	
		}
		else
		{
			genre_menu_item = document.createElement('div');
			var url = 'javascript:select_genre('+i+')';
			genre_menu_item.innerHTML = '<a href='+url+'>'+genre+'</a>';;
			genre_menu_item.className = 'genre_menu_item';
			genre_menu_item.setAttribute('class','genre_menu_item');
		}
		genre_menu.appendChild(genre_menu_item);
	}
	genre_menu.appendChild(CLEAR_BOTH());
	return genre_menu;
}

function remove_html_entities(s,c)
{
	if(c == null)
		c = '-';
	var r = s.replace(/\&[a-zA-Z0-9_]*\;/g, c);
	return r;
}

function open_fb_sharer_window(tab,sub,poll,will_watch)
{
	var show = config.days[tab].times[sub].shows[poll];
	var show_title  = show.title;
	var show_img    = config.BASE_RESOURCE_URL+show.thumbnail;
	var title = 'TV.com 2009 Fall Premieres';
	var link_url = "http://www.tv.com/fall-premieres2009/";
	var msg = (will_watch==1)?"Count me in for the season premiere of "+show_title+". Which fall shows will you watch? Which ones will you skip? Vote in TV.com's poll, and find out when all your favorite shows are premiering this fall.":
							  "I'm skipping the season premiere of "+show_title+". Which fall shows will you watch? Which ones will you take a pass on? Vote in TV.com's poll, and find out when all your favorite shows are premiering this fall."; 
	msg = remove_html_entities(msg);	
	
	var share_link = "http://www.facebook.com/sharer.php?u="+escape("http://grid.transpond.com/sharetofb.php?title="+title+"&description="+msg+"&image_src="+show_img+"&url="+escape(link_url));
	var popup = window.open(share_link,'sharer_win',
							'left=200,top=200,width=640,height=480,toolbar=1,resizable=0');
	popup.focus();
}

function open_twitter_sharer_window(tab,sub,poll,will_watch)
{
	var show = config.days[tab].times[sub].shows[poll];
	var show_title  = show.title;
	var show_img    = config.BASE_RESOURCE_URL+show.thumbnail;
	var title = 'TV.com 2009 Fall Premieres';
	var link_url = "http://www.tv.com/fall-premieres2009/";
	var msg = (will_watch==1)?"I'll watch the season premiere of "+show_title+". Will you? Take TV.com's poll. http://www.tv.com/fall-premieres2009/":
							  "I'll skip the season premiere of TK. Will you? Take TV.com's poll.http://www.tv.com/fall-premieres2009/";
	
	msg = encodeURI(remove_html_entities(msg)).split('%20').join('+');
	var share_link = "http://twitter.com/home?status="+msg;
	//alert(share_link);
	var popup = window.open(share_link,'t_sharer_win',
							'left=200,top=200,width=550,height=480,toolbar=1,resizable=1');

	popup.focus();
}

function MAKE_DIV(classname,id)
{
	var div = document.createElement('div');
	div.className = classname;
	div.setAttribute('class',classname);
	if(id != null)
	{
		div.id = id;
		div.setAttribute('id',id);
	}
	return div;
}

function MAKE_TEXT_DIV(text,classname,id)
{
	var div = MAKE_DIV(classname,id);
	div.innerHTML = text;
	return div;
}

function MAKE_HREF_DIV(url,text,classname,id)
{
	var div = MAKE_DIV(classname,id);
	div.innerHTML = "<a href='"+url+"'>"+text+"</a>";
	return div;
}

function MAKE_IMG_DIV(src,classname,id)
{
	var div = MAKE_DIV(classname,id);
	div.innerHTML = "<img src='"+src+"'/>";
	return div;
}

function MAKE_HREF_IMG_DIV(url,src,classname,id)
{
	var div = MAKE_DIV(classname,id);
	div.innerHTML = "<a href='"+url+"'><img src='"+src+"'/></a>";
	return div;
}

function MAKE_SIZED_HREF_IMG_DIV(w,h,url,src,classname,id)
{
	var div = MAKE_DIV(classname,id);
	div.innerHTML = "<a href='"+url+"'><img src='"+src+"' width='"+w+"' height='"+h+"'/></a>";
	return div;
}

function MAKE_ID_IMG_DIV(id,src,classname,did)
{
	var div = MAKE_DIV(classname,did);
	div.innerHTML = "<img src='"+src+"' id='"+id+"'/>";
	return div;
}

function CLEAR_BOTH()
{
	var d = MAKE_DIV();
	d.style.clear = 'both';
	return d;
}

/* UTIL */
var fp_2009_cookie = {id:'fp_2009_cookie'};
var __the_cookie__ = fp_2009_cookie;
var cinit = false;
function SET_COOKIE(c_name,value,expiredays)
{
	if(cinit == false)
	{
		GET_COOKIE("");
		cinit = true;
	}
	
	if(value == null)
		delete __the_cookie__[c_name];
	else
		__the_cookie__[c_name] = value;
	
	var flattened_cookie = flatten_cookie();
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie= __the_cookie__.id+ "=" +flattened_cookie+
	"; path=/" ;
}

function flatten_cookie()
{
	var s="";
	for(key in __the_cookie__ )
	{
		s+= key;
		s+= '=';
		s+= __the_cookie__[key];
		s+= '&';
	}
	return escape(s); 
}


function GET_COOKIE(c_name)
{
	var unflattened_cookie = unflatten_cookie();
	var pairs = unflattened_cookie.split('&');
	for(var i = 0;i < pairs.length;i++)
	{
		var ppair = pairs[i].split('=');
		__the_cookie__[ppair[0]]=ppair[1];
	}
	//alert("cookie "+c_name+" is "+__the_cookie__[c_name]);
	return __the_cookie__[c_name];
}

function unflatten_cookie()
{
	if (document.cookie.length>0)
	  {
		  c_start=document.cookie.indexOf(__the_cookie__.id+ "=");
		  if (c_start!=-1)
		    {
			    c_start=c_start + __the_cookie__.id.length+1;
			    c_end=document.cookie.indexOf(";",c_start);
			    if (c_end==-1) c_end=document.cookie.length;
				//alert(document.cookie.substring(c_start,c_end));
			    return unescape(document.cookie.substring(c_start,c_end));
		    }
	  }
	  return "";
}


function ERASE_COOKIE(name) 
{
	SET_COOKIE(name,null,-1);
}

function GET_URL_PARAM( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return null;
  else
    return results[1];
}

function RELOAD(anchor)
{
	SET_COOKIE('internal_reload',"yes");
	
	if(anchor != null)
		SET_COOKIE('fp_pending_anchor',anchor);

	document.location.href = document.location.href.replace(/#.*/, "");	
	

}

function GOTO_TOP(anchor)
{
	SET_COOKIE('cat_idx',0);
	RELOAD('the_top');
}



function ANCHOR(name)
{
	var a = document.createElement('a');
	a.setAttribute('name',name);
	a.name = name;
	a.id   = name;
	return a;
}


