function toggleDiv(id,flagit) {
if (flagit=='1'){
	if (document.layers) document.layers[''+id+''].visibility = 'show'; //for Mac/Older Mozilla
	else if (document.all) document.all[''+id+''].style.visibility = 'visible'; //for Older IE
	else if (document.getElementById) document.getElementById(''+id+'').style.visibility = 'visible'; //for New IE/Mozilla
	}
else if (flagit=='0'){
	if (document.layers) document.layers[''+id+''].visibility = 'hide'; //for Mac/Older Mozilla
	else if (document.all) document.all[''+id+''].style.visibility = 'hidden'; //for Older IE
	else if (document.getElementById) document.getElementById(''+id+'').style.visibility = 'hidden'; //for New IE/Mozilla
	}
};

toggleArrow = function(obj, divId){
	//To Use: <a href="#yourDivID" onclick="toggleArrow(this,'yourDivID');" class="toggleArrow">&nbsp;</a>
	if(obj){
		if(obj.style.backgroundPosition == '0px 16px') {
			obj.style.backgroundPosition = '0px 0px';
			if($(divId)) $(divId).style.display = 'none';
		}
		else {
			obj.style.backgroundPosition = '0px 16px';
			if($(divId)) $(divId).style.display = 'block';
		}
	}
};

loadEditor = function(varURL){
	NewWindow = window.open(varURL,'ED','width=750,height=575,toolbar=No,location=No,scrollbars=No,status=No,resizable=No,fullscreen=No'); 
	NewWindow.focus(); 
	void(0);
};

getElementLeft = function (ele) {
	xPos = ele.offsetLeft;
	tempEl = ele.offsetParent;
	while (tempEl != null) {
		xPos += tempEl.offsetLeft;
		tempEl = tempEl.offsetParent;
	}
	return xPos;
};


function getElementTop(ele) {
	yPos = ele.offsetTop;
	tempEl = ele.offsetParent;
	while (tempEl != null) {
		yPos += tempEl.offsetTop;
		tempEl = tempEl.offsetParent;
	}
	return yPos;
};

enterEditDiv = function(ele, btn){
	$(ele).className = 'editDiv';
	$(btn).style.display = 'block';
};

exitEditDiv = function(ele, btn){
	$(ele).className = '';
	$(btn).style.display = 'none';
};

getMultiSelectValue = function(fieldID){
  var selectedArray = new Array();
  $('#'+fieldID+' option:selected').each(function(i, selected){
    selectedArray.push($(selected).val());
  });
  return selectedArray.toString();
};

getMultiSelectName = function(fieldID){
  var selectedArray = new Array();
  $('#'+fieldID+' option:selected').each(function(i, selected){
    selectedArray.push($(selected).text());
  });
  return selectedArray.toString();
};

getCheckBoxListValues = function(list){
	var ele = document.getElementsByName(list);
	var ids = new Array();
	for(var i = 0; i < ele.length; i++){
		if(ele[i].checked){
			ids.push(ele[i].value);
		}
	}
	return ids.toString();
};

removeChars = function(varStr, varRem){
	varFinish = '';
	for(var i = 0; i < varStr.length; i++){
		if(varStr.charAt(i) != varRem){
			varFinish = varFinish + varStr.charAt(i);
		}
	}
	return varFinish;
};

replaceChars = function(varStr, varOld, varNew){
	varFinish = varStr;
	for(var i = 0; i < varStr.length; i++){
		if(varStr.charAt(i) == varOld){
			varFinish = varFinish.substr(0, i) + " " + varFinish.substr(i + 1, varFinish.length);
		}
	}
	return varFinish;
};

trimLeft = function(s){
	var trimedLeft = s.split("");
	if(trimedLeft.length > 0){
		while(trimedLeft[0] == " "){
			trimedLeft.shift();
		}
	}
	return(trimedLeft.join(""));
};

trimRight = function(s){
	var trimedRight = s.split("");
	if(trimedRight.length > 0){
		while(trimedRight[trimedRight.length - 1] == " "){
			trimedRight.pop();
		}
	}
	return(trimedRight.join(""));
};

trim = function(s){
	var trimed = s;
	if(trimed.length > 0){
		trimed = trimLeft(trimed);
		trimed = trimRight(trimed);
	}
	return(trimed);
};

validateSESChars = function(str){
	re = /^[\/a-zA-Z0-9_\-]+$/;
	var res = re.test(trim(str));
	return res;
};

textAreaCounter = function(varTA, varDisplay, maxChar){
	if(varTA.value.length > maxChar){
		varTA.value = varTA.value.substring(0, maxChar);
	}else{
		varDisplay.innerHTML = maxChar - varTA.value.length;
	}
};

openNewWindow = function(URLtoOpen, windowName, windowFeatures){
	newWindow=window.open(URLtoOpen, windowName, windowFeatures); 
};

/*
clear default value from form input on click
*/

function clearText(thefield){
if (thefield.defaultValue==thefield.value)
	thefield.value = ""
};

getCheckedValue = function(ele){ //pass in document.getElementsByName('XXXXX')
	if(!ele){
		return '';
	}
	var radioLength = ele.length;
	if(radioLength == undefined)
		if(ele.checked)
			return ele.value;
		else
			return '';
	for(var i = 0; i < radioLength; i++) {
		if(ele[i].checked) {
			return ele[i].value;
		}
	}
	return '';
};

function dateAddExtention(p_Interval, p_Number){


   var thing = new String();
   
   
   //in the spirt of VB we'll make this function non-case sensitive
   //and convert the charcters for the coder.
   p_Interval = p_Interval.toLowerCase();
   
   if(isNaN(p_Number)){
   
      //Only accpets numbers 
      //throws an error so that the coder can see why he effed up   
      throw "The second parameter must be a number. \n You passed: " + p_Number;
      return false;
   };

   p_Number = new Number(p_Number);
   switch(p_Interval.toLowerCase()){
      case "yyyy": {// year
         this.setFullYear(this.getFullYear() + p_Number);
         break;
      }
      case "q": {      // quarter
         this.setMonth(this.getMonth() + (p_Number*3));
         break;
      }
      case "m": {      // month
         this.setMonth(this.getMonth() + p_Number);
         break;
      }
      case "y":      // day of year
      case "d":      // day
      case "w": {      // weekday
         this.setDate(this.getDate() + p_Number);
         break;
      }
      case "ww": {   // week of year
         this.setDate(this.getDate() + (p_Number*7));
         break;
      }
      case "h": {      // hour
         this.setHours(this.getHours() + p_Number);
         break;
      }
      case "n": {      // minute
         this.setMinutes(this.getMinutes() + p_Number);
         break;
      }
      case "s": {      // second
         this.setSeconds(this.getSeconds() + p_Number);
         break;
      }
      case "ms": {      // second
         this.setMilliseconds(this.getMilliseconds() + p_Number);
         break;
      }
      default: {
      
         //throws an error so that the coder can see why he effed up and
         //a list of elegible letters.
         throw   "The first parameter must be a string from this list: \n" +
               "yyyy, q, m, y, d, w, ww, h, n, s, or ms.  You passed: " + p_Interval;
         return false;
      }
   }
   return this;
};
Date.prototype.dateAdd = dateAddExtention; 

/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		};

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		};

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

fireEvent = function(obj,evt){
	var fireOnThis = obj;
	if( document.createEvent ) {
	  var evObj = document.createEvent('MouseEvents');
	  evObj.initEvent( evt, true, false );
	  fireOnThis.dispatchEvent(evObj);
	} else if( document.createEventObject ) {
	  fireOnThis.fireEvent('on'+evt);
	}
	/*
	use this to call this function:
	fireEvent(document.getElementById("grey_link"),'click');
	*/
};

showStatus = function(s, imgID){
	imgID = imgID || 'statusImage';
	switch(s){
		case 0:
			$(imgID).src = '/images/admin/transparent.gif';
			break;
		case 1:
			$(imgID).src = '/images/admin/waiting.gif';
			break;
		case 2:
			$(imgID).src = '/images/admin/updated.gif';
			break;
		case 3:
			$(imgID).src = '/images/admin/error.gif';
			break;
	}
};

clearField = function(ele){
	ele.value = '';
};

getVarClear = function(){
	var d = new Date();
	var varClear = d.getTime();
	return varClear;
};

/** jQuery Plugin's **/
(function($){$.fn.extend({ 

	spinner: function(opts){/** Spinner jQuery Plugin [Usage: $('.controls_row').spinner({status:'updated'});] **/
		var defaults = {
			status : 'waiting',
			remove : false
		};
		var opts = $.extend(defaults,opts);
		return this.each(function(){
			if(opts.remove){
				$(this).children('.spinner').remove();
				$(this).children('input,button').removeAttr('disabled').css('color','#555555');
			}else{
				if($(this).children('.spinner').get(0) == null){
					 $(this).append('<img src="/images/admin/' + opts.status + '.gif" class="spinner" align="absmiddle" alt="' + opts.status + '" />');
				}else{
					 $(this).children('.spinner').attr('src','/images/admin/' + opts.status + '.gif');
					 $(this).children('.spinner').attr('alt',opts.status);
				}
				if(opts.status == 'waiting'){
					$(this).children('input,button').attr('disabled','disabled').css('color','#D3D3D3');
				}else{
					$(this).children('input,button').removeAttr('disabled').css('color','#555555');	
				}
			}
		});
	},
	counter: function(opts){/** Spinner jQuery Plugin [Usage: $('textarea#tdc_summary').counter({errorContainer:'span#char_counter',charLimit:255});] **/	
		var defaults = {
			charLimit : 255
		};
		var opts = $.extend(defaults,opts);
		return this.each(function(){
			var obj = $(this);
			var errorContainer = obj.attr('id') + '_counter';
			var charLength = obj.val().length;
			var charsRemain = opts.charLimit - charLength;
			obj.after($('<span id="' + errorContainer + '" class="char_counter ui-state-highlight ui-corner-all">Characters Remaining: <strong>' + charsRemain + '</strong></span>'));
			// Alerts when remaining chars is @ 10
			obj.bind('keyup click focus blur',function(e){
				var obj = $(this);
				var charLength = obj.val().length;
				var charsRemain = opts.charLimit - charLength;
				var errorContainer = $('#' + obj.attr('id') + '_counter');
				if(charLength > (opts.charLimit - 11)){
					errorContainer.css('color','#900');
					// Alerts when charLimit is reached
					if(charLength > opts.charLimit){
						obj.addClass('limit-error');
						errorContainer.css('color','');
						errorContainer.addClass('ui-state-error');
						errorContainer.removeClass('ui-state-highlight');
					}else if(charLength <= opts.charLimit){
						obj.removeClass('limit-error');
						errorContainer.removeClass('ui-state-error');
						errorContainer.addClass('ui-state-highlight');
					}
				}else{
					errorContainer.css('color','');
					obj.removeClass('limit-error');
					errorContainer.removeClass('ui-state-error');
					errorContainer.addClass('ui-state-highlight');
				}
				errorContainer.html('Characters Remaining: <strong>' + charsRemain + '</strong>');
			});
		});
	}
})})($);

$(function (){	
	$('.ui_hover').hover(function() {
		$(this).addClass('ui-state-hover');
	}, function() {
		$(this).removeClass('ui-state-hover');
	});		
	
	$('.target_blank').attr('target','_blank');
});

modalMsg = function(t,m,f,c){
	$('body').prepend('<div id="dialog-alert">'+m+'</div>');
	
	if(c){
		$('#dialog-alert').dialog({
			modal:true,
			title:t,
			buttons: {
				'Cancel': function(){
					$(this).dialog("close");
				},
				'Ok': function(){
					eval(f);
					$(this).dialog("close");
				}
			}
		});
	}else if(f){
		$('#dialog-alert').dialog({
			modal:true,
			title:t,
			buttons: {
				'Ok': function(){
					eval(f);
					$(this).dialog("close");
				}
			}
		});
	}else{
		$('#dialog-alert').dialog({
			modal:true,
			title:t,
			buttons: {
				'Ok': function(){
					$(this).dialog("close");
				}
			}
		});
	};

};

resizeFancybox = function(w){
	$('#fancybox-wrap').width(w+20);
	$('#fancybox-content').width(w);
	$.fancybox.center();
};
resizeElement = function(eid,h,w){
	$('#'+eid).height(h).width(w);
};

(function($,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  $.fn.serializeObject = function(){
    var obj = {};
    
    $.each( this.serializeArray(), function(i,o){
      var n = o.name,
        v = o.value;
        
        obj[n] = obj[n] === undefined ? v
          : $.isArray( obj[n] ) ? obj[n].concat( v )
          : [ obj[n], v ];
    });
    
    return obj;
  };
  
})(jQuery);
