var scroll = "";
var currentScroll = 0; // stores the index of the currently highlighted tab.
var clicked = -1; // int to see if a button is currently clicked. meant to disable hover. value set to index of currently clicked button onclick.
var indexedIDs = new Array(5), indexedPhone = new Array(5), indexedEmail = new Array(5), indexedLandID = new Array(5), indexedLandFile = new Array(5), indexedTitle = new Array(5), indexedLandingURL = new Array(5); 
// above creates a five-element array to store IDs of each game in getinvitations.


// Variables that reach into form values
var elCountry = "0";  // Country selected
var elPhone = "";     // Phone number
var elAm21 = false;   // I am 21 years of age
var elName = "";      // Captured name
var myCountry = "0";  // No country has been selected yet
var myPhone = "";     // No phone number has been selected yet
var myAm21 = false;   // Have not checked the "I am 21" box
var myName = "";      // My name
var srvConfig = 0;    // Server's contest configuration
var displayMode = "unknown"; // Will be "icons" or "form"
var pageMode = "radio";// 'radio', 'landing' or 'prelanding'.
var countryOptions = ""; //need this to create a list of <options> later for the forms.
var phone_number = "", gsn_email_address = "", pagetitle = "", landingID = "", landingFile = ""; //set a variable to be passed to the PHP pages for phone games.
var popupSpecs = new Array("","","","587:740","617:820","617:820","617:820"); //popup variables for each game with a pop-up page. format: width:height
var gamePop = false; // container to hold the popup window for captcash and gsi.

function getOnAir() {
	var rand = Math.random();
	var onAirIndicator = "";
	var recheck = 0; //recheck has to be global.
	$.ajax({url: '/radio/getinvitations.php?rnd='+rand, type: 'GET', success: function(parseOnAirValues) {
		$('nextshow',parseOnAirValues).each(function(values) {
			what = $(this).find("what").text();
			wait = $(this).find("wait").text(); // unused unless countdown clock is implemented.
			recheck = $(this).find("recheck").text();
			if (what == "showing" || what == "tail") { //we have a live show or are *probably* off-air but not yet sure.
				onAirIndicator = '<img src="/dynamic/images/radio/radioonair.png" alt="GSN Radio is On the Air" width="122" height="43" />';
			} else {
				if (what == "comingup") { //not showing
					// not strictly necessary to the code at present but might be if the countdown clock is ever re-implemented.
				} else {
					// again, not used by this version but this clause will fire if there is an error or returncode of "reset" 
				}
				onAirIndicator = '';
			}
		});
		$("#radio_counter").html(onAirIndicator);
		t = setTimeout('getOnAir()',(recheck*1000));
	}});
}

function populateContests() {
		//now attempting to build the wild contest rotator. 
	var contestsTabs = "", contestsBigImages = "", contestsRadioImages = "";
	$.ajax({url: '/radio/getinvitations.php', type: 'GET', success: function(parseOnAirValues) {
		$('drawing',parseOnAirValues).each(function(values) {
			gsnid = $(this).find("gsnid").text(); // big old block to get every child of the drawing node.
			ctitle = $(this).find("title").text();
			cdescription = $(this).find("description").text();
			rulesurl = $(this).find("rulesurl").text();
			tcurl = $(this).find("tcurl").text();
			imgbuttonid = $(this).find("imgbuttonid").text();
			imgbuttonfile = $(this).find("imgbuttonfile").text();
			imgradioid = $(this).find("imgradioid").text();
			imgradiofile = $(this).find("imgradiofile").text();
			imgmainid = $(this).find("imgmainid").text();
			imgmainfile = $(this).find("imgmainfile").text(); // end children of drawing node.
			if (ctitle.indexOf('Marquis Game') > 0) { //we want to split up and reconfigure the game title if Marquis Game exists in the string.
				var startMarquisString = ctitle.indexOf('Marquis Game');
				var maintitle = ctitle.substring(0,startMarquisString);
				var subtitle = '<br/><span class="marquis_sub">'+ctitle.substring(startMarquisString)+'</span>';
				var fulltitle = maintitle+subtitle;
			} else {
				var fulltitle = ctitle;
			}
			contestsTabs += '<a href="" onClick="return false;" class="radio_contest_button loadform"><img src="/radio/displayImage.php?image_id='+imgbuttonid+'&image_file='+imgbuttonfile+'" height="35" width="48"><span>'+fulltitle+'</span></a>\n';
			contestsBigImages += '<div class="radio_contests_active_inside loadform"><img src="/radio/displayImage.php?image_id='+imgmainid+'&image_file='+imgmainfile+'" alt="'+ctitle+'"></div>\n';
			contestsRadioImages += '<div class="radio_player_active_inside loadform"><img src="/radio/displayImage.php?image_id='+imgradioid+'&image_file='+imgradiofile+'" alt="'+ctitle+'"></div>\n';
			for (aPos=0;aPos<10;aPos++) {
				var aValue = indexedIDs[aPos];
				if (typeof aValue == "undefined") {
					indexedIDs[aPos] = gsnid;
					indexedPhone[aPos] = "";
					indexedEmail[aPos] = "";
					indexedLandID[aPos] = "";
					indexedLandFile[aPos] = "";
					indexedTitle[aPos] = ctitle;
					//alert(indexedIDs[aPos]);
					break;
				}
			}
		});
		$('game',parseOnAirValues).each(function(values) {
			gameid = $(this).find("gameid").text(); // big old block to get every child of the game node.
			gtitle = $(this).find("title").text();
			landingurl = $(this).find("landingurl").text();
			phone = $(this).find("phone").text();
			email = $(this).find("email").text();
			imgbuttonid = $(this).find("imgbuttonid").text();
			imgbuttonfile = $(this).find("imgbuttonfile").text();
			imgradioid = $(this).find("imgradioid").text();
			imgradiofile = $(this).find("imgradiofile").text();
			imgmainid = $(this).find("imgmainid").text();
			imgmainfile = $(this).find("imgmainfile").text();
			imglandid = $(this).find("imglandingid").text();
			imglandfile = $(this).find("imglandingfile").text();
			gametype = $(this).find("gametype").text(); // end children of game node.
			contestsTabs += '<a href="" onClick="return false;" class="radio_contest_button noloadform"><img src="/radio/displayImage.php?image_id='+imgbuttonid+'&image_file='+imgbuttonfile+'" height="35" width="48"><span>'+gtitle+'</span></a>\n';
			contestsBigImages += '<div class="radio_contests_active_inside noloadform"><a href="#"><img src="/radio/displayImage.php?image_id='+imgmainid+'&image_file='+imgmainfile+'" alt="'+gtitle+'"></a></div>\n';
			contestsRadioImages += '<div class="radio_player_active_inside noloadform"><a href="#"><img src="/radio/displayImage.php?image_id='+imgradioid+'&image_file='+imgradiofile+'" alt="'+gtitle+'"></a></div>\n';
			for (aPos=0;aPos<10;aPos++) {
				var aValue = indexedIDs[aPos];
				if (typeof aValue == "undefined") {
					indexedIDs[aPos] = gameid;
					indexedPhone[aPos] = phone;
					indexedEmail[aPos] = email;
					indexedLandID[aPos] = imglandid;
					indexedLandFile[aPos] = imglandfile;
					indexedTitle[aPos] = gtitle;
					indexedLandingURL[aPos] = landingurl;
					break;
				}
			}
		});

		//bop in the button HTML.
		$('div#radio_contests_toolbar').append(contestsTabs);
		$('div#radio_contests_active').append(contestsBigImages);
		$('div#radio_player_active').append(contestsRadioImages);

		//hover state functions for all buttons
		$('a.radio_contest_button').hover(function() {
			scroll = stopscrolltabs();
			if (clicked >= 0) { // we have a clicked button, so we shouldn't reset its mouseover, just all others. this is just a cleanup function to make sure we don't get lingering hover states.
				$('a.radio_contest_button:lt('+clicked+')').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
				$('a.radio_contest_button:gt('+clicked+')').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
			} else {
				$('a.radio_contest_button').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'}); //resets state for all five tabs.
			}
			$(this).css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
			var index = $("a.radio_contest_button").index(this);
			if (clicked < 0) {
				$("div.radio_contests_active_inside:lt("+index+")").hide();
				$("div.radio_contests_active_inside:gt("+index+")").hide();
				$("div.radio_contests_active_inside:eq("+index+")").show();
			}
			}, function() {
			$(this).css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
			var index = $("a.radio_contest_button").index(this);
			if (clicked < 0) {
				scroll = setTimeout("scrolltabs("+index+")",5000);
			}
			currentScroll = index;
			}
		);

		//click state functions for all tab-buttons
		$('a.loadform').click(function() { 
			scroll = stopscrolltabs();
			var index = $("a.radio_contest_button").index(this);
			$(this).css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
			$('a.radio_contest_button:lt('+index+')').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
			$('a.radio_contest_button:gt('+index+')').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
			$("div.radio_contests_active_inside:lt("+index+")").hide();
			$("div.radio_contests_active_inside:gt("+index+")").hide();
			$("div.radio_contests_active_inside:eq("+index+")").show();
			$("div#radio_tile").html('');
			$("div#radio_tile_sub").html('');
			load_form(indexedIDs[index], "", "");
			$('div#radio_form').show();
			//$('div#radio_tile_sub').show();
			/*$(this).hover(function() {
				scroll = stopscrolltabs();
				}, function() {
				$(this).css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
				}
			);*/
			clicked = index;
			return false;
			}
		);

		$('a.noloadform').click(function() { 
			scroll = stopscrolltabs();
			var index = $("a.radio_contest_button").index(this);
			$(this).css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
			$('a.radio_contest_button:lt('+index+')').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
			$('a.radio_contest_button:gt('+index+')').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
			$("div.radio_contests_active_inside:lt("+index+")").hide();
			$("div.radio_contests_active_inside:gt("+index+")").hide();
			$("div.radio_contests_active_inside:eq("+index+")").show();
			$("div#radio_tile").html('');
			$("div#radio_tile_sub").html('');
			$('div#radio_form').hide();
			$('div#radio_tile_sub').hide();
			$(this).hover(function() {
				scroll = stopscrolltabs();
				}, function() {
				$(this).css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
				}
			);
			clicked = index;
			gamePopUp(indexedLandingURL[clicked]);
			
			//alert("clicked "+clicked);
			return false;
			}
		);
		
		//click state functions for player images
		$('div.radio_contests_active_inside').click(function() {
			scroll = stopscrolltabs();
			var index = $("div.radio_contests_active_inside").index(this);
			clicked = index;
			if($(this).find('a').length <= 0 ) { // if we've streamed in a link, we should open the link, NOT try to load a form.
				$("div#radio_tile").html('');
				$("div#radio_tile_sub").html('');
				$("div.radio_player_active_inside").hide();
				load_form(indexedIDs[index], "", "");
				$('div#radio_form').show();
				//$('div#radio_tile_sub').show();
				//$('div#banner_txt').html('Enter to Play Now! <a href="" class="contestrules" onClick="popUp(\'/cgi/disclaimer/disclaimer_full.html?name=GSNRadioRules\');return false;">Rules for Entry</a>');
			} else {
				gamePopUp(indexedLandingURL[clicked]);
				return false;
			}
			}
		);
		
		//click state functions for player images
		$('div.radio_player_active_inside').click(function() {
			scroll = stopscrolltabs();
			var index = $("div.radio_player_active_inside").index(this);
			clicked = index;
			if($(this).find('a').length <= 0 ) { // if we've streamed in a link, we should open the link, NOT try to load a form.
				$("div#radio_tile").html('');
				$("div#radio_tile_sub").html('');
				$("div.radio_player_active_inside").hide();
				load_form(indexedIDs[index], "", "");
				$('div#radio_form').show();
				$('div#radio_tile_sub').show();
				$('div#banner_txt').html('Enter to Play Now! <a href="" class="contestrules" onClick="popUp(\'/cgi/disclaimer/disclaimer_full.html?name=GSNRadioRules\');return false;">Rules for Entry</a>');
			} else {
				gamePopUp(indexedLandingURL[clicked]);
				return false;
			}
			}
		);

		//click state functions for player scroll arrows
		$('div#left_arrow > img').click(function() {
			//this should do -1, because it's left.
			scroll = stopscrolltabs();
			var index = -1;
			for (vis=0;vis<$('div.radio_player_active_inside').length;vis++) {
				if ($("div.radio_player_active_inside:eq("+vis+")").is(':visible')) {
					index = vis;
					break;
				}
			}
			if (index == 0) {
				index = $('div.radio_player_active_inside').length-1;
			} else if (index < 0) {
				index= 0;
			} else {
				index--;
			}
			clicked = index;
			$("div#radio_tile").html('');
			$("div#radio_tile_sub").html('');
			$("div#radio_form").hide();
			$("div.radio_player_active_inside:lt("+index+")").hide();
			$("div.radio_player_active_inside:gt("+index+")").hide();
			$("div.radio_player_active_inside:eq("+index+")").show();
			$('div#banner_txt').html('Enter to Play Now! <a href="" onClick="popUp(\'/cgi/disclaimer/disclaimer_full.html?name=GSNRadioRules\');return false;">Rules for Entry</a>');
			return false;
			}
		);
		$('div#right_arrow > img').click(function() {
			//this should do +1, because it's right.
			scroll = stopscrolltabs();
			var index = -1;
			for (vis=0;vis<$('div.radio_player_active_inside').length;vis++) {
				if ($("div.radio_player_active_inside:eq("+vis+")").is(':visible')) {
					index = vis;
					break;
				}
			}
			if (index == $('div.radio_player_active_inside').length-1) {
				index = 0;
			} else {
				index++;
			}
			clicked = index;
			$("div#radio_tile").html('');
			$("div#radio_tile_sub").html('');
			$("div#radio_form").hide();
			$("div.radio_player_active_inside:lt("+index+")").hide();
			$("div.radio_player_active_inside:gt("+index+")").hide();
			$("div.radio_player_active_inside:eq("+index+")").show();
			$('div#banner_txt').html('Enter to Play Now! <a href="" onClick="popUp(\'/cgi/disclaimer/disclaimer_full.html?name=GSNRadioRules\');return false;">Rules for Entry</a>');
			return false;
			}
		);

		//force hover state upon first button for initial load.
		$('a.radio_contest_button:first').css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
		$('a.radio_contest_button:gt(0)').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
		$('div.radio_contests_active_inside:gt(0)').hide();
		$('div#radio_form').hide();
		$('div#radio_tile_sub').hide();
		$('div.radio_contests_active_inside:first').show();
		//impact the player frame too even if it's not showing.
		$('div.radio_player_active_inside:gt(0)').hide();
		$('div.radio_player_active_inside:first').show();
	}});
	$('#radio_contests_loading').hide();
	$('#radio_contests_active').show();
	$('#radio_contests_toolbar').show();
}

var gamePopup = "";
function gamePopUp(landingURL) {
	if (clicked >= 0) {
		var index = clicked;
	} else {
		var index = currentScroll;
	}
	//alert(index);
	phone_number = indexedPhone[index];
	gsn_email_address = indexedEmail[index];
	pagetitle = indexedTitle[index];
	landingID = indexedLandID[index];
	landingFile = indexedLandFile[index];
	var landingPopSpecs = popupSpecs[index].split(":");
	var landingPopWidth = landingPopSpecs[0];
	var landingPopHeight = landingPopSpecs[1];
	if ($.browser.msie)	{
		//IE calcs the size differently, should add 25px to each to account for scrollbars.
		landingPopHeight = parseInt(landingPopHeight)+25;
		landingPopWidth = parseInt(landingPopWidth)+25;
	}
	//alert("lPW="+landingPopWidth+" - lPH="+landingPopHeight);
	gamePop = window.open(landingURL, 'gamePopup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width='+landingPopWidth+',height='+landingPopHeight+',left = 340,top = 262');
	gamePop.resizeTo(landingPopWidth,landingPopHeight);
	gamePop.focus();
}

function scrolltabs(passedInt) {
	if (clicked != true || clicked < 0) { // should change nothing if a button is clicked, so, if this condition is true we can proceed.
		if (typeof passedInt == "undefined") {
			//we have no passedInt, therefore we are initializing the scroller.
			var passedInt = 0;
		}
		if (pageMode != "radio") {
			var $all = $('a.radio_contest_button');
		} else {
			var $all = $('div.radio_player_active_inside');
		}
		if (passedInt < ($all.length-1)) {
			var nextInt = passedInt+1;
		} else {
			var nextInt = 0;
		}
		$('a.radio_contest_button:eq('+passedInt+')').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
		$('a.radio_contest_button:eq('+nextInt+')').css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
		//$('div.radio_contests_active_inside:eq('+passedInt+')').hide();
		$('div.radio_contests_active_inside:gt('+nextInt+')').hide();
		$('div.radio_contests_active_inside:lt('+nextInt+')').hide();
		if ($('div#radio_form').is(':hidden')) {
			$('div.radio_contests_active_inside:eq('+nextInt+')').show();
		}
//		alert(passedInt);
		$('div.radio_player_active_inside:lt('+nextInt+')').hide();
		$('div.radio_player_active_inside:gt('+nextInt+')').hide();
		$('div.radio_player_active_inside:eq('+nextInt+')').show();
		scroll = clearTimeout(scroll);
		scroll = setTimeout("scrolltabs("+nextInt+")",5000);
		currentScroll = passedInt;
	}
}
function stopscrolltabs() {
	clearTimeout(scroll);
}


// This function loads the contest entry form
function load_form(contest, error_text, red_line) {

  // first thing to do is to hide everything currently living in the div.
  $('div.radio_contests_active_inside').hide();

  // Indicate that we're asking the server for info about contests
  displayMode = "form";

  // Pick up some additional information about the contest in question
  var cdescr = "unknown";
  var crules = "unknown";
  var ctc = "unknown";
  var ctitle = "unknown";
  var cimg = "unknown";
  var cimgfile = "unknown";
  
  //replacing old forks for IE/Fox with jQuery ajax call (to separate from getOnAir's call)
  $.ajax({async: false, url: '/radio/getinvitations.php', type: 'GET', success: function(generateFormValues) {
		$('drawing',generateFormValues).each(function(formValues) {
			if (($(this).find("gsnid").text() == contest) || ($(this).find("gameid").text() == contest)) { //allows one clause to grab relevant data.
				// Yes. Pluck out some additional fields.
				ctitle = $(this).find("title").text();
				cdescr = $(this).find("description").text();
				crules = $(this).find("rulesurl").text();
				ctc = $(this).find("tcurl").text();
				cimg = $(this).find("imgbuttonid").text();
				cimgfile = $(this).find("imgbuttonfile").text();
				return false;
			}
		});
		//create options, then end the select, move on to phone
		$('country',generateFormValues).each(function(countryValues) {
			name = $(this).find("name").text();
			itucode = $(this).find("itu-code").text();
			gsnCID = $(this).find("gsn-id").text();
			countryOptions += '\n\t\t\t\t<option value="'+itucode+':'+gsnCID+'" ';
			if (myCountry == itucode+':'+gsnCID) {
				//we should tick this as selected.
				countryOptions += 'selected="selected"';
			}
			countryOptions += '>'+name+'</option>';
		});
	}});

 
  // Next, replace the overall radio tile with specifics about this competition
  var $m = $('div#radio_tile');
  
  //clear out $m to prevent overdrawing.
  $m.html('');

  if ($m != 0) {
    var d, i, f, b, a, t, e, r, k, s, o, n, c, tb, d2, d3;

	if (pageMode != "radio") {
		// due to V2 design of radio, can't fit the banner INSIDE here. So we can't write it, have to handle it all outside.
		$m.append('\n\t<div id="banner" class="banner">\n\t\t<div id="banner_txt" class="banner_txt">Enter Your Information Below</div>\n\t</div>');
	}
	if (pageMode == 'landing') {
		$m.append('<div id="form_tile" class="form_onair"><img class="form_promo" src="/radio/spacer.gif" style="background-image: url(\'/radio/displayImage.php?image_id='+cimg+'&image_file='+cimgfile+'\');" /></div>');
	} else {
		//$m.append('<div id="form_tile" class="form_onair"></div>');
	}
	  
    // Shall we put out an error here?
    if (error_text != "") {
      var ediv;
      // Yes. Get a red divider out
	  $m.append('<div id="form_error" class="form_error"><b>Entry Error<br/>'+error_text+'. </b></div>');

    } else if ( pageMode == "prelanding" ) {

	  // coming soon page form top
	  $m.append('<h3>DON\'T WAIT!</h3><h3>ENTER NOW TO PLAY!</h3>');
      
    } else {
	  // wrap the next text in a span so we can position it better.
	  var $descString = '<div id="radio_title_desc">';
      // Get a bolded version of the game in there
	  $descString += '<b>'+ctitle+'</b>';

      // Next we need the rules of entry
      if (pageMode == "radio") {
         //$descString += ' - Learn ';
      } else {
		 $descString += '<br/>'+cdescr+' <br/>';
      }
	  $descString += '<br/></div>';
	  $m.append($descString); 
    }

    // Get a blank line in here (terminate the first one and then an extra)
    if (pageMode == "radio" && error_text == "" )
    {
	  //hide this break if Entry Error is displayed
	  //$m.append('<br/>');
    }


    // At this point we need a form for data entry
	var $formBuilder = '<form id="submission">';

	 // Now we need a table to organize this.
	$table1 = '<table id="table1" class="country_phone">\n\t<tbody>\n\t\t<tr ';
	if (red_line == "name") {
      $table1 += 'class="redbold"';
    }
	$table1 += '>\n\t\t\t<td align="right"><b>\u00a0Name:\u00a0</b><td align="left"><input id="submit_name" type="text" size="16" maxwidth="32" ';
	if (red_line == "name") {
      $table1 += 'class="phone_nr_error"';
    } else {
      $table1 += 'class="phone_nr_normal"';
	}
	//finish off "name" and begin "country"
	$table1 += ' value="'+myName+'"></td>\n\t\t</tr>\n\t\t<tr ';
	if (red_line == "country") {
      $table1 += 'class="redbold"';
    }
	$table1 += '>\n\t\t\t<td align="right"><b>\u00a0Country:\u00a0</b><td align="left"><select ';
	if (red_line == "country") {
      $table1 += 'class="select_country_error"';
    } else {
      $table1 += 'class="select_country_normal"';
	}
	$table1 += '  id="submit_country" >';
	//made default option, because this does not live in the XML/DB.
	$table1 += '<option value="0" ';
	if (myCountry == "0") {
		$table1 += 'selected="selected"';
	}
	$table1 += '>Select Your Country</option>';
	

	$table1 += countryOptions;

	$table1 += '\n\t\t\t</select>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr ';
	if (red_line == "phone") {
      $table1 += 'class="redbold"';
    }
	$table1 += '>\n\t\t\t<td align="right"><b>\u00a0Phone:\u00a0</b></td>\n\t\t\t<td align="left"><input id="submit_phone" type="text" size="16" maxwidth="32" ';
	if (red_line == "phone") {
      $table1 += 'class="phone_nr_error"';
    } else {
      $table1 += 'class="phone_nr_normal"';
	}
	//finish off "phone" and shut down table 1 with a trailing linebreak.
	$table1 += ' value="'+myPhone+'"></td>\n\t\t</tr>\n\t</tbody>\n</table><br/>';
	$formBuilder += $table1;

	//new table, this one manages the age checking content.
	$table2 = '<table class="years21" id="table2">\n\t<tbody>\n\t\t<tr ';
	if (red_line == "am21") {
      $table2 += 'class="redbold"';
    }
	$table2 += '>\n\t\t\t<td align="right"><input id="submit_age" type="checkbox" ';
	if (myAm21 == true) {
	  $table2 += 'checked="checked"';
    }
	$table2 += '</td>\n\t\t\t<td align="left" class="checkbox_txt">I am at least 21 years old and agree to the <a href="" onClick="popUp(\'/cgi/disclaimer/disclaimer_full.html?name=GSNRadioRules\');return false;">Official Rules</a> and <a href="" onClick="popUp(\'/cgi/corporate/privacy.html\');return false;">Privacy Policy</a>.</td>\n\t\t</tr>';
	$table2 += '\n\t</tbody>\n</table>';
	$formBuilder += $table2;

	// Are we in radio mode?
	$buttonrow = '';
    if ( pageMode == "radio" || pageMode == "landing" ) {
		$buttonrow += '<img class="enter_button" src="/radio/but_enter.gif" onClick="validate_form('+contest+');" />';
		$buttonrow += '<img class="cancel_button" src="/radio/but_cancel.gif" />';
	} else {
		// this is the coming soon display
		$buttonrow += '<img class="enter_button_center" src="but_enter_comingsoon.gif" onClick="validate_form('+contest+');" />';
		$buttonrow += '<a href="" class="form_faq_link" onClick="popUp(\'faq.html?'+pageMode+'\');return false;">Learn More About GSN Radio</a>';
	}
	$formBuilder += $buttonrow;
	$m.append($formBuilder);
  }
  $('img.cancel_button').click(function() {
	$('a.radio_contest_button:first').css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
	$('a.radio_contest_button:gt(0)').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
	$('div.radio_contests_active_inside:gt(0)').hide();
	$('div.radio_player_active_inside:gt(0)').hide();
	$('div#radio_form').hide();
	$('div#radio_tile_sub').hide();
	$('div.radio_contests_active_inside:first').show();
	$('div.radio_player_active_inside:first').show();
	clicked = -1;
	scroll = stopscrolltabs();
	scroll = scrolltabs(3); // 3 is the final tab, so we can restart at 0 like good kittens.
	}
  );
}

// This function validates form values
function validate_form(contest)
{
    var phone_digs = 0;
    var modPhone;
    var modName;
    var firstDigit = true;
    var spage = "/radio/dsubmit.php";
    var position = 0;
    var was_blank = 0;

    // Capture what the user entered as selected country
	myCountry = $("select#submit_country").val();

    // Get the phone number
	myPhone = $("input#submit_phone").val();

    // And then what the user selected for being 21 or not
	myAm21 = $("input#submit_age").attr('checked')?1:0;

    // My name
	myName = $("input#submit_name").val();
					
    // Verify the name
    modName = "";
    for (i=0; i<myName.length; i++) {
      if (("abcdefghijklmnopqrstuvwxyz- ").indexOf(myName.charAt(i).toLowerCase()) == -1) {
        return (load_form(contest, "Please use only A-Z and Space in name", "name"));
      }
      var id = ("abcdefghijklmnopqrstuvwxyz").indexOf(myName.charAt(i).toLowerCase());
      if (id == -1) {
        switch (position) {
          case 0:
          {
            break;
          }
          case 1:
          {
            was_blank = 1;
            break;
          }
        }
      } else {
        switch (position) {
          case 0:
          {
            modName += myName.charAt(i);
            position = 1;
            was_blank = 0;
            break;
          }
          case 1:
          {
            if (was_blank != 0) {
              modName += "+"; // Space in how we encode in URL
              was_blank = 0;
            }
            modName += myName.charAt(i);
            break;
          }
        }
      }
    }

    // Make sure name string is not too long
    if (modName.length > 32) {
      modName = modName.slice(0, 32);
    }
    
    // Verify the country.
    if (myCountry == "0") {
      return (load_form(contest, "Please select country", "country"));
    }

    // Check the phone number
    modPhone = "";
    for (i=0; i<myPhone.length; i++) {
      if (("0123456789/[].-()").indexOf(myPhone.charAt(i)) == -1) {
        return (load_form(contest, "Please enter a valid phone #", "phone"));
      }
      if (("0123456789").indexOf(myPhone.charAt(i)) != -1) {
        if (firstDigit) {
          if (myPhone.charAt(i) != '0') {
            modPhone += myPhone.charAt(i);
            phone_digs++;
          }
          firstDigit = false;
        } else {
          modPhone += myPhone.charAt(i);
          phone_digs++;
        }
      }
    }
    if (phone_digs < 6) {
      return (load_form(contest, "Please enter a valid phone number", "phone"));
    }
				if ( phone_digs < 10 && ( $("select#submit_country").text() == "USA" || $("select#submit_country").text() == "United States" || $("select#submit_country").text() == "United States of America" ) ) {
				  return (load_form(contest, "Phone number must include Area Code", "phone"));
				}

    // Verify the 21 year box
    if (myAm21 == false) {
      return (load_form(contest, "You must be 21 or older", "am21"));
    }

    // Prepare a submission URL
    spage += ("?c=" + contest);   // The contest
    spage += ("&n=" + modPhone);  // The phone number
    spage += ("&f=" + modName);  // The optional first name
    spage += ("&y=" + myCountry); // GSN country index
    spage += ("&l=" + pageMode); // 'radio' or 'landing'
    spage += ("&r=" + Math.random()); // Ensure our response is 'current'


    // Submit this.
	$.ajax({url: spage, type: 'GET', success: function(spage_response) {
		var csts;
		var contest;
		var csts;
		var cmsg;
		var chdr;
		var txtmsg;
		var divver;
		$('entry-submission',spage_response).each(function(formValues) {
			contest = $(this).find("gsnid").text();
			ctitle = $(this).find("title").text();
			csts = $(this).find("submission-status").text();
			chdr = $(this).find("submission-heading").text();
			cmsg = $(this).find("submission-message").text();
		});
    // Dispatch on response code
    divver = document.createElement("div");
    txtmsg = document.createElement("b");
    divver.appendChild(txtmsg);
    divbody = document.createElement("div");
    divver.appendChild(divbody);
    switch (csts) {
      case 'OK':
      {

        // Build up a positive confirmation
        divver.setAttribute("class", "ok_response_header");
        divver.setAttribute("className", "ok_response_header"); // IE
        txtmsg.appendChild(document.createTextNode(chdr));
        divbody.setAttribute("class", "ok_response_text");
        divbody.setAttribute("className", "ok_response_text"); // IE
        divbody.appendChild(document.createElement("br"));
        divbody.appendChild(document.createElement("br"));
        divbody.appendChild(document.createTextNode(cmsg));

        // And get it out.
        display_error_lowlevel(divver, contest);
        break;
      }
      case 'WARNING':
      {

        // Build up a warning
        divver.setAttribute("class", "warning_response_header");
        divver.setAttribute("className", "warning_response_header"); // IE
        txtmsg.appendChild(document.createTextNode(chdr));
        divbody.setAttribute("class", "warning_response_text");
        divbody.setAttribute("className", "warning_response_text"); // IE
        divbody.appendChild(document.createElement("br"));
        divbody.appendChild(document.createTextNode(cmsg));
        divbody.appendChild(document.createElement("br"));
        divbody.appendChild(document.createElement("br"));
        divbody.appendChild(document.createTextNode("Please try again later!"));

        // And get it out.
        display_error_lowlevel(divver, contest);
        break;
      }
    }
	}});

    // Done
    return;
}

// Display a processing error using element input
function display_error_lowlevel(toappend, contest)
{

  var m = document.getElementById("radio_tile");
  if (m != 0) {
    var d, i, f, d2, d3;

    // Create the overall divider
    d = document.createElement("div");
    d.id = "radio_tile";
    d.setAttribute("class", "promoloc");
    d.setAttribute("className", "promoloc"); // IE

	if (pageMode != "radio") { //don't do another banner if we're in radio, we can't fit it.
		// Get the header background out
		d2 = document.createElement("div");
		d2.id = "banner";
		d2.setAttribute("class", "banner");
		d2.setAttribute("className", "banner"); // IE
		d.appendChild(d2);
		

		// Next, lay out the text itself
		d3 = document.createElement("div");
		d3.id = "banner_txt";
		d3.setAttribute("class", "banner_txt");
		d3.setAttribute("className", "banner_txt"); // IE
		d2.appendChild(d3);
		d3.appendChild(document.createTextNode("Enter your information below"));
	}

    // Create an area into which we can stuff the error into
    f = document.createElement("div");
    f.id = "error_tile";
    f.setAttribute("class", "error_tile");
    f.setAttribute("className", "error_tile"); // IE
    d.appendChild(f);

    // Append the error message to this.
    f.appendChild(toappend);

    // Get an OK  button up
    i = document.createElement("img");
    i.setAttribute("class", "ok_button");
    i.setAttribute("className", "ok_button"); // IE
    i.setAttribute("src", "/radio/but_ok.gif");
    f.appendChild(i);

    // Done. Swap them.
    m.parentNode.replaceChild(d, m);
	$('img.ok_button').click(function() {
		$('a.radio_contest_button:first').css({backgroundImage: 'url(/dynamic/images/radio/promo_tab_on.gif)', backgroundRepeat: 'no-repeat', color: 'black', textDecoration: 'none'});
		$('a.radio_contest_button:gt(0)').css({backgroundImage: 'none', color: 'white', textDecoration: 'none'});
		$('div.radio_contests_active_inside:gt(0)').hide();
		$('div.radio_player_active_inside:gt(0)').hide();
		$('div#radio_form').hide();
		$('div#radio_tile_sub').hide();
		$('div.radio_contests_active_inside:first').show();
		$('div.radio_player_active_inside:first').show();
		clicked = -1;
		scroll = stopscrolltabs();
		scroll = scrolltabs(3); // 3 is the final tab, so we can restart at 0 like good kittens.
	}
  );
  }
}

// Get the value of a specific argument
function get_argument(argname, defval)
{

  // Pick up the URL that invoked us
  var j = window.location.search;

  // Break this up into an array of argname/value pairs
  var args = j.substr(1, j.length - 1).split("&");

  // Look for the one we care about
  var l;
  var argval = defval;
  for (l=0; l<args.length; l++) {
    var argument = args[l].split("=");
    if (argument[0] == argname) {
      argval = argument[1];
      break;
    }
  }

  // Done, back to caller
  return (argval);
}

function set_pagemode(mode)
{
  // Set the page mode
  pageMode = mode;
}
