// some browser sniffing for shithouse Netscape
if (navigator.appName == "Netscape") {
	var nn = true;
	if (parseInt(navigator.appVersion) == 4) {
		var nn4 = true;
	}
}

// declare global vars
loaded = false;
xMousePos = 0;
yMousePos = 0;
xMousePosMax = 0;
yMousePosMax = 0;


// These start the count for which set of 5 (most recent, read, and commented)
// are displayed.

recent_show = 1;
read_show = 1;
commented_show = 1;


var cur_image_id = "";
var last_image_id = "";
var next_image_id = "";
var next_img_num = 0;
var prev_img_num = 0;
var img_num = 0;
var grp_siz = 0;
var left = 0;
var my_top = 0;


// cool cross-platform object reference getter
function getObj(name) {
  if (document.getElementById) {
  	//alert(name);
    this.obj = document.getElementById(name);
    this.style = document.getElementById(name).style;
    this.id = document.getElementById(name).id;
  }
  else if (document.all) {
    this.obj = document.all[name];
    this.style = document.all[name].style;
    this.id = document.all[name].id;    
  }
  else if (document.layers) {
    this.obj = document.layers[name];
    this.style = document.layers[name].style;
    this.id = document.layers[name].id;

  }
}

// set up mouse position capture on mouse moves (across browsers).
if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}

// capture mouse position and max position (across browsers)
function captureMousePosition(e) {
    if (document.layers) {
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
        ceiling = window.pageYOffset;
    } else if (document.all) {
        xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight+document.body.scrollTop;
        ceiling = window.document.body.scrollTop;
    } else if (document.getElementById) {
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
        ceiling = window.pageYOffset;
    }
}


// Image positioner and shower.

function showImg ( myDiv, width, height ) {

	// Find dimensions of image (if in cache) using JQuery - thus obviating
	// effing need to manually enter them going forward.
	
	cur_image = myDiv.id.replace("Div", "Img");
		
	if ( $("#'+cur_image+'").height() ) {

		eval ( 'width = $("#'+cur_image+'").width() ');
		eval ( 'height = $("#'+cur_image+'").height() ');
	
	}

	myDiv.style.visibility = "visible";
	//left = (xMousePosMax/2) - (width/2);
	left = xMousePos - (width/2) + 40;
	my_top = yMousePos - (height/2);
	if ((left + width) > xMousePosMax) left = xMousePosMax - width - 20;
	if (left < 80) left = 80;
	if (my_top < ceiling) my_top = ceiling + 40;
	if ((my_top + height) > yMousePosMax) my_top = yMousePosMax - height - 40;


	// If 5th and 6th args passed in, these will be hardcoded top and left
	// from previous image of image group

	if ( showImg.arguments[4] ) {

		left = showImg.arguments[4];
		my_top = showImg.arguments[5];
	
	}
	
	myDiv.style.left = left;
	myDiv.style.top = my_top;

	
	// Set default that flippers are not displayed.
	
	flippersDisplayed = false;
	
	
	// Now, see if this image is a member of an image group, with extra arg.
	// (For to flash up arrows ([no x closer for now].)

	if ( showImg.arguments[3] ) {
	

		// Pull out image number and size

		things_array = showImg.arguments[3].split(":");
		
		img_num = parseInt ( things_array[0] );
		
		grp_siz = parseInt ( things_array[1] );
		
		
		// Get some data we're going to need for either or both flippers.
		
		arrows_top = my_top + height - 28;		

		cur_image_id = myDiv.id.replace("Div", "");

		index_of_cur = jQuery.inArray ( cur_image_id, all_images );		// no fucking indexOf function in JS!


		// Unbind any previous click functions from the arrows (so they don't pile up).
		
		$("#left_arrow_link").unbind('click');
		$("#right_arrow_link").unbind('click');


		// Now - if there should be a left flipper.

		if ( img_num > 1 ) {

			// First show and position flipper.

			$('#left_arrow').show();
			var arrow_l_left = left + 2;
			$('#left_arrow').css('top', arrows_top).css('left', arrow_l_left);


			// Now work out onClick action for this flipper.

			prev_img_num = img_num - 1;
			index_of_prev = index_of_cur - 1;
			last_image_id = all_images[index_of_prev];
			
			$('#left_arrow_link').click(function () {
				flipImage(cur_image_id, last_image_id, prev_img_num, grp_siz, left, my_top);
				return false;
			});

		}


		// Then - if there should be a link on right flipper.
		
		if ( img_num < grp_siz ) {

			// First show and position flipper.

			$('#right_arrow').show();
			var arrow_r_left = left + width - 55;
			$('#right_arrow').css('top', arrows_top).css('left', arrow_r_left);


			// Now work out onClick action for this flipper.
			
			next_img_num = img_num + 1;
			index_of_next = index_of_cur + 1;		
			next_image_id = all_images[index_of_next];
			
			$('#right_arrow_link').click(function () {
				flipImage(cur_image_id, next_image_id, next_img_num, grp_siz, left, my_top);
				return false;
			});

		}


		// Finally, toggle global var to indicate that flippers are . . . UP!

		flippersDisplayed = true;
	
	}
	
	
	// Now look and see if there is a caption.
	
	cur_thumb_id = myDiv.id.replace("Div", "").replace("_", "_t");

	eval ( 'my_alt = $("#'+cur_thumb_id+'").attr("alt")' );

	if ( my_alt ) {
	
		showCaption ( my_alt, width, height, left, my_top );
	
	}
	
	
	// Finally, grey out background elements w/helper function.
	
	greyOut();

}


// This is helper/grouper function for flipping images in groups.

function flipImage ( from, to, img_num, grp_siz, left, my_top ) {


	// Hide the old image.

	eval ( 'hideImage ( '+from+' )' );
	

	// Find dimensions of both images.

	var old_image = from + "Img";
	eval ( 'var old_height = $("#'+old_image+'").height() ');
	eval ( 'var old_width = $("#'+old_image+'").width() ');
	
	var new_image = to + "Img";
	eval ( 'var new_height = $("#'+new_image+'").height() ');
	eval ( 'var new_width = $("#'+new_image+'").width() ');
	
	
	// Make the 4th arg, with image number and group size.
	
	var grp_info = '"'+img_num+':'+grp_siz+'"';
	
	
	// Now figure out where to display the new bastage.
	
	new_left = left + ( ( old_width - new_width ) / 2 );
	new_top = my_top + ( ( old_height - new_height ) / 2 );

	
	// Show the new image.

	eval ( 'showImg ( '+to+', '+new_width+', '+new_height+', '+grp_info+', '+new_left+', '+new_top+' )' );

}


// Show photo captions.

function showCaption ( my_alt, width, height, left, my_top ) {

	var cap_width = width - 140;

	$("#caption").width(cap_width);
	
	my_alt = '<span id="caption_contents">'+my_alt+'</span>';
	
	$("#caption").html(my_alt);
	
	var cap_height = $("#caption").height();
	
	cap_left = left + 70;
	
	cap_top = my_top + height - cap_height - 6;
	
	$("#caption").css("left", cap_left);

	$("#caption").css("top", cap_top);
	
	$("#caption").show();

}


// Popup text positioner and shower.

function showPopup(popDiv) {
	//var left = (xMousePosMax/2) - 190;
	//var left = xMousePos - (190) + 40;
	var left = 160;
	if (showPopup.arguments[1]) left += showPopup.arguments[1];
	var my_top = yMousePos - 100;
	if (my_top < ceiling) my_top = ceiling + 20;
	popDiv.style.left = left;
	popDiv.style.top = my_top;
	popDiv.style.visibility = "visible";
	$(popDiv).show();

	
	// Finally, grey out background elements w/helper function.
	
	greyOut();
	
}


// Picture popup text positioner and shower.

function showPixPopup2(popDiv, width, height) {
	popDiv.style.width = width + 4;
	var left = (xMousePosMax/2) - (width/2);
	var my_top = ceiling + 16;
	//var my_top = yMousePos - (height/2);
	if ((left + width) > xMousePosMax) left = xMousePosMax - width - 20;
	if (left < 0) left = 4;
	//if (my_top < ceiling) my_top = ceiling + 10;
	//if ((my_top + height) > yMousePosMax) my_top = yMousePosMax - height - 20;
	popDiv.style.left = left;
	popDiv.style.top = my_top;
	popDiv.style.visibility = "visible";


	// Finally, grey out background elements w/helper function.
	
	greyOut();

}


// Picture popup text positioner and shower.

function showPixPopup(popDiv) {
	var left = 20;
	var my_top = ceiling + 20;
	popDiv.style.left = left;
	popDiv.style.top = my_top;
	popDiv.style.visibility = "visible";

	// Finally, grey out background elements w/helper function.
	
	greyOut();

}


// Picture hider.

function hideImage ( myDiv ) {


	// Hide the div with the picture in it.

	hide ( myDiv );


	// If flippers are displayed, hide those bad boys.	

	hideFlippers();
	
	
	// If caption is displayed, ditto.
	
	$('#caption').hide();
	

}


function hideFlippers() {

	$('#left_arrow').hide();
	
	$('#right_arrow').hide();

}


// dingus hider
function hide(myDiv) {
	myDiv.style.visibility = "hidden";
	myDiv.style.left = -500;
	myDiv.style.top = -500;
	unGreyOut();
}


// oi hider

function hideOi(oiDiv, head_name) {

	oiDiv.style.visibility = "hidden";
	oiDiv.style.left = -500;
	oiDiv.style.top = -500;
	unGreyOut();
	
	
	// Ungrey background.
	
	unGreyOut();
	
	
	// Change head image source to match new background.
	
	head_div_name = oiDiv.id.substring ( 0, oiDiv.id.length - 3 ) + '_head';

	var head = document.getElementById(head_div_name);

	head_old_src = head.src;
	
	head.src = head_old_src.replace("-greyout", "");


	// Change z-index to put back behind greyout.
	
	head.style.zIndex = 5;

}


// oi positioner and shower
function showOi(oiDiv, y, person) {
	var my_top = y;
	var left = 255;
	oiDiv.style.left = left;
	oiDiv.style.top = my_top;
	oiDiv.style.visibility = "visible";
	
	
	// Grey out background elements w/helper function.
	
	greyOut();
	
	
	// Change head image source to match new background.
	
	head_div_name = oiDiv.id.substring ( 0, oiDiv.id.length - 3 ) + '_head';

	var head = document.getElementById(head_div_name);

	head_old_src = head.src;
	
	head.src = head_old_src.replace(".gif", "-greyout.gif");


	// Change z-index to bring in front of greyout.
	
	head.style.zIndex = 8;
	
}


// Zoomy image positioner and shower
function showZoomer(myDiv, width, height) {
		myDiv.style.visibility = "visible";
		var left = (xMousePosMax/2) - (width/2);
		var my_top = yMousePos - (height/2);
		if ((left + width) > xMousePosMax) left = xMousePosMax - width - 20;
		if (left < 0) left = 4;
		if (my_top < ceiling) my_top = ceiling + 10;
		if ((my_top + height) > yMousePosMax) my_top = yMousePosMax - height - 20;
		myDiv.style.left = left;
		myDiv.style.top = my_top;
		
		// Finally, grey out background elements w/helper function.
		
		greyOut();
}

// Image zoomer and unzoomer
function zoom(name, img, div) {
	eval ("if (" + name + "_zoomed % 2 == 1) hide(div)");
	eval ("if (" + name + "_zoomed % 2 == 0) " + name + "Suffix = 'C'");
	eval ("if (" + name + "_zoomed % 2 == 1) " + name + "Suffix = ''");
	eval ("var suffix = " + name + "Suffix");
	if (nn4) {
		eval ("document.layers." + name + "Div.document.images." + name + "_img.src = 'img/" + img + suffix + ".jpg'");
	}
	else if (nn) {
		eval ("document.images." + name + "_img.src = 'img/" + img + suffix + ".jpg'");
	}
	else {
		eval (name + "_img.src = 'img/" + img + suffix + ".jpg'");
	}
	eval (name + "_zoomed++");
}


// This greys out everything behind popup elements.

function greyOut() {

	// Get reference to the div.
	
	greyout = new getObj('greyoutDiv');


	// Get screen size.
	
	if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {

		var pageWidth = document.body.scrollWidth+'px';
		var pageHeight = document.body.scrollHeight+'px';

	} else if( document.body.offsetWidth ) {

		var pageWidth = document.body.offsetWidth+'px';
		var pageHeight = document.body.offsetHeight+'px';

	} else {

	 	var pageWidth='100%';
	 	var pageHeight='100%';
	}
	
	greyout.style.width = pageWidth;
	greyout.style.height = pageHeight;

	greyout.style.visibility = 'visible';

}


// This greys out everything behind popup elements.

function unGreyOut() {

	// Get reference to the div.
	
	greyout = new getObj('greyoutDiv');
	
	greyout.style.visibility = 'hidden';

}



// 'email this' form shower
function showMailer() {


	// Makes sure fields aren't disabled.

	$("#from_email").removeAttr("disabled"); 

	$("#to_emails").removeAttr("disabled"); 
	
	
	// Make sure their contents are empty.
	
	$("#from_email").val("");
	$("#to_emails").val("");	

	mail_form = new getObj('mail_formDiv');

	$('#mail_formDiv').css('visibility','visible')
		.css('left','396px')
		.css('top',yMousePos);

	
	// Finally, grey out background elements w/helper function.
	
	greyOut();
	
}


// 'subscribe' form shower
function showSubscriber() {


	// Makes sure field isn't disabled.

	$("#email").removeAttr("disabled"); 	
	
	
	// Make sure contents is empty.
	
	$("#email").val("");

	
	subscribe_form = new getObj('subscribe_formDiv');
	
	subscribe_form.style.left = 396;
	subscribe_form.style.top = 250;
	subscribe_form.style.visibility = "visible";

	
	// Finally, grey out background elements w/helper function.
	
	greyOut();
	
}


// Set up the AJAX 'email this' section to, erm, work. (Called by init().)

function setUpEmail() {

	$("#mail_submit").click(function() {


		// Gray out the fields so they can`t be modified (and look in transit).
		
		$("#from_email").attr("disabled", "true");
		
		$("#to_emails").attr("disabled", "true");


		// Make the submit and cancel buttons disappear; replace with pulsing rod of loading.
		
		$("#mailer_buttons").hide();
		
		$("#mail_form_content").append('<div style="margin:-4px 32px 0 0; color:#990B0D;" align="right"><i>sending</i><br><img width="48" height="8" src="/razorsedge/img/loader-line.gif" alt="loading" id="loading" /></div>');

		// Now send the form contents via AJAX post request.
		
		from_emailVal = $("#from_email").val();
		to_emailsVal = $("#to_emails").val();
		headerVal = $("#header_val").val();
		subheader1Val = $("#subheader1_val").val();
		subheader2Val = $("#subheader2_val").val();
		subheader3Val = $("#subheader3_val").val();
		teaserVal = $("#teaser_val").val();
		story_Val = $("#story_val").val();
		
		$.post("/razorsedge/bin/emailer.php",
		   { from_email: from_emailVal, to_emails: to_emailsVal, header: headerVal, subheader1: subheader1Val, subheader2: subheader2Val, subheader3: subheader3Val, teaser: teaserVal, story: story_Val },
			function(data){

				$("#mail_form_content").slideUp("normal", function() {

					if (data) {
						resp_head = "Win!";
						resp_body = "Your mail was sent.";
					}

					else {
						resp_head = "Fail!";
						resp_body = "Your attempt to send mail<br>screwed the pooch! Sorry.";
					}

					$("#mail_form_content").after('<br><h1 style="margin:16px 0 24px 16px">'+resp_head+'</h1><p>'+resp_body+'</p><div align="center"><br><input type="button" onClick="javascript:hide(mail_form)" value="close this bad boy"></div>');
					
				});

			}
		);	
	
		return false;

	} );
}




// Set up the AJAX 'subscribe' section to, erm, work. (Called by init().)

function setUpSubscriber() {

    $("#subscriber_submit").click(function() {


        // Gray out the field so they cannot be modified (and look in transit).

        $("#email").attr("disabled", "true");


        // Make the submit and cancel buttons disappear; replace with pulsing rod of loading.

        $("#subscriber_submit").hide();
        $("#subscriber_cancel").hide();

        $("#subscriber_buttons").append('<div style="margin:4px; color:#990B0D;"><i>sending</i> <img width="48" height="8" src="/razorsedge/img/loader-line.gif" alt="loading" id="loading" /></div>');


        // Now send the form contents via AJAX post request.

        emailVal = $("#email").val();
        story_Val = $("#story_val").val();


        $.post("/razorsedge/bin/subscriber.php",
           { email: emailVal, story: story_Val },
            function(data){

                $("#subscriber_form_content").slideUp("normal", function() {

                    if (data) {
                        resp_head = "Win!";
                        resp_body = "You have been subscribed!</p><p>You will receive a confirmation message.";
                    }

                    else {
                        resp_head = "Fail!";
                        resp_body = "Your attempt to subscribe<br>screwed the pooch! Sorry.";
                    }

                    $("#subscriber_form_content").after('<br><h1 style="margin:16px 0 24px 16px">'+resp_head+'</h1><p>'+resp_body+'</p><div align="center"><input type="button" onClick="javascript:hide(subscribe_form)" value="close this puppy"></div>');

                });

            }
        );

        return false;

    } );
}






// These are some stock initialisation tasks called by the init()
// script in index.php.

function stockInit () {

	// Position related articles by story tags.

	// Get bottom of window.
	var myb = 0 - ( $(document).height() - $(window).height() ) + 20;

	// Get height of sidebar, make sure we're beneath that.
	var sbh = $('#sidebar').height();

	//if ( myb < ( 224 + sbh ) ) {
		//myb = 224 + sbh;
	//}
	

	// Set top and make visible.
	$('#related_show').css('bottom',myb+'px'); 
	$('#related_show').css('visibility','visible'); 



	// Set up the AJAX 'email this' section to, erm, work.

	setUpEmail();


	// If we're called with a #subs anchor, go ahead and show mail form.

	if ( window.location.hash == "#subs" ) {
		showSubscriber();
	}


	// Set up the AJAX 'subscribe' section to, erm, work.

		setUpSubscriber();


	// Set up the hover effect of the image flipper arrows.
	
	$("#left_arrow_image").hover (
		
		function () {
		
			$(this).attr("src", "graphics/left_arrow-a.png");
		
		}, 
		
		function () {
		
			$(this).attr("src", "graphics/left_arrow.png");
		
	});

	
	$("#right_arrow_image").hover (
		
		function () {
		
			$(this).attr("src", "graphics/right_arrow-a.png");
		
		}, 
		
		function () {
		
			$(this).attr("src", "graphics/right_arrow.png");
		
	});


	// Bind left and right arrow key presses to click the next
	// and previous image arrow buttons.

	$(document).keydown(function(e){

		if (e.keyCode == 37) { 

		   $('#left_arrow_link').click();

		   return false;

		}

		if (e.keyCode == 39) { 

		   $('#right_arrow_link').click();

		   return false;

		}


	});

	// Set up search box to perform.

	$('#searchbox').focus(function(e){
		$(this).css('opacity','1');
		$(this).attr('value','');
	});

	$('#searchbox').blur(function(e){
		if ( $(this).attr('value') == '' ) {
			$(this).css('opacity','.6');
			$(this).attr('value',' s e a r c h ');
		}
	});

  // Make Facebook count bubble appear.
  //jQuery("span.fb_share_no_count").each(function(){
    //jQuery(this).removeClass("fb_share_no_count");
    //jQuery(".fb_share_count_inner", this).html("0");
  //});

	// This is for 'show more' buttons.

	$('.revealer').click(function(e){
		e.preventDefault();
		$(this).next().show(400, function() {
			$(this).next().css('display','inline');
		});
		$(this).hide();
		return false;
	});

	$('.unrevealer').click(function(e){
		e.preventDefault();
		$(this).parent().hide(400);
		//$(this).parent().prev().show();
		return false;
	});



	// Set up the 'more' buttons on most recent/read/commented to flip.

	$('.moster').click(function(e){

		// Prevent default behaviour.

		e.preventDefault();


		// Get handle for parent div, plus id, plus the ol.

		$d = $(this).parent().parent();
		my_id = $d.attr('id');
		$my_ol = $('ol', $d);


		// Get which set to show from global var, which is named same as div id.

		var my_set = window[my_id];


		// Establish range of items to show.

		var my_start = ( my_set * 5 );
		var my_end = my_start + 5;


		// If we`re in 6-20, set numbers on lis.

		if ( my_set > 0 ) {
			$my_ol.addClass('ol-numbers');
			$my_ol.attr('start', my_start + 1);
		}

		else {
			$my_ol.removeClass('ol-numbers');
		}


		// Get handle for all lis in this section (do it once for efficiency).

		$lis = $('li', $d);


		// Hide all list items in this set.

		$lis.hide();


		// Get handle for, and show, the correct 5.

		$lis.slice(my_start, my_end).show();


		// Increment our set number.

		window[my_id]++;
		if ( window[my_id] == 4 ) window[my_id] = 0;

		return false;

	});

	// Set up about stuff.

	$("#about-opener").hover(function () {
			$(this).css("border-color", "#716c51");
			$(this).css("background-color", "#fcfbf3");
		}, 
		function () {
			$(this).css("background-color", "#f7f4d7");
			$(this).css("border-color", "#9f9872");
	});


	$('#about-opener').click(function(e){
		greyOut();
		$('#about-dftre').show();
	});


	$('#about-close').click(function(e){
		$('#about-dftre').hide();
		unGreyOut();
	});


	// Set up footnote closers.

	$('.footnote-closer').click(function(e){
		unGreyOut();
		$(this).parent().hide();
	});

}


// Email hider/printer

function showAddy(user, host, tld) {
	document.write ( '<a href="mailto:'+user+'@'+host+'.'+tld+'">'+user+'@'+host+'.'+tld+'</a>' );
}

