// Some global variables
var characters = ['baker','hassay','corrion','leggett','hartsock','desola','allen','garnett','courtland','obrieski','rivas','risner','cole','eisenhower'];
var current_character = 0;
var weapons_timeout = null;

// Called on page load, useful for shoehorning content in, starting timed effects
function after_ajax(page) {         
	insert_esrb_logo('doubletime', page, 144, 78, true);

  //Make sure the left menu is black
  $('menu').addClassName('feral_blackmenu');
  

  if ($('bia_menu')) {
    set_up_menu();
  }
	
	switch(page) {
    case 'home': 
    case null: 
    case '': 
      $$('select').invoke('observe','change',validate_age.bindAsEventListener(this));
      break;
    case 'story':
      play_story_movie();
      break;
    case 'characters':
      set_up_characters();
      break;
    case 'weapons':
      set_up_weapons();
      break;
    case 'media':
      set_up_media();
      break;
  }
}

function set_up_menu() {
  ['story','characters','weapons','media','sysreqs','reviews'].each(function(page) {
    $('bia_menu_'+page).down('a').observe('click',function(event) {
      load_minisite_section("doubletime",page);
      Event.stop(event);
    });
  });
}

function play_story_movie() {
  var movie_player = new Element('object',{
    "CLASSID": "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B",
    "width": "356",
    "height": "198",
    "CODEBASE": "http://www.apple.com/qtactivex/qtplugin.cab"
  });
  
  var params = $H({
    src: "data/games/doubletime/images/story/video.mov",
    qtsrc: "video.mov",
    autoplay: "true",
    loop: "true",
    controller: "false"
  });  
  
  params.each(function(param) {
    movie_player.insert({
      bottom: new Element('param',{
        "name": param.key,
        "value": param.value
      })
    });
  });
  
  var movie_file = new Element('embed',{
    "src": "data/games/doubletime/images/story/video.mov",
    "qtsrc": "video.mov",
    "width": "356",
    "height": "198",
    "autoplay": "true",
    "loop": "true",
    "controller": "false",
    "pluginspage": "/quicktime/download/"
  });
  
  movie_player.insert({ bottom: movie_file });
  
  $('story_qt').update(movie_player);
}

function set_up_characters() {
  current_character = 0;
  $('characters_text_note').appear({duration: 0.5, queue: 'front'});
  $('characters_mugshot_baker').appear({duration: 0.5, queue: 'end'});
  $('characters_arrow_next').appear({duration: 0.3, queue: 'end'});
  $('characters_arrow_prev').observe('click',character_change.bindAsEventListener(this,-1));
  $('characters_arrow_next').observe('click',character_change.bindAsEventListener(this,1));
}

function character_change() {
  //Forwards or backwards? Arguments sent from the clicked element using bindAsEventListener
  var increment_value = $A(arguments)[1];
  
  //Keep track of where we are and where we're going
  var this_character = current_character;
  var next_character = current_character + increment_value;

  //Fade out the the current mugshot and biography
  $('characters_mugshot_'+characters[this_character]).fade({duration: 0.2, queue: 'front'});
  $('characters_'+characters[this_character]).fade({duration: 0.2, queue: 'end'});
  
  //Fade in the new mugshot and biography
  $('characters_'+characters[next_character]).appear({duration: 0.3, queue: 'end'});
  $('characters_mugshot_'+characters[next_character]).appear({duration: 0.8, queue: 'end'});
  
  //Catch up with ourselves 
  current_character = next_character;
  
  //Now to sort out the prev/next arrows. There are no queue positions for these
  // effects as we want them to run parallel with the others.

  //If we're at the beginning of the list, fade out the 'previous' arrow
  if (current_character == 0) {
    $('characters_arrow_prev').fade({duration: 0.2});
  } else if (!$('characters_arrow_prev').visible()) {
    //Otherwise, make sure it is visible
    $('characters_arrow_prev').appear({duration: 0.2});
  };

  //If we're at the end of the list, fade out the 'next' arrow
  if (current_character == (characters.length - 1)) {
    $('characters_arrow_next').fade({duration: 0.2});
  } else if (!$('characters_arrow_next').visible()) {
    //Otherwise, make sure it is visible
    $('characters_arrow_next').appear({duration: 0.2});
  };
  

}

function set_up_weapons() {
  var weapons = ['grenade','pistol','carbine','garand','boltaction','m1a1','bar','bazooka','browning'];

  weapons.each(function(weapon) {
    $('weapons_'+weapon).observe('mouseover',weapon_show_text.bindAsEventListener(this));
    $('weapons_'+weapon).observe('mouseout',weapon_revert_text.bindAsEventListener(this));
  });
}

function weapon_show_text(event) {
  //Stop the text revert timeout
  if (weapons_timeout) { clearTimeout(weapons_timeout); };
  
  //Find the weapon text that is currently visible and hide it.
  $('weapons_text_frame').childElements().find(function(weapon_text) { return weapon_text.visible(); }).hide();
  
  //Show the relevant weapon text (the 'event' var is brought in because we have used bindAsEventListener)
  var weapon = Event.element(event);
  $(weapon.identify()+'_text').show();
}

function weapon_revert_text(event,kill_switch) {
  //This code only runs if it hasn't been called in the previous half-a-second.
  if (kill_switch) {
    //Find the weapon text that is currently visible and hide it.
    $('weapons_text_frame').childElements().find(function(weapon_text) { return weapon_text.visible(); }).hide();

    //Show the default page text
    $('weapons_default_text').show();    
  } else {
    //Set this function to run properly in 500 milliseconds time.
    //If it is called again before the timer goes off, the timer is reset.
    if (weapons_timeout) { clearTimeout(weapons_timeout); };
    weapons_timeout = setTimeout("weapon_revert_text(null,true)",300);
  }

}

function set_up_media() {
  $$('.media_close_button').invoke('observe','click',close_media_popup_window.bindAsEventListener(this));
  $('media_overlay').observe('click',close_media_popup_window.bindAsEventListener(this,true));
  
  $('media_screenshots_label',
    'media_desktops_label',
    'media_trailer_label',
    'media_demo_label').invoke('observe','click',open_media_popup_window.bindAsEventListener(this));

  $$('.media_screen_cell img').invoke('observe','click',show_screenshot.bindAsEventListener(this));  
  $$('.media_desk_cell img').invoke('observe','click',choose_desktop.bindAsEventListener(this));  
  
}

function open_media_popup_window(event) {
  $('media_overlay').appear({duration: 0.4, from: 0.0, to: 0.7});
  var clicked_label_id = Event.element(event).identify();
  var window_to_show_id = clicked_label_id.substr(0,clicked_label_id.length - 6) + "_window";
  $(window_to_show_id).appear({duration: 0.4});
}

function close_media_popup_window(event) {
  //Find all the open windows
  var open_windows = $$('.media_popup_window').findAll(function(popup) { return popup.visible(); });
  
  //If the overlay was clicked...
  if ($A(arguments)[1]) {
    //Find all open windows + the overlay
    var windows_to_close = open_windows
    windows_to_close.push($('media_overlay'));
  } else {
    // Otherwise, work out which window the X button belonged to.
    var windows_to_close = new Array(Event.element(event).up());
    
    //If this is the only window open, close the overlay too.
    if (open_windows.size() < 2) {
      windows_to_close.push($('media_overlay'));
    };
  };
  
  // Close the windows
  windows_to_close.invoke('fade',{duration: 0.3});
}

function show_screenshot(event) {
  var clicked_thumbnail = Event.element(event);
  var required_image = clicked_thumbnail.readAttribute('src').split('/').last();
  $('media_fullscreen').writeAttribute({src: 'data/games/doubletime/images/media/screenshots/'+required_image});
  
  var caption = new Element('p').update(clicked_thumbnail.readAttribute('alt'));
  $('media_fullscreen_caption').update(caption);
  
  $('media_fullscreen_window').appear({duration: 0.4});
}

function choose_desktop(event) {
  var clicked_thumbnail = Event.element(event);
  var required_image = clicked_thumbnail.readAttribute('src');
  
  $('media_fulldesk_thumb').writeAttribute({src: required_image});
  
  var desktop_file_name = required_image.split('/').last();
  desktop_file_name = desktop_file_name.substr(0,desktop_file_name.length - 4);
  ['_1920','_1680','_1440','_1280'].each(function(res){
    $('media_desk'+res).writeAttribute({href: 'data/games/doubletime/images/media/desktops/' + desktop_file_name + res + '.jpg'});
  });

  $('media_fulldesk_window').appear({duration: 0.4});
}

function validate_age(event) {
  //Get form values
  var year_numeric = parseInt($F('year'));
	var year_index = $('year').selectedIndex;
	var month = $('month').selectedIndex;
	var day = $('day').selectedIndex;

  //If not all of the fields have been filled in, stop.
	if (year_index == 0 || month == 0 || day == 0) {
		return;
	}
  
  //Get error text
	if ($('home_age_error').innerText) {
	  var age_error = $('home_age_error').innerText;
	} else {
	  var age_error = $('home_age_error').textContent;
	};
  
  //Create date objects
  var their_date = new Date((year_numeric + 18), month, day);
  var today = new Date();
  
  //If they're not old enough, or the cookie has already been set...
  if ((today.getTime() - their_date.getTime()) < 0 || get_cookie('doubletime_mac_age') == 1) {
    //Set the cookie and inform the user
    set_cookie("doubletime_mac_age",1,1);
    alert(age_error);
  } else {
    //Otherwise, proceed to the site.
	// set_cookie("doubletime_mac_age",2,1);
    // load_minisite_section("doubletime","story");
	var loc = window.location.toString();
	window.location = "http://" + loc.split("/")[2] + "/?game=doubletime&subsection=story";
  }
}

function set_cookie(check_name,value,expire_days) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expire_days);
  document.cookie = check_name + "=" + escape(value) + ((expire_days == null) ? "" : ";expires=" + exdate.toGMTString());
}

function get_cookie(check_name) {
	// Function lifted from techpatterns.com
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	
	if (!b_cookie_found) { return null; }
}
