if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n !== 0 && n !== Infinity && n !== -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

$(document).ready(function() {

	// 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");
	$('div.group .abstract').addClass("ui-widget ui-widget-header ui-state-default ui-corner-bottom");


	$('.resource-container').on('resourceStart', 'div.group', function() {
		var $this = $(this);
		$this.addClass("ui-widget ui-widget-content ui-corner-all shadow");
		$this.find('h3.group').addClass("ui-widget ui-widget-header ui-state-default ui-corner-top");
		$this.find('.abstract').addClass("ui-widget ui-widget-header ui-state-default ui-corner-bottom");
	});


	// resource / resource editors within tabs sometimes need to know if the active tab has changed
	$('.tabs').tabs({select: function(e, ui){ $(this).find('.resource-container').trigger('tabChanged'); }}).show();

	// integrate this into tab startup
	// TODO support for multiple tabsets, perhaps with psuedo-namespacing
	// e.g. <input type="hidden" id="activeTab" value="my-tab.tabsetname"> OR
	// e.g. <input type="hidden" id="activeTab" value="my-tab" data-tabset="tabsetname">
	var activeTab = $('#activeTab');
	if(activeTab.length) {
		if(activeTab.val().match(/^\d+$/)) {
			$('.tabs').tabs('select', parseInt(activeTab.val()));
		} else {
			if($('#' + activeTab.val()).length) {  // make sure we have a div of the same name
				$('.tabs').tabs('select', activeTab.val());
			}
		}
	}


	// get resources
/*	$('[id^="resTrig_"]').live('click', function() {
		var id = $(this).attr('id').substr(8);  // resTrigger_ = 8 chars
		console.log(id);
		$.get('/ajax/page_ajax.php', {'q': 'content', 'resourceid': id}, function(response) {
			$('#resDiv_' + id).html(response);
		});
	}); */


/*	window.alert = (function(str) {
		var alert = $('<div></div>').append(str).dialog({
			modal: true,
			dialogClass: 'lang-align',
			title: $('meta[name=app_name]').attr('content') + ':',
			buttons: { "OK": function() {
				$(this).dialog("close");
			}}
		});
	});


	window.confirm = (function(str) {
		var confirm = $('<div></div>').append(str).dialog({
			modal: true,
			dialogClass: 'lang-align',
			title: $('meta[name=app_name]').attr('content') + ':',
			buttons: { "OK": function() {
				$(this).dialog("close");
			}}
		});
	}); */

/*
	// onload modal alerts - coming soon
	if($('#onLoadAlerts').html().length) {
		alert($('#onLoadAlerts').html());
	} */

	$('.guessfiletype').change(function(){
		$.getJSON("/ajax/folder_ajax.php", {'q': 'guessFiletypeID', 'filename': $(this).val(), 'sid':  + Math.random }, function(data) {
			// this is always there in practice
			$('#DOMfiletypeid').val(data);
		});
	})
});


function getUrlParameters() {
	var map = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
	map[key] = value;
	});
	return map;
}

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;
}







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

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 pageinfoTeam(query, accountid, resourceid) {
	$.get("/ajax/page_ajax.php", {'q' : query, 'resourceid' : resourceid, 'accountid' : accountid, "sid" : Math.random() },
		function(data) {
			$('#pi' + accountid).html(data);
		}
	);
}

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

function hidePageinfoTeam(accountid, resourceid) {
	pageinfoTeamAoH('hidePageinfoTeam', 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(data);
				$('div.poll.group').trigger('resourceStart');
			}
		);
	}
}



/** 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();
	}
}



