// general.js
// (c) where applicable 2006-2009 Re-evolved ltd
// Tristan 'doctea' Rowley

function MiniNewWindow(newurl, width, height) {window.open(newurl,"ministatus","status=0,height=" + height + ",width=" + width + ",toolbar=0,location=0,directories=0,menubar=0,scrollbars=0,resizeable=0");}


function setupCalendarButton (id, buttonid) {
	var b = document.getElementById (buttonid);
	if (b!=null) {
		b.onclick = function () { 
			var t = document.getElementById (id);
			//alert ("got t '" + t.id + "'!");
			//t.focus();
			t.onclick();
			//alert ("clicked");
			return true;
		}
	}
	//alert ("setupCalendarButton('" + id + "', '" + buttonid + "')!");
	
	var obj = document.getElementById (id);
	//alert ("Got object '" + obj + "'!");
	
	Calendar.setup({
        inputField     :    id,   // id of the input field
        //button				 :		buttonid,	// id of the to-be-clicked button
        ifFormat       :    "%Y-%m-%d %H:%M", //:%S",       // format of the input field
        showsTime      :    true,
        timeFormat     :    "12",
        //singleClick		 :		false,
        electric			 :		true,
        showOthers		 :		true,
        firstDay			 :		1
  	});
}

function setupCalendar(id) {
	//alert ("setupCalendar('" + id + "')!");
	
	Calendar.setup({
        inputField     :    id,   // id of the input field
        ifFormat       :    "%Y-%m-%d %H:%M", //:%S",       // format of the input field
        showsTime      :    true,
        timeFormat     :    "12",
        //singleClick		 :		false,
        electric			 :		true,
        showOthers		 :		true,
        firstDay			 :		1
  	});
}



// cribbed from http://www.sitepoint.com/blogs/2004/05/26/closures-and-executing-javascript-on-page-load/ 21/05/2007 11:23 
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}


var pics = new Array ();

function click (elementname) {
	var d = document.getElementById(elementname);
	d.click(); 
}


// todo: this selectOpt function should probably get put into a 'general js' file, when i get around to making one of those. 20/10/2006 15:07
function selectOpt( f, s, v ){
	//alert ("selectOpt: f is '"+f+"', s is '"+s+"', v is '"+v+"'!");
	
	//var form = document.forms[f];
	//var element = form.elements.getElementById(v);
  //var opts = element.options;
  
  var opts = document.forms[f].elements[s].options;
  var o, i = opts.length;
  while ( ( o = opts[--i] ) ) {
    if ( o.value == v ) {
      o.selected = true;
      return;
    }
  }
} 

function FocusThumb (ThumbnailGroup, PicNum, TargetImg, TargetLink, TargetLinkName) {
	//alert ("TargetLink.href is " + TargetLink.href);		
	//alert ("thumbnailgroup is " + ThumbnailGroup + ", picnum is " + PicNum + ", targetimg is " + TargetImg + ", targetlink is " + TargetLink);
	//alert ("document links length is " + document.links.length  + "!");
	//alert ("enlargelink11.href is " + enlargelink11.href + "!");		
	//alert ("document.links['enlargelink11'].href is " + document.links['enlargelink11'].href + "!");		
	document.images[TargetImg].src = "ithumb.php?img=" + pics[ThumbnailGroup][PicNum] + "&w=120&border=0&bg=000000";

	if (TargetLink==null) {
		//alert ("TargetLink is null so getting '" + TargetLinkName + "'");
		TargetLink = document.getElementById (TargetLinkName);
	}
	//TargetLink.href = baseurl + "preview.php?url=" + pics[ThumbnailGroup][PicNum];
	//TargetLink.href = "preview.php?url=" + pics[ThumbnailGroup][PicNum];
	TargetLink.href = "index.php?FilePath=Preview&TargetKey=" + ThumbnailGroup + "&PicNum=" + PicNum;
	
	return true;
	
}

function MiniNewWindow(newurl, width, height) {window.open(newurl,"ministatus","status=0,height=" + height + ",width=" + width + ",toolbar=0,location=0,directories=0,menubar=0,scrollbars=0,resizeable=0");}


// these two hideElement and showElement functions copied here from EditForm.js 26/10/2006 13:28
function hideElement (elementName) {
	var e = document.getElementById (elementName);
	if (null!=e) e.style.display = 'none';
}

function showElement (elementName, displayType) { // , displayType) {
	//if (displayType=="") displayType = 'block';
	var e = document.getElementById (elementName);
	if (null!=e) e.style.display = 'block';
}

function toggleElement (elementName) {
	var e = document.getElementById (elementName);
	if (e.style.display == 'none') {
		showElement (elementName);
	} else {
		hideElement (elementName);
	}
}

function toggleElementInline (elementName) {
	var e = document.getElementById (elementName);
	if (e.style.display == 'none') {
		showElementInline (elementName);
	} else {
		hideElement (elementName);
	}
}


function showElementInline (elementName) {
	var e = document.getElementById (elementName);
	if (null!=e) {
		e.style.display = 'inline';
	} else {
		alert ("couldn't find element named '" + elementName + "'");
	}
}



function toggleDisable (elementName) {
	//alert ("toggleDisable('"+elementName+"')!");
	var e = document.getElementById (elementName);
	if (null!=e) {
		if (e.disabled!="") {
			//alert("setting currently disabled - is '" + e.disabled + "' - setting enabled");
			e.disabled = "";
		} else {
			//alert("setting to disabled");
			e.disabled = "disabled";
		}
	} else {
		alert ("toggleDisabled: Couldn't find element with ID '"+elementName+"'!");
	}
}

function hideDiv(pass) {
	//alert ("hideDiv ("+pass+")");
	var divs = document.getElementsByTagName('div');
	//alert ("Found " + divs.length + " divs!");
	//if (divs.length==0) return;
	for(i=0;i<divs.length;i++){
		//alert ("testing div " . divs[i].id);
		if(divs[i].id.match(pass)){//if they are 'see' divs
			if (document.getElementById) // DOM3 = IE5, NS6
				divs[i].style.visibility="hidden";// show/hide
			else
				if (document.layers) // Netscape 4
					document.layers[divs[i]].display = 'hidden';
				else // IE 4
					document.all.hideshow.divs[i].visibility = 'hidden';
		}
	}
	//alert ("end of hidediv ("+pass+")");
}

function showDiv(pass) {
	//alert ("showDiv ("+pass+")");
	var divs = document.getElementsByTagName('div');
	//alert ("Found " + divs.length + " divs!");	
	//if (divs.length==0) return;
	for(i=0;i<divs.length;i++){
		//alert ("testing div " . divs[i].id);
	if(divs[i].id.match(pass)){
	if (document.getElementById)
	divs[i].style.visibility="visible";
	else
	if (document.layers) // Netscape 4
	document.layers[divs[i]].display = 'visible';
	else // IE 4
	document.all.hideshow.divs[i].visibility = 'visible';
	}
	}
	//alert ("end of showdiv ("+pass+")");
}

// http://www.dustindiaz.com/top-ten-javascript/
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};


String.prototype.entityify = function () {
	return this.replace(/&/g, "&amp;").replace(/</g,
		"&lt;").replace(/>/g, "&gt;");
};



var GUIDLog = Array ();

// http://www.thescripts.com/forum/thread523253.html
function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1) }
function getGUID() {
	var value = (S4()+S4()+S4()+S4()).toUpperCase();
	while (GUIDLog.inArray (value)) {
		value = (S4()+S4()+S4()+S4()).toUpperCase();
	}

	GUIDLog.push (value);
	
	return value;
}


 function isObject(a)
 {
     return (typeof a == 'object' && !!a) || isFunction(a);
 }
 
 
 
function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
} 


function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function myoverlib (title, time) {
	return overlib(title,STICKY,CAPTION,time,CLOSECLICK);
}


/* RefreshOO.js */

function SectionHelperObject () {
	
	this.refreshers = new Array ();
	this.customfunctions = new Array ();
	
	this.NeedsRefreshing = new Array ();
	this.NeedsBlurring = new Object(); //Array(); //[]; //new Object();
	
	this.registerFormRefresher = function (FormName, TargetID) {
		//alert ("registering for '" + FormName + "' and '" + TargetID + "'");
		//if (!isarray(this.NeedsRefreshing[FormName])) {
			//alert ("creating array");
			this.NeedsRefreshing[FormName] = new Array (TargetID);
		/*} else {
			alert ("about to push");
			this.NeedsRefreshing[FormName].push(TargetID);
		}*/
		//alert ("set to " + this.NeedsRefreshing[FormName]);
	}
	
	this.registerFormBlurrer = function (FormName, TargetID) {
		//alert ("registering FormBlurrer '" + FormName + "' and '" + TargetID + "'");
		if (undefined==this.NeedsBlurring[FormName]) {
			this.NeedsBlurring[FormName] = new Array();
		}
		//this.NeedsBlurring[FormName] = new Array (TargetID);
		//this.NeedsBlurring[FormName].push(TargetID);
		//this.NeedsBlurring[FormName]
		this.NeedsBlurring[FormName].push(TargetID); //[TargetID] = TargetID;
		
		//alert ("registered FormBlurrer.");
	}
	
	this.getNeedsRefreshing = function (FormName) {
		//alert ("getNeedsRefreshing returning " + FormName + ": " + this.NeedsRefreshing[FormName] + "!");
		return this.NeedsRefreshing[FormName];
	}
	
	this.getNeedsBlurring = function (FormName) {
		//alert ("getneedsblurring returning " + this.NeedsBlurring[FormName] + " for '" + FormName + "'");
		return this.NeedsBlurring[FormName];
	}
	
	this.registerRefresh = function (blockname, divname, template, query, sourcetype, sourceid) {
		if (blockname=="") {
			alert ("registerRefresh - blockname isn't specified!");
		} /*else if (typeof this.refreshers[blockname] != 'undefined') {
			alert ("registerRefresh ('" + blockname + "', '" + divname + "', '" + template + "') is already defined!");
		}*/
		/*else {
			alert ("registerRefresh - registering '" + blockname + "'");
		}*/
		//alert ("registerRefresh - registering '" + blockname + "'");
			
		this.refreshers[blockname] = new Array (blockname, divname, template, query);
		//alert ("sizeofrefreshers is " + this.refreshers.size() +"!");
		//alert ("registerRefresh: this.refreshers['" + blockname + "'] is " + this.refreshers[blockname] + "!");
	}
	
	this.callRefresh = function (blockname, ExtendedQuery) {
		//alert ("callRefresh ('" + blockname + "','" + ExtendedQuery + "')");	
		//alert ("callRefresh: this.refreshers['" + blockname + "'] is " + this.refreshers[blockname] + "!");
		
		a = this.refreshers[blockname];
		
		if (typeof a == 'undefined') {
			alert ("callRefresh: couldn't find block '" + blockname + "'!");
			return false;
		}
		
		blockname = a[0];
		divname = a[1];
		template = a[2];
		query = a[3];
		
		//alert ("callRefresh ('" + blockname + "'): div is '" + a[1] + "', template is '" + a[2] + "', query is '" + a[3] + "'!");
		
		xajax.loadingFunction = function(){
			var item = document.getElementById (divname + '_Loading');
			if (null != item) { item.style.display='block'; }
		};
		//xajax.doneLoadingFunction = function(){xajax.$('{$functionname}_Loading').style.display='none';};
		xajax.doneLoadingFunction = function (){
			var item = document.getElementById (divname + '_Loading');
			if (null != item) { item.style.display='none'; }
		};
	
		xajax_ReplaceTemplate (divname, template, '<xjxquery><q>'+query+'&'+ExtendedQuery+'</q></xjxquery>');
	}
	
	
	this.callMultipleRefresh = function (blocknames, ExtendedQuery) {
		var multi = new Array();
		for (var i = 0 ; i < blocknames.length ; i++) {
			//alert ("CallMultipleRefresh got blockname '" + this.refreshers[blocknames[i]][0] + "'!");
			var a = this.refreshers[blocknames[i]];
			
			if (typeof a == 'undefined') {
				alert ("callRefresh: couldn't find block '" + blockname + "'!");
				return false;
			}
			
			blockname = a[0];
			divname = a[1];
			template = a[2];
			query = a[3];			
			
			//alert ("got a '" + a + "'!");
			
			multi.push (a);
		}
		
		xajax.loadingFunction = function(){
			for (var x = 0 ; x < multi.length ; x++) {
				var item = document.getElementById(multi[x][1]+'_Loading');
				if (null != item) { item.style.display='block'; }
			}
		};
		xajax.doneLoadingFunction = function(){
			for (var x = 0 ; x < multi.length ; x++) {
				var item = document.getElementById (multi[x][1]+ '_Loading');
				if (null != item) { item.style.display='none'; }
			}
		};		
		
			
		
		//alert ("got multi: " + multi + "!");
		
		xajax_MultipleReplaceTemplate(multi);
	}
	
	
	this.registerCustom = function (customname, functioncode) {
		alert ("registerCustom: Registering Custom function called '" + customname + "' with functioncode '" + functioncode + "'");
		this.customfunctions[customname] = new Array (customname, functioncode);
	}
	
	this.callCustom = function (customname) {
		alert ("callCustom: calling '" + customname + "'!");
		f = function () {
			eval (this.customfunctions[customname][1]);
		}
		f ();
	}
}


var SectionHelper = new SectionHelperObject ();







////
function setSearchMode (SearchFormName, SearchOrderName, value) {
	var SearchForm = document.getElementById(SearchFormName);
	//var SearchOrderInput = document.getElementById(SearchOrderName);
	//if (SearchOrderInput != null && SearchOrderInput.type=="select") {
		selectOpt(SearchFormName, SearchOrderName, value);
	//} else if (SearchOrderInput!=null) {
		//SearchOrderInput.value = value;
		//alert ("blah?");
	//} else {
		//alert ("couldn't find id '" + SearchFormName + "' with SearchOrderName '" + SearchOrderName + "'!");
	//}
	//alert ("setSearchMode ('" + SearchFormName + "', '" +SearchOrderName + "', '" + value + "'): about to submit!");

	/*if (null==SearchForm) {
		alert ("setSearchMode SearchForm '" + SearchFormName + "' is null!");
	}	else {
		alert ("setSearchMode Got SearchForm '" + SearchFormName + "'!");
	}*/
	
	//alert ("SearchForm's Action is '" + SearchForm.action +"'!");
	var t = typeof(SearchForm.onsubmit);
	if (t=="undefined") {
		//alert (".submit()ing form because t is '" + t + "'");
		SearchForm.submit ();
	} else {
		//alert ("onsubmitting() form because t is '" + t + "'");
		SearchForm.onsubmit();
	}
}

function setSearchPageNumber (SearchFormName, Prefix, value ) {
	//alert ("setSearchPageNumber got '" + SearchFormName + "', '" + Prefix + "', '" + value + "'!");
	
	var SearchForm = document.getElementById(SearchFormName);
	
	var el = document.getElementById(""+Prefix+"PageNum");
	
	//alert ("el disabled is at first '" + el.disabled + "'");
	//el.setAttribute("disabled", "");
	el.disabled = false;
	el.setAttribute("value", value);
	
	//el.setAttribute("disabled", '');
	//alert ("el disabled is now '" + el.disabled + "'");
	
	/*var newinp = document.createElement('input');
	newinp.setAttribute('id', Prefix+SearchFormName);
	newinp.setAttribute('name', Prefix+"PageLimit");
	newinp.value = PageNumber;

	SearchForm.addElement (newinp);	*/
	
	var t = typeof(SearchForm.onsubmit);
	if (t=="undefined") {
		SearchForm.submit ();
	} else {
		SearchForm.onsubmit ();
	}	
}




/* this QuickPick stuff copy&pasted here from EditForm.js 23/06/2008 13:19:30 because we need QuickPick functionality for search forms too now (and have done for ages) */
function pre_xajax_ShowQuickPick(displayid, idid, SourceType, prepend) {
	//alert ("pre_xajax_ShowQuickPIck - prepend is '" + prepend + "'");
	var d = document.getElementById(displayid);
	var i = document.getElementById(idid);
	
	var SearchText = d.value;
	
	if (prepend==undefined) prepend = "";
	//alert ("prepend is '" + prepend + "'");
	
	return xajax_ShowQuickPick(displayid, idid, SourceType, SearchText, prepend);
}

function QuickPick_selectdirect (displayid, idid, selectedname, selectedid, prepend) {
	//alert ("QuickPick_selectdirect ('" + displayid + "', '" + idid + "', '" + selectedname + "', '" + selectedid + "', '" + prepend + "')");
	
	var d=document.getElementById(displayid); 
	var i=document.getElementById(idid); 

	if (prepend!=undefined)
		i.value = prepend + selectedid;
	else
		i.value = selectedid;
		
	//alert ("set value to '" + i.value + "'");
	d.value = selectedname;
	
	showElementInline (idid + "_verified_true");
	hideElement 			(idid + "_verified_false");
}

function QuickPick_close (id) {
	//alert ("got QuickPick_close " + id + "!");
	hideElement (id);
}

function QuickPick_select(displayid, idid, resultsid, prepend) {
	//var d=document.getElementById(displayid); 
	//var i=document.getElementById(idid); 
	
	if (prepend==undefined) prepend = "";
	
	var src=document.getElementById(resultsid); 
	
	if (src.selectedIndex>=0) {	
		var t = src.options[src.selectedIndex].text; 
		if (t=="") t = src.options[src.selectedIndex].textContent;
		
		//alert ("about to QuickPick_selectdirect ('" + displayid + "', '" + idid + "', '" + t + "', '" + src.options[src.selectedIndex].value);
		
		QuickPick_selectdirect (displayid, idid, t, src.options[src.selectedIndex].value, prepend);
	} else {
		alert ("QuickPick error: Nothing selected!");
	}
	
	//d.value = t; 
	//i.value = src.options[src.selectedIndex].value;
	
	//alert ("set " + idid + " to '" + i.value + "'")
	
}




function disableform(form) {
	for (i = 0 ; i < form.elements.length ; i++) {
		if (form.elements[i].id!="" && (form.elements[i].value=="" || form.elements[i].value==null)) {
			//alert ("disabling " + form.elements[i].id + "!");
			form.elements[i].name = "";
			form.elements[i].disabled = true;
		}
	}
	//alert ("disabled stuff!");
	//return true;
}


function handleEndUpload (SelectorID, TargetType, SourceType, endfileNames) {
	alert ("finsihed uploading!");
	alert ("handleEndUpload got TargetType '" + TargetType + "' and SourceType '" + SourceType + "'!");
	for (var i = 0 ; i < endfileNames.length ; i++) {
		fn = endfileNames[i];
		alert ("calling selectfile on '" + fn + "'!");		
		xajax_SelectFile(SelectorID, null, "<xjxquery><q>TargetType="+TargetType+"&SourceType="+SourceType+"&Filename="+fn+"</q></xjxquery>");
		alert ("did selectfile on '" + endfileNames[i] + "'!");
	}
	alert ("out of handleEndUpload");
}



/* from comments at: http://www.geekwisdom.com/dyn/passwdmeter */
function testPassword(passwd)
{
		var intScore   = 0
		var strVerdict = "weak"
		var strLog     = ""
		
		// PASSWORD LENGTH
		if (passwd.length<5)                         // length 4 or less
		{
			intScore = (intScore+3)
			strLog   = strLog + "3 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>4 && passwd.length<8) // length between 5 and 7
		{
			intScore = (intScore+6)
			strLog   = strLog + "6 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>7 && passwd.length<16)// length between 8 and 15
		{
			intScore = (intScore+12)
			strLog   = strLog + "12 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>15)                    // length 16 or more
		{
			intScore = (intScore+18)
			strLog   = strLog + "18 point for length (" + passwd.length + ")\n"
		}
		
		
		// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
		if (passwd.match(/[a-z]/))                              // [verified] at least one lower case letter
		{
			intScore = (intScore+1)
			strLog   = strLog + "1 point for at least one lower case char\n"
		}
		
		if (passwd.match(/[A-Z]/))                              // [verified] at least one upper case letter
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one upper case char\n"
		}
		
		// NUMBERS
		if (passwd.match(/\d+/))                                 // [verified] at least one number
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one number\n"
		}
		
		if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/))             // [verified] at least three numbers
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least three numbers\n"
		}
		
		
		// SPECIAL CHAR
		if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one special char\n"
		}
		
									 // [verified] at least two special characters
		if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least two special chars\n"
		}
	
		
		// COMBOS
		if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))        // [verified] both upper and lower case
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for upper and lower letters\n"
		}

		if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) // [verified] both letters and numbers
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters and numbers\n"
		}
 
									// [verified] letters, numbers, and special characters
		if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/))
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters, numbers and special chars\n"
		}
	
		//intScore += 5; // doctea hacky level booster :P
		
		if(intScore < 16)
		{
		   strVerdict = "very weak"
		}
		else if (intScore > 15 && intScore < 25)
		{
		   strVerdict = "weak"
		}
		else if (intScore > 24 && intScore < 35)
		{
		   strVerdict = "mediocre"
		}
		else if (intScore > 34 && intScore < 45)
		{
		   strVerdict = "strong"
		}
		else
		{
		   strVerdict = "stronger"
		}
	
	//document.forms.passwordForm.score.value = (intScore)
	//document.forms.passwordForm.verdict.value = (strVerdict)
	//document.forms.passwordForm.matchlog.value = (strLog)
	
	return strVerdict;
	
}