// this function creates a shadowbox-like effect in Scribe Admin
// the div to remain 'lit' is sent to this function
function dimmer(nodim)
{
	$('body').toggleClass('dimmed'); 
	$(nodim).toggleClass('no-dim'); 
}

function addListener(element, type, expression, bubbling)
{
	bubbling = bubbling || false;
	
	if(window.addEventListener)	{ // Standard
		element.addEventListener(type, expression, bubbling);
		return true;
	} else if(window.attachEvent) { // IE
		element.attachEvent('on' + type, expression);
		return true;
	} else return false;
}
// toggle collapsible menu items and store cookie
function toggleMenu(trigger, target, cookie) {
	$(trigger).toggleClass('hidden');
	$(target).toggle('blind', '', 800);
	toggleCookie(target, 'hide', 'show')
}
function toggleCookie(name, toggle1, toggle2) // toggle the state of a cookie using jquery cookie plugin
{
	name = name.replace(/[^a-zA-Z 0-9 -]+/g,''); // strip non alpha numeric characters
	//alert(name); return false;
	var cookie = $.cookie(name);
	if (cookie == null) {
		cookie = toggle1;
	} else if (cookie == toggle1) {
		cookie = toggle2;
	} else {
		cookie = toggle1;
	}
	$.cookie(name, cookie, { expires: 30 });
}


function toggle_it(itemID){
	var ids = itemID.split(",");
	
	for(i = 0; i < ids.length; i++) {
    	// Toggle visibility between none and inline
      	if ((document.getElementById(ids[i]).style.display == 'none'))
      	{
			//document.getElementById(ids[i]).style.display = 'block'; <- stopped working 17/11/08 not sure why //
			document.getElementById(ids[i]).style.display = '';
        	if (oddeven == 'odd') {
				document.getElementById(ids[i]).style.background = 'transparent';
				var oddeven = 'even';
			} else {
				document.getElementById(ids[i]).style.background = '#f9f4fa';
				var oddeven = 'odd';
			}
      	} else {
        	document.getElementById(ids[i]).style.display = 'none';
        	document.getElementById(ids[i]).style.background = 'transparent';
      	}
	}
}
function toggleDisplay(itemname)
{
    tmp = document.getElementsByTagName('div');
    for (i=0;i<tmp.length;i++)
    {
         if (tmp[i].className == itemname) tmp[i].style.display = 'none';
    }
}

function toggleDisplay02(obj,fromclassname,toclassname) {
	var el = document.getElementById(obj);
	if ( el.className == fromclassname ) {
		el.className = toclassname;
	}
	else {
		el.className = fromclassname;
	}
}

function toggle_help_module() {
	$('#module-help').toggle('blind', '', 800);
/* below was used for old SPRY approach
	var ID = 'module-help';
	var el = document.getElementById(ID);
	var fromclassname = 'hide';
	if (el.className == 'hidden') {
		//MM_effectBlind(ID, 800, '0%', '100%', true);
		$('#'+ID).toggle('blind', '', 800);
		el.className = '';
	} else {
		if ( el.className == fromclassname ) {
		el.className = '';
		}
		else {
			el.className = fromclassname;
		}
		//MM_effectBlind(ID, 800, '100%', '0%', true);
		$('#'+ID).toggle('blind', '', 800);
	}
*/
}

function toggle_show_hide_help_module()
{
	var id = 'show-hide-help-module';
	var el = document.getElementById(id);
	
	var text = ' help in all modules'
	var show_text = 'Show'+text;
	var hide_text = 'Hide'+text;
	
	if(el.innerHTML==show_text) {
		createCookie("show_help",true,365000);
		el.innerHTML = hide_text;
	} else {
		toggle_help_module();
		createCookie("show_help",false,365000);
		el.innerHTML = show_text;
	}
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function swapPlusMinusImg(imgID) {
	var img = document.getElementById(imgID);
	var string = img.src;
	
	if (string.match('minus')) {
		img.src = '/scribe/sites/all/scripts/drag-drop-folder-tree/images/dhtmlgoodies_plus.gif';
	} else {
		img.src = '/scribe/sites/all/scripts/drag-drop-folder-tree/images/dhtmlgoodies_minus.gif';
	}
}

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == "none")
    e.style.display = "block";
    else
    e.style.display = "none";
}

function changePage(newLoc)
 {
   nextPage = newLoc.options[newLoc.selectedIndex].value;
		
   if (nextPage != "")
   {
      document.location.href = nextPage;
   }
 }

function confirm_window(message, url) 
{
	if(confirm(message)) location.href = url;
}

function pausejavascript(milliseconds) {
	var date = new Date();
	var curDate = null;

	do { 
		curDate = new Date(); 
	} while(curDate-date < milliseconds);
}

function checkUncheckAll(theElement) {
	var theForm = theElement.form, z = 0;
 	for(z=0; z<theForm.length;z++){
		if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
			theForm[z].checked = theElement.checked;
		}
 	}
}

function check_uncheck_all(scope, controller) {
	select_all_state = document.getElementById(controller).checked;
	$("#"+scope+" input:checkbox").each(function() {
		if(this.value!="on") {
			this.checked = select_all_state;
		}
	});
}

function checkUncheckSome(controller,theElements) {
	//Programmed by Shawn Olson
	//Copyright (c) 2006-2007
	//Updated on August 12, 2007
	//Permission to use this function provided that it always includes this credit text
	//  http://www.shawnolson.net
	//Find more JavaScripts at http://www.shawnolson.net/topics/Javascript/

	//theElements is an array of objects designated as a comma separated list of their IDs
	//If an element in theElements is not a checkbox, then it is assumed
	//that the function is recursive for that object and will check/uncheck
	//all checkboxes contained in that element

     var formElements = theElements.split(',');
	 var theController = document.getElementById(controller);
	 for(var z=0; z<formElements.length;z++){
	  theItem = document.getElementById(formElements[z]);
	  if(theItem.type){
	    if (theItem.type=='checkbox') {
	    	theItem.checked=theController.checked;
	    }
	  } else {
	  	  theInputs = theItem.getElementsByTagName('input');
	  for(var y=0; y<theInputs.length; y++){
	  if(theInputs[y].type == 'checkbox' && theInputs[y].id != theController.id){
	     theInputs[y].checked = theController.checked;
	    }
	  }
	  }
    }
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}


/* =============================================================================== */
/* Dreamweaver */

function MM_effectAppearFade(targetElement, duration, from, to, toggle)
{
	Spry.Effect.DoFade(targetElement, {duration: duration, from: from, to: to, toggle: toggle});
}

function MM_effectBlind(targetElement, duration, from, to, toggle)
{
	Spry.Effect.DoBlind(targetElement, {duration: duration, from: from, to: to, toggle: toggle});
}


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_changeProp(objName,x,theProp,theValue) { //v6.0
  var obj = MM_findObj(objName);
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false)
      eval("obj."+theProp+"="+theValue);
    else eval("obj."+theProp+"='"+theValue+"'");
  }
}
function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function MM_setTextOfTextfield(objId,x,newText) { //v9.0
  with (document){ if (getElementById){
    var obj = getElementById(objId);} if (obj) obj.value = newText;
  }
}


/* Select all checkboxes in a group =====================
 * Use this function if there are groups of checkboxes in a single form
 * When a select all checkbox of id all_XYZ is checked, checkboxes with class XYZ are checked */
var checkbox_group = {}
function selectCheckboxGroup(obj) {
    var checkbox_class = obj.id.substring(4);
    var boxes = $("input." + checkbox_class);
    if (!checkbox_group[checkbox_class])
        checkbox_group[checkbox_class] = obj.checked;
    else
        checkbox_group[checkbox_class] = !checkbox_group[checkbox_class];
    for (var x=0; x<boxes.length; x++)
        boxes[x].checked = checkbox_group[checkbox_class];
}
/* /Select all checkboxes in a group =====================

/* Sweet Titles =============================================================================== 
Sweet Titles (c) Creative Commons 2005
http://creativecommons.org/licenses/by-sa/2.5/
Author: Dustin Diaz | http://www.dustindiaz.com
*/
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
	
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

var sweetTitles = { 
	xCord : 0,								// @Number: x pixel value of current cursor position
	yCord : 0,								// @Number: y pixel value of current cursor position
	tipElements : ['a','abbr','acronym','label','h2','h3','input','p'],	// @Array: Allowable elements that can have the toolTip
	obj : Object,							// @Element: That of which you're hovering over
	tip : Object,							// @Element: The actual toolTip itself
	active : 0,								// @Number: 0: Not Active || 1: Active
	init : function() {
		if ( !document.getElementById ||
			!document.createElement ||
			!document.getElementsByTagName ) {
			return;
		}
		var i,j;
		this.tip = document.createElement('div');
		this.tip.id = 'toolTip';
		document.getElementsByTagName('body')[0].appendChild(this.tip);
		this.tip.style.top = '0';
		this.tip.style.visibility = 'hidden';
		var tipLen = this.tipElements.length;
		for ( i=0; i<tipLen; i++ ) {
			var current = document.getElementsByTagName(this.tipElements[i]);
			var curLen = current.length;

			for ( j=0; j<curLen; j++ ) {
				if (current[j].getAttribute('title') != null && current[j].getAttribute('title') != "") { //jez edit
					addEvent(current[j],'mouseover',this.tipOver);
					addEvent(current[j],'mouseout',this.tipOut);
					current[j].setAttribute('tip',current[j].title);
					current[j].removeAttribute('title');
				} //jez edit
			}
		}
	},
	updateXY : function(e) {
		if ( document.captureEvents ) {
			sweetTitles.xCord = e.pageX;
			sweetTitles.yCord = e.pageY;
		} else if ( window.event.clientX ) {
			sweetTitles.xCord = window.event.clientX+document.documentElement.scrollLeft;
			sweetTitles.yCord = window.event.clientY+document.documentElement.scrollTop;
		}
	},
	tipOut: function() {
		if ( window.tID ) {
			clearTimeout(tID);
		}
		if ( window.opacityID ) {
			clearTimeout(opacityID);
		}
		sweetTitles.tip.style.visibility = 'hidden';
	},
	checkNode : function() {
		var trueObj = this.obj;
		if ( this.tipElements.inArray(trueObj.nodeName.toLowerCase()) ) {
			return trueObj;
		} else {
			return trueObj.parentNode;
		}
	},
	tipOver : function(e) {
		sweetTitles.obj = this;
		tID = window.setTimeout("sweetTitles.tipShow()",500);
		sweetTitles.updateXY(e);
	},
	tipShow : function() {		
		var scrX = Number(this.xCord);
		var scrY = Number(this.yCord);
		var tp = parseInt(scrY+15);
		var lt = parseInt(scrX+10);
		var anch = this.checkNode();
		var addy = '';
		var access = '';
		if ( anch.nodeName.toLowerCase() == 'a' ) {
			addy = (anch.href.length > 25 ? anch.href.toString().substring(0,25)+"..." : anch.href);
			var access = ( anch.accessKey ? ' <span>['+anch.accessKey+']</span> ' : '' );
		} else {
			addy = anch.firstChild.nodeValue;
		}
		// original // this.tip.innerHTML = "<p>"+anch.getAttribute('tip')+"<em>"+access+addy+"</em></p>";
		this.tip.innerHTML = "<p>"+anch.getAttribute('tip')+"</p>";
		if ( parseInt(document.documentElement.clientWidth+document.documentElement.scrollLeft) < parseInt(this.tip.offsetWidth+lt) ) {
			this.tip.style.left = parseInt(lt-(this.tip.offsetWidth+10))+'px';
		} else {
			this.tip.style.left = lt+'px';
		}
		if ( parseInt(document.documentElement.clientHeight+document.documentElement.scrollTop) < parseInt(this.tip.offsetHeight+tp) ) {
			this.tip.style.top = parseInt(tp-(this.tip.offsetHeight+10))+'px';
		} else {
			this.tip.style.top = tp+'px';
		}
		this.tip.style.visibility = 'visible';
		this.tip.style.opacity = '.1';
		this.tipFade(50);
	},
	tipFade: function(opac) {
		var passed = parseInt(opac);
		var newOpac = parseInt(passed+10);
		if ( newOpac < 80 ) {
			this.tip.style.opacity = '.'+newOpac;
			this.tip.style.filter = "alpha(opacity:"+newOpac+")";
			opacityID = window.setTimeout("sweetTitles.tipFade('"+newOpac+"')",20);
		}
		else { 
			this.tip.style.opacity = '.90';
			this.tip.style.filter = "alpha(opacity:90)";
		}
	}
};
function pageLoader() {
	sweetTitles.init();
}
addEvent(window,'load',pageLoader);

/* /Sweet Titles =============================================================================== */

/* URL encoding ===================== */
function urlencode (str) {
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };

    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();

    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

/* /URL encoding ===================== */
