// prepare global variable object
var globals = {};

function getCSSNumber(string,extlength) {
	if(string != undefined) {
		return string.substr(0,string.length-extlength);
	}
	else {
		return 0;
	}
}

function prepareCufon() {
	Cufon.replace(".cufon");	
}

/*function setBoxHeight() {
	if($('.contentBox').length == 0) {return false;}
	var boxes = $('.contentBox');
	for(var i=0;i<boxes.length;i++) {
		var height = (boxes.eq(i).find('.title').outerHeight(true) + 180) + 'px'; //add 180 for images as they haven't loaded at INITDOM
		boxes.eq(i).css('height',height);
		boxes.eq(i).attr('name', height); // write this value to the DOM for easy access later
	}	
}*/

/*function prepareHomepageScroller() {
	var scrollers = $('.horizWindow');
	
	// loop through all the scrollers and set up
	for(var i=0; i<scrollers.length; ++i) {
		var currentScroller = scrollers.eq(i);
		var itemWrapper = currentScroller.find('.scrollwrapper');
		var images = currentScroller.find('.contentBox');
		
		// calculate the total width of the inner wrapper and set it
		var scrollerWidth = 0;
		for(var j=0; j<images.length; ++j) {
			scrollerWidth += images.eq(j).outerWidth(true);
		}
		itemWrapper.width(scrollerWidth);
				
		// add controls
		// do we need a javascript scroller?
		var left = currentScroller.find('.scrollcontrol.left');
		var right = currentScroller.find('.scrollcontrol.right');
		
		left.click(function () {
			var mover = this.parent().find('.scrollwrapper');
		})
	}
	
}*/

/* sets up the scroller on the content pages
*/
function prepareScroller() {
	var scrollers = $('.scroller');
	
	// loop through all the scrollers and set up
	for(var i=0; i<scrollers.length; ++i) {
		var currentScroller = scrollers.eq(i);
		var itemWrapper = currentScroller.find('.item_wrapper');
		var divs = scrollers.find('.page_item');
		var left = currentScroller.find('.js_left');
		var right = currentScroller.find('.js_right');
		
		// calculate the total width of the inner wrapper and set it
		var scrollerWidth = 0;
		var scrollPos = 0;
		var margin = getCSSNumber(divs.eq(0).css("margin-right"), 2);

		for(var j=0; j<divs.length; ++j) {
			// so that if there is a lot of text it will wrap
			//divs.eq(j).width(divs.eq(j).find('.media').width());
			divs.eq(j).width(646);
			divs.eq(j).attr("scrollpos", scrollPos);
			scrollerWidth += divs.eq(j).outerWidth(true);
			scrollPos = parseInt(scrollerWidth) + parseInt(margin);
		}
		
		itemWrapper.width(scrollerWidth);
		scrollerHeight = left.outerHeight(true) + itemWrapper.outerHeight(true);
		currentScroller.height(scrollerHeight);
		
		// hook up mouse events
		currentScroller.attr("pos_index", "0");
		left.css('visibility', 'hidden');
		left.click(scrollMove);
		if(divs.length <= 1) {
			right.css('visibility', 'hidden');
		}
		right.click(scrollMove);
		
		currentScroller.css('opacity',0);
		currentScroller.css('visibility', 'visible');
		currentScroller.animate({opacity:1},500);
	}
}

function scrollMove() {
	var currentScroller = $(this).parent().parent().parent();
	var itemWrapper = currentScroller.find('.item_wrapper');
	var items = itemWrapper.children('.page_item');
	var posIndex = currentScroller.attr("pos_index");
	var left, right, distance;
	
	switch($(this).attr('class')) {
		case 'js_left':
			currentScroller.attr("pos_index", --posIndex);
			distance = items.eq(posIndex).outerWidth(true);
			left = $(this);
			right = currentScroller.find('.js_right');
			break;
		
		case 'js_right':
			distance = items.eq(posIndex).outerWidth(true);
			currentScroller.attr("pos_index", ++posIndex);
			right = $(this);
			left = currentScroller.find('.js_left');
			break;
	}
	
	if(posIndex == 0) {
		left.css('visibility', 'hidden');
	}
	else {
		left.css('visibility', 'visible');
	}
	if(posIndex + 1 == items.length) {
		right.css('visibility', 'hidden');
	}
	else {
		right.css('visibility', 'visible');
	}
	
	var pos = items.eq(posIndex).attr("scrollpos");
	pos *= -1;
	var speed = 1;
	var time = Math.round(distance / speed);
	itemWrapper.animate({left:pos}, time, "easeOutBack");
	return false;

}

/* function to allow easy swfobject replacement for multiple dynamic flash movies
 * replaces divs with class "flash" and desired attributes with correct object tags
 */
function setupFlashContent() {
	var flashDivs = $('.flash');
	
	for(var i=0; i<flashDivs.length; ++i) {
		var flashvars = {};
		var params = {};
		var replace = flashDivs.eq(i).children('div');
		var src = replace.attr('data');
		var width = replace.attr('width');
		var height = replace.attr('height');
		var id = replace.attr('id');
				
		if(replace.attr('params')) {
			var pArray = replace.attr('params').split('&');
			for(var j=0; j<pArray.length; ++j) {
				var keyValue = pArray[j].split('=');
				params[keyValue[0]] = keyValue[1]; 
			}
		}
		if(replace.attr('flashvars')) {
			var fArray = replace.attr('flashvars').split('&');
			for(var k=0; k<fArray.length; ++k) {
				var keyValue = fArray[k].split('=');
				flashvars[keyValue[0]] = keyValue[1]; 
			}
		}
		
		swfobject.embedSWF(src, id, width, height, '9.0.0', 'public/flash/expressInstall.swf', flashvars, params);
	}
}

/* hooks up the mouse events on the homepage
*/
function prepareLinks() {
	if(!$('#content').hasClass('js_homepage')){return false;}
	// flash mouse event problem
	var picLinks = $('#content').find('a.media').click(function (e) {
		e.preventDefault();
		homepageClickHandler($(this));
	});
	//var picLinks = $('.contentBox').children('a');
	/*for(var i=0;i<picLinks.length; i++) {
		// flash mouse event problem
		/*picLinks.eq(i).hover(function () {
			$(this).css('cursor','pointer');
		})
		
		picLinks.eq(i).click(function () {
			return homepageClickHandler(this);
		});
	}*/
}

/* function to prepare the mouse event passed from a swf
 * so that the homepageClickHandler fires correctly with flash movies
 * deals with the problem of anchor tags not working when surrounding swfs
 */
function as3Interface(clicked_id) {
	homepageClickHandler($('#'+clicked_id));
}

/* function to show/hide the text on the homepage
 * loads the second page on two clicks
 */
function homepageClickHandler($target) {
	// if wmode is set to opaque on the index page this function will fire correctly in firefox 3.6.
	var contentBox = $target.parent();
		
	if(contentBox.attr('id') != 'open') {
		var targetHeight = contentBox.children('.title').outerHeight(true) + contentBox.find('.media').outerHeight(true) + contentBox.children('.toggle').outerHeight(true);
		
		var old = null;

		if($('#open').length > 0) {
			old = $('#open');
			var oldHeight = 230;
			if(contentBox != old) {
				old.animate({
					height:oldHeight
				},250);
			}
		}
					
		contentBox.animate({
			height:targetHeight
		},250);
		if(old != null)old.attr('id','');
		contentBox.attr('id','open');
	}
	else {
		//flash mouse event problem
		window.location = $target.attr('href');
	}
}

/* function to show or hide form fields based on user-input from a drop down
 * form must have class "hidden_form" (as many forms per page as you like)
 * relevant select options must have class "show"
 * the part(s) of the form that should be shown and hidden must be contained in a div with class "hide"
 */
function formFieldToggler() {
	var form = $('.hidden_form');
	for(var i=0; i<form.length; ++i) {
		// check if it's the first loaded thing
		var toggler = form.eq(i).find('.show_hide');
		var index = toggler.attr('selectedIndex');
		if(toggler.find('option').eq(index).attr('class') == "show") {
			form.eq(i).find('.hide').css('display','block');
		}
		else {
			form.eq(i).find('.hide').css('display','none');
		}
		// check if it's selected when we change
		toggler.change(function () {
			var index = $(this).attr('selectedIndex');
			if($(this).find('option').eq(index).attr('class') == "show") {
				$(this.form).find('.hide').css('display','block');
			}
			else {
				$(this.form).find('.hide').css('display','none');
			}
		})
	}
}

/* function to supply confirmation when delete is selected from a form
 * form(s) must have class "delete_form"
 * function works by counting checked checkboxes so no other checkboxes should be used in the form
 */
function confirmDelete() {
	var form = $('.delete_form');
	for(var i=0; i<form.length; ++i) {		
		form.eq(i).submit(function () {
			var numChecked = 0;
			for(var j=0; j<this.length; ++j) {
				if(this.elements[j].type == "checkbox" && this.elements[j].checked == true) {
					numChecked++;
				}
			}
			var msg = (numChecked > 1) ? 'Are you sure you want to delete these '+numChecked+' items?' : 'Are you sure you want to delete this item';
			if(numChecked != 0) {
				var bool = confirm(msg);
				return bool;
			}
			else {
				alert('No items selected for deletion!');
				return false;
			}
		})
	}
}

/* functions to reorder table rows
 * prepareOrderListeners - sets up the a tags to fire the relevant js  
 * tables(s) must have class "reorder_table"
 * rows that are movable must have class "order"
 * the a tags used to move rows must have class "order_control"
 * the up a tag must also have class "up" and down class "down"
 * a hidden form with class "reorder_form" stores the current order in an input with name "order"
 * calls function applyOrder
 * buttons call function doOrder
 */
function prepareOrderListeners() {
	var table = $('.reorder_table');
	
	for(var i=0; i<table.length; ++i) {
		applyOrder(table.eq(i));
		var rows = table.eq(i).find('.order');
		
		for(var j=0; j<rows.length; ++j) {
			rows.eq(j).find('.order_control').css('display','inline');
			rows.eq(j).find('.order_control').click(doOrder);
			if(j==0) {
				rows.eq(j).find('.up').css('display','none');
			}
			if(j+1==rows.length) {
				rows.eq(j).find('.down').css('display','none');
			}
		}
		
	}	
}

/* reads the reordable rows set by class 'order'
 * from the passed table and sets the value of an input called 'order'
 * with the ordered ids of the rows, this is the value sent to PHP to apply the order in the DB */
function applyOrder(table) {
	var form = table.find('.reorder_form');
	var roworder = new Array();
	var rows = table.find('.order');
	for(var i=0; i<rows.length; ++i) {
		roworder.push(rows.eq(i).find('input[name=id]').attr('value'));
	}
	form.find('input[name=order]').attr('value', roworder);
}

// does the visual DOM swapping
function doOrder() {
	var currentRow = $(this).parent().parent();
	if((/up/).test($(this).attr('class'))){
		var swapRow = currentRow.prev();
	}
	else if((/down/).test($(this).attr('class'))){
		var swapRow = currentRow.next();
		swapRow = swapRow.next();
	}
	currentRow.insertBefore(swapRow);
	// reset the links
	prepareOrderListeners();
	return false;
}

function prepareTweetBox() {
	var search_word = $('#js_twitter_word').text();
	if(search_word.length > 0) {
		var box = $('.contentBox').eq(4).find('span.subhead');
		var tweetBox = new TweetBox(box, search_word);
		tweetBox.getJSON();
	} 
}

function initDOM() {
	prepareTweetBox();
	confirmDelete();
	formFieldToggler();
	prepareOrderListeners();
	prepareCufon();
	setupFlashContent();
}

function initImgFuncs() {
	prepareScroller();
	prepareLinks();
	//prepareHomepageScroller();
	//setBoxHeight();
	//prepareOverlay();
}

$(document).ready(initDOM);
window.onload = initImgFuncs;

// overlay functions
// functions add a transparent overlay to the page with an image in the middle
// and close button to close (requires overlay to be in markup)

/*$(window).resize(resizeFunc);
function resizeFunc() {
	prepareOverlay();
}

function prepareImages() {
	var images = $('.scroller').find('img');
	
	for(var i=0; i<images.length; ++i) {
		var link = images.eq(i).parent();
		
		link.click(function () {
			createOverlay($(this).attr('href'));
			return false;
		})
	}
}

function prepareOverlay() {
	var viewportHeight = $(document).height();
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var overlay = $('#overlay');
	var png = overlay.find('#background');
	overlay.css('width',windowWidth);
	overlay.css('height',viewportHeight);
	png.css('width',windowWidth);
	png.css('height',viewportHeight);
	
	var picture = overlay.children('#picture');
	if(picture.length > 0) {
		var width = picture.width();
		var height = picture.height();
		var left = (windowWidth - width) / 2;
		var top = (windowHeight - height) / 2;
		picture.css('top', top);
		picture.css('left', left);
	}
}

function createOverlay(src) {
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var overlay = $('#overlay');
	overlay.animate({opacity:0},0);
	overlay.css('visibility','visible');
	var image = new Image();
	image.src = src;
	image.id = 'picture';
	var width, height;
	image.onload = function () {
		var width = this.width;
		var height = this.height;
		var left = (windowWidth - width) / 2;
		var top = (windowHeight - height) / 2;
		$(this).css('top', top);
		$(this).css('left', left);
		overlay.append(image);
		overlay.fadeTo(250,1);
	}
	prepareCloseButton();
}

function prepareCloseButton() {
	var overlay = $('#overlay');
	$('#close').click(function () {
		overlay.remove('#picture');
		overlay.css('visibility','hidden');
		return false;
	});
}*/