
$(document).ready(function() {
	// generic listing table expand function
	$('.pline-expand').click(function(){
		$(this).toggleClass('pline-contract pline-expand');
		$(this).parents('tr').next('.expand-toggle-target').toggleClass('hide');
	});

	// psuedo jquery-ui item grouping to replace old fieldset stuff
	$('div.group').addClass("ui-widget ui-widget-content ui-corner-all shadow");
	$('h3.group').addClass("ui-widget ui-widget-header ui-state-default ui-corner-top");

	$('.tabs').tabs().show();

	var activeTab = $('#activeTab');
	if(activeTab.length && $('#' + activeTab.val()).length) { // make sure we have an activeTab and a div of the same name
		$('.tabs').tabs('select', activeTab.val());
	}

	//window.alert = (function(str) {
	//var alert = $('<div></div>').append(str).dialog({ modal: true });
	//});
});



function resourceID(domID)
{
	var re = /\d+/;
	return domID.match(re)[0];
}

function clearInput(input)
{
	if (input.defaultValue == input.value) {
		input.value = '';
	}
}


function findIntersectors(targetSelector, intersectorsSelector)
{
    var intersectors = [];

    var $target = $(targetSelector);
    var tAxis = $target.offset();
    var t_x = [tAxis.left, tAxis.left + $target.outerWidth()];
    var t_y = [tAxis.top, tAxis.top + $target.outerHeight()];

    $(intersectorsSelector).each(function() {
          var $this = $(this);
          var thisPos = $this.offset();
          var i_x = [thisPos.left, thisPos.left + $this.outerWidth()]
          var i_y = [thisPos.top, thisPos.top + $this.outerHeight()];

          if ( t_x[0] < i_x[1] && t_x[1] > i_x[0] &&
               t_y[0] < i_y[1] && t_y[1] > i_y[0]) {
              intersectors.push($this);
          }

    });
    return intersectors;
}









/*********************************************************
*
* setOptions (str ElementId, str JSON)
*
* generalised method for populating a list with an array
* of JSON hashes
* Can support any attributes but MUST include at least
* a name and value
*
* TODO port me to jquery
*********************************************************/

function setOptions(id, options) {
	if (options == undefined || id == undefined) {
		return;
	}

	select = document.getElementById(id);

	if (select !== undefined && options.length) {

		// clear existing children
		if (select.hasChildNodes()) {
			while (select.firstChild) {
				select.removeChild(select.firstChild);
			}
		}

		// populate with new nodes
		for (var i = 0; i < options.length; i++) {

			var opt = document.createElement('option');

			for (var prop in options[i]) {
				if (prop === 'name') {
					opt.appendChild(document.createTextNode(options[i].name));
				} else if (prop === 'selected') {
					if (options[i].selected !== '')
						opt.setAttribute('selected', options[i].selected);
				} else {
					// and any other attributes
					opt.setAttribute(prop, options[i][prop]);
				}
			}

			select.appendChild(opt);
		}
	}
}





/************************************
 * Folder and File
 *
 ************************************/

function filetypeAoH(str) {
	$.getJSON("/ajax/folder_ajax.php", {'q': 'filetypeAoH', 'filename': str, 'sid':  + Math.random },
	function(data) {
		// NB this is the ONLY thing that uses setOptions (function above)
		setOptions('DOMfiletypeid', data);
	});
}

function foldercontentsAoH(rid, order, sort) {
	$.get("/ajax/folder_ajax.php", {'q': 'foldercontentsAoH', 'resourceid': rid, 'order': order, 'sort': sort, 'sid': Math.random },
	function(data) {
		if(data.length)
			$('#r' +rid).replaceWith(data);
	});
}


/************************************
 * Pageinfo
 *
 ************************************/

function pageinfoTeamAoH(query, accountid, resourceid) {
	$.get("/ajax/page_ajax.php", {'q' : query, 'resourceid' : resourceid, 'accountid' : accountid, "sid" : Math.random() },
		function(data) {
			$('#pi' + accountid).html(data)
		}
	);
}

function showPageinfoTeamAoH(accountid, resourceid) {
	pageinfoTeamAoH('showPageinfoTeamAoH', accountid, resourceid);
}

function hidePageinfoTeamAoH(accountid, resourceid) {
	pageinfoTeamAoH('hidePageinfoTeamAoH', accountid, resourceid);
}

function pageinfoTeamELanguagesAoH(query, accountid, resourceid) {
	$.get("/ajax/page_ajax.php", {'q' : query, 'resourceid' : resourceid, 'accountid' : accountid, "sid" : Math.random() },
		function(data) {
			$('#pi' + accountid).html(data)
		}
	);
}

// blah to super-verbose function names
function showPageinfoTeamELanguagesAoH(accountid, resourceid) {
	pageinfoTeamELanguagesAoH('showPageinfoTeamELanguagesAoH', accountid, resourceid);
}


function hidePageinfoTeamELanguagesAoH(accountid, resourceid) {
	pageinfoTeamELanguagesAoH('hidePageinfoTeamELanguagesAoH', accountid, resourceid);
}



/************************************
 * Poll functions
 *
 ************************************/

function pollResponse(form) {

	var answers = form.answerid;
	var resourceid = form.resourceid.value;

	/* check that one answer has been selected and
   * return it's value OR false
   */
	var isValidRadio = function(options) {
		for (var i = 0; i < options.length; i++) {
			if (options[i].checked) {
				return options[i].value;
			}
		}
		return false;
	};

	var answerid = isValidRadio(answers);

	if (answerid != false) {
		$.get("/ajax/poll_ajax.php", {'q' : 'pollResponse', 'resourceid' : resourceid, 'answerid' : answerid,	"sid" : Math.random()},
			function(data) {
				$("#r" + resourceid).replaceWith($('<div id="' + resourceid + '"></div>').html(data));
			}
		);
	}
}



//TODO flash in - fade out element above image showing current zoom%
function growImage(resourceid, direction, factor) {
	resourceid = resourceid === undefined ? null: resourceid;
	direction = direction === undefined ? 'grow': direction;
	factor = factor === undefined ? 1.2: factor;

	$.getJSON("/ajax/gallery_ajax.php", {
		'q' : 'growImage',
		'resourceid' : resourceid,
		'direction' : direction,
		'factor' : factor,
		"sid" : Math.random()
	},
	function(dim) {
		var image = "#r" + resourceid + "_image";
		var caption = "#r" + resourceid + "_caption";
		if ($(image) !== null && dim.height !== undefined && dim.width !== undefined) {
			$(image).attr('height', dim.height);
			$(image).attr('width', dim.width);
			$(caption) !== null && $(caption).attr('width', dim.width);
		}
	});
}

function getTemplate(filename) {
	filename = filename === undefined ? '404.html': filename;
    return $.ajax({type: "GET", url: "/ajax/page_ajax.php", data: {'q': 'getTemplate', 'filename': filename}, async: false }).responseText;
}



/** these next two  are used to show or hide whatsnext links **/
function reveal(link, divID) {
	var pos = $('#' + link).offset();
	$('#' + divID).css({
		'position': 'absolute',
		'top': (pos.top - 11) + 'px',
		'left': (pos.left - 145) + 'px'
	});
	$('#' + divID).show();
}

function conceal(divID) {
	if (divID != null) {
		$('#' + divID).hide();
	}
}



