
// +-------------------------------------------------------------+
// | DeskPRO v3.1.0  Build #5063
// | Copyright (C) 2001 - 2006 Headstart Solutions Limited
// | http://www.deskpro.com    |     support@deskpro.com
// +-------------------------------------------------------------+
// | DESKPRO IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than www.deskpro.com or if you have otherwise received
// | this software from someone who is not a representative of
// | this organization you are involved in an illegal activity.
// | License agreement: http://www.deskpro.com/license.php
// +-------------------------------------------------------------+
// | License ID : 1164547046
// | License Owner : Anderson School District Five
// | Licensed Location : support.anderson5.net
// +-------------------------------------------------------------+
// | $Id: general.js 4724 2007-10-20 05:00:19Z chroder $
// +-------------------------------------------------------------+
// | File Details:
// | -
// +-------------------------------------------------------------+

var monthLength = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

function insertAtCaret (textEl, text) {

	textEl.focus();
	textLen = text.length;

	// Fix bug with newlines
	if (textLen != text.replace(/\r?\n/g, '_').length) {
		textLen = text.replace(/\r?\n/g, '_').length;
	}

	if (typeof(textEl.selectionStart) != 'undefined') {
		var opn = textEl.selectionStart + 0;
		var scrollpos = textEl.scrollTop;

		textEl.value = textEl.value.substr(0, textEl.selectionStart) + text + textEl.value.substr(textEl.selectionEnd);

		textEl.selectionStart = opn + textLen;
		textEl.selectionEnd = opn + textLen;

		textEl.scrollTop = scrollpos;

	} else if (document.selection && document.selection.createRange) {
		var sel = document.selection.createRange();
		sel.text = text.replace(/\r?\n/g, '\r\n');
		sel.moveStart('character', -textLen);

	} else {
		textEl.value += text;
	}
}

function resetselect(obj, value) {

	if (obj.value == value){
		obj.value = '';
	} else {
		obj.select();
	}
}

function checkDate(name)
{
	var x = document.forms[0].elements;
	var day = parseInt(x[name+"_day"].options[x[name+"_day"].selectedIndex].value);
	var month = parseInt(x[name+"_month"].options[x[name+"_month"].selectedIndex].value);
	var year = parseInt(x[name+"_year"].options[x[name+"_year"].selectedIndex].value);

	if (!day || !month || !year)
		return false;

	if (year/4 == parseInt(year/4))
		monthLength[1] = 29;

	if (day > monthLength[month-1])
		return false;

	monthLength[1] = 28;

	var now = new Date();
	now = now.getTime(); //NN3

	var dateToCheck = new Date();
	dateToCheck.setYear(year);
	dateToCheck.setMonth(month-1);
	dateToCheck.setDate(day);
	var checkDate = dateToCheck.getTime();

	var futureDate = (now < checkDate);
	var pastDate = (now > checkDate);

	return pastDate;
}

function myPrint() {
    if (window.print) {
        if (confirm("Print Page?")) {
            window.print();
        }
    }
}

function showTime(name, full) {

	document.getElementById(name + '_start_day').options[0].selected = true;
	document.getElementById(name + '_start_month').options[0].selected = true;
	document.getElementById(name + '_start_year').options[0].selected = true;
	document.getElementById(name + '_end_day').options[0].selected = true;
	document.getElementById(name + '_end_month').options[0].selected = true;
	document.getElementById(name + '_end_year').options[0].selected = true;

	visyes(name + '_time');
	visno(name + '_date');

	if (full) {
		visno(name + '_time_closed');
		visyes(name + '_time_open');

	} else {
		visyes(name + '_time_closed');
		visno(name + '_time_open');
	}
}

function showCalendar(name, full) {

	document.getElementById(name + '_start_datetype').options[0].selected = true;
	document.getElementById(name + '_end_datetype').options[0].selected = true;
	document.getElementById(name + '_start_number').value = '';
	document.getElementById(name + '_end_number').value = '';

	visno(name + '_time');
	visyes(name + '_date');

	if (full) {
		visno(name + '_date_closed');
		visyes(name + '_date_open');
		visyes(name + '_date_open2');
	} else {
		visyes(name + '_date_closed');
		visno(name + '_date_open');
		visno(name + '_date_open2');
	}
}

function delRow(aTable, keyrow) {
	aRow = aTable.deleteRow(keyrow-1);
}

function storeCaret(textEl) {
    if (textEl.createTextRange) {
        textEl.caretPos = document.selection.createRange().duplicate();
	}
}

function showdata(category) {

	// empty old rows
	for (m=document.forms['dpform'].list3.options.length;m>=0;m--) {
		document.forms['dpform'].list3.options[m]=null;
	}

	// create new rows
	if (category != '') {
		var a = 0;
		for(i in reply[category]) {
			document.forms['dpform'].list3.options[a] = new Option(reply[category][i], i);
			a++;
		}
	}
}

function insert_quickreply(ticketId, options) {

	options = $.extend({
		toggle: '#quick_reply_button, #quick_reply_loading',
		textarea: '#reply',
		list: '#quick_reply_list'
	}, options);

	var quickReplyId = DeskPRO.Forms.getValue($(options.list).get(0));

	if (!quickReplyId) {
		alert('Please select a quick reply');
		return;
	}

	$(options.toggle).toggle();

	$.ajax({

		url: '../rpc/quickreply.php',
		data: { id: quickReplyId, ticketid: ticketId },
		dataType: 'json',

		success: function(data) {
			if (!data || !data.quickReply) {
				return;
			}

			var txt = $(options.textarea).get(0);
			insertAtCaret(txt, data.quickReply);
			txt.focus();
		},

		complete: function() {
			$(options.toggle).toggle();
		}
	});

}

function in_array(ineedle, haystack) {

	var needle = new String(ineedle);

	for (i in haystack) {
		if (haystack[i] == needle) {
			return true;
		}
	}
	return false;

}

function clearAll(form) {
	for(j=0; j<form.elements.length; j++) {
		if(form.elements[j].type=='text')
			form.elements[j].value='';
		if((form.elements[j].type=='radio') || (form.elements[j].type=='checkbox'))
			form.elements[j].checked=false;
		if((form.elements[j].type=='select-one') || (form.elements[j].type=='select-multiple'))
			form.elements[j].selectedIndex='';
	}
}

function change_class(id, newClass) {
	identity=document.getElementById(id);
	identity.className=newClass;
}

function getElement(name) {
	if (document.getElementById) {
		return document.getElementById(name);
	} else if (document.all) {
		return document.all[name];
	} else if (document.layers){
		return document[name];
	} else {
		return 0;
	}
}

function jprompt(message,url) {
	input_box=confirm(message);
	if (input_box==true) {
		window.location=url;
	}
}

function jprompt_multi(message, message2, urltrue, urlfalse) {
	input_box=confirm(message);
	if (input_box == true) {
		second_box=confirm(message2);
		if (second_box == true) {
			window.location = urltrue;
		} else {
			window.location = urlfalse;
		}
	}
}

function select_all_from_select(formname, selectname) {
    var s = document.forms[formname].elements[selectname];
    for (var i = 0; i < s.options.length; i++) {
        s.options[i].selected = true;
    }
}

function select_none_from_select(formname, selectname) {
    var s = document.forms[formname].elements[selectname];
    for (var i = 0; i < s.options.length; i++) {
        s.options[i].selected = false;
    }
}

function checkall(formname, regex_match) {
	for (var i = 0; i < formname.elements.length; i++) {
		var element = formname.elements[i];
		if ((element.name != "allbox") && (element.type == "checkbox"))
		{
			if (!regex_match || element.name.match(regex_match)) {
				element.checked = formname.allbox.checked;
			}
		}
	}
}

function oc(id) {
	var e=document.getElementById(id).style;
	if (e.display=='') {
		e.display='none';
	} else {
		e.display='';
	}
}

function isvis(id) {

	e=document.getElementById(id).style;
	if (e.display == 'none') {
		return false;
	} else {
		return true;
	}
}

function visno(id) {

	if (document.getElementById(id) == null) {
		alert('ID does not exist: ' + id);
		return 'error';
	}

	e=document.getElementById(id).style;
	e.display='none';

}

function visyes(id) {

	if (document.getElementById(id) == null) {
		alert('ID does not exist: ' + id);
		return 'error';
	}

	e=document.getElementById(id).style;
	e.display='';

}

function wysiwyg(form, element, element2) {
	openWindow('./../home/editor.php?form='+form+'&element='+element+'&element2='+element2, 660, 460);
}

function openWindow(url,w,h,windowname){
	if (!w) {
		w = '600';
	}
	if (!h) {
		h = '400';
	}
	if (!windowname) {
		windowname = 'window';
	}
	popupWin=window.open(url,windowname,'scrollbars,resizeable,status,'+'width='+w+',height='+h);
	popupWin.focus();
}

function openWindow2(url) {
	popupWin=window.open(url,'dp_window','scrollbars,resizeable,status');
	popupWin.focus();
}

function submitform(formname,valuename,thevalue) {
	var str = "<input type='hidden' name='" + valuename + "' value='" + thevalue + "'>"
	document.getElementById("hiddenbit_" + formname).innerHTML = str;
	document.forms[formname].submit();
}

function datePop(formname,fieldname) {

	var w = '205';
	var h = '185';
	var windowname = 'dateselect';

	year = eval('document.' + formname + '.y' + fieldname + '.options[document.' + formname + '.y' + fieldname + '.' + 'selectedIndex].value;');
	month = eval('document.' + formname + '.m' + fieldname + '.options[document.' + formname + '.m' + fieldname + '.' + 'selectedIndex].value;');

	openWindow('./datepop.php?formname='+formname+'&fieldname='+fieldname+'&year='+year+'&month='+month, w, h, windowname);

}

var IFrameObj;
var ajaxElm;
var ajaxTransaction;
var ajaxElmTried = false;

function callToServerSuccess(res) {

	if (!ajaxElm) {

		if (!document.getElementById || !document.createElement) {
			return false;
		}

		ajaxElm = document.getElementById('rpc_content');

		if (!ajaxElm && !ajaxElmTried) {

			var div = document.createElement('div');

			div.id = 'rpc_content';
			div.style.height = '1px';
			div.style.width = '1px';
			div.style.visibility = 'hidden';

			var div_tn = document.createTextNode('');
			div.appendChild(div_tn);

			var body = document.getElementsByTagName("body").item(0);
			body.appendChild(div);
			ajaxElmTried = true;

			ajaxElm = document.getElementById('rpc_content');

			if (!ajaxElm) {
				// Some browsers might need time to realize the new tag
				setTimeout("callToServerSuccess(res);", 300);
				return false;
			}
		}

		if (!ajaxElm) {
			return false;
		}
	}

	if(res.responseText) {

		ajaxElm.innerHTML = res.responseText;

		var hd = document.getElementsByTagName("head")[0];
        var re = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/img;
        var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
        var match;
        while(match = re.exec(res.responseText)){
			var srcMatch = match[0].match(srcRe);
			if(srcMatch && srcMatch[2]){
				var s = document.createElement("script");
				s.src = srcMatch[2];
				hd.appendChild(s);

			} else if(match[1] && match[1].length > 0) {
				eval(match[1]);
			}
        }
	}
}

function callToServer(URL, callback, norand) {

	if (!callback) {
		callback = {
			success: callToServerSuccess
			//failure: callToServerFailue,
		};
	}

	if (!norand) {
		if (URL.indexOf('?') == -1) {
			URL += '?';
		} else {
			URL += '&';
		}

		var d = new Date();
		URL += 't=' + d.getTime();
	}



	ajaxTransaction = YAHOO.util.Connect.asyncRequest('GET', URL, callback)
	return false;
}

function setWYSIWYGcontent(instanceName,content) {

	editor_frame = document.getElementById(instanceName+'___Frame');

	if (editor_frame!=null) {
		editor_source = editor_frame.contentWindow.document.getElementById('eEditorArea');
		if (editor_source!=null) {
			oldcontent=editor_source.contentWindow.document.body.innerHTML; editor_source.contentWindow.document.body.innerHTML=content;
			return oldcontent;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

// for calendar
function setSelectbox(s_id, s_value) {

	var e_sel = getInput(s_id);

	if (!e_sel)
		return alert("Can't find selectbox with id '" + s_id + "' in form " + s_form);
	var b_found = 0;
	for (var i = 0; i<e_sel.options.length; i++)
		if (e_sel.options[i].value == s_value || e_sel.options[i].text == s_value) {
			e_sel.options[i].selected = true;
			b_found = 1;
		}
	if (!b_found)
		return alert("Can't find value '" + s_value + "' in selectbox '" + s_id + "'");
}

function getSelectbox(s_id) {
	var e_sel = getInput(s_id);
	if (!e_sel)
		return 0;
	var e_option = e_sel.options[e_sel.selectedIndex];
	return Number(e_option.value ? e_option.value : e_option.text);
}

function onSelect(o_cal, s_date) {

	if (!o_cal.dateClicked) return;
	var s_prefix = o_cal.params.inputField;

	setSelectbox(s_prefix + '_year', o_cal.date.getFullYear());
	setSelectbox(s_prefix + '_month', o_cal.date.getMonth() + 1);
	setSelectbox(s_prefix + '_day', o_cal.date.getDate());
	if (o_cal.showsTime) {
		setSelectbox(s_prefix + '_hour', o_cal.date.getHours());
		setSelectbox(s_prefix + '_minute', o_cal.date.getMinutes());
		// note that this function is 24h mode only
	}
	o_cal.callCloseHandler();
}

var getInput = 	document.all ?
	function (i) { return document.all[i] } :
	function (i) { return document.getElementById(i) };


function log_out() {

	ht = document.getElementsByTagName("html");
	ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";

	if (confirm('Are you sure you want to log out?')) {
		return true;
	} else {
		ht[0].style.filter = "";
		return false;
	}
}

function select_jump(f) {

	var opt = f.selectedIndex;
	var url = f.options[opt].value;
	if (url != 0) {
		self.document.location = url;
	}
}

function occlass(theClass) {

	var CSSRules
	if (document.all) {
		CSSRules = 'rules'
	} else if (document.getElementById) {
		CSSRules = 'cssRules'
	}

	for (var i = 0; i < document.styleSheets[1][CSSRules].length; i++) {
		if (document.styleSheets[1][CSSRules][i].selectorText == theClass) {
			if (document.styleSheets[1][CSSRules][i].style['display'] == 'none') {
				document.styleSheets[1][CSSRules][i].style['display'] = '';
			} else {
				document.styleSheets[1][CSSRules][i].style['display'] = 'none';
			}
		}
	}
}

function repeat_options(obj, name) {

	if (!name) {
		name = 'repeat';
	}

	// get the option
	for (var i=0; i < obj.form.type.length; i++) {
		if (obj.form.type[i].checked) {
			var value = obj.form.type[i].value;
		}
	}

	visno(name + '_html_table_id_3');
	visno(name + '_html_table_id_5');
	visno(name + '_html_table_id_7');
	visno(name + '_html_table_id_9');

	if (value == 'daily') {
		visyes(name + '_html_table_id_3');
	} else if (value == 'weekly') {
		visyes(name + '_html_table_id_5');
	} else if (value == 'monthly') {
		visyes(name + '_html_table_id_7');
	} else if (value == 'yearly') {
		visyes(name + '_html_table_id_9');
	}
}


function go_select(id, prefix) {

	if (!prefix) {
		prefix = '';
	}

	var el = document.getElementById(id);

	if (!el) {
		return false;
	}

	var url = prefix + el.options[el.selectedIndex].value;

	if (url) {
		location.href = url;
		return true;
	}

	return false;
}



function perm_docheck(this_cb, what) {

	if (!what) {
		what = 'check';
	}

	// If it wasn't checked, then nothing to change
	if (this_cb && !this_cb.checked) {
		return;
	}

	// perm_ids is global, defined before being called
	if (typeof perm_ids == 'undefined') {
		return;
	}

	// When a permission is checked, must deselect inherit/all
	if (what == 'check') {

		var cb = document.getElementById('perm_inherit');
		if (cb) cb.checked = false;

		cb = document.getElementById('perm_all');
		if (cb) cb.checked = false;
	}

	// When inherit is checked, deselect all/checked groups
	else if (what == 'inherit') {

		var cb = document.getElementById('perm_all');
		if (cb) cb.checked = false;

		for(var i = 0; i < perm_ids.length; i++) {
			cb = document.getElementById(perm_ids[i]);
			if (cb) cb.checked = false;
		}
	}
}


function handle_cat_change(sel, default_sel) {

	// Hide other select
	var el_contain = document.getElementById('contain_sub_cats');
	el_contain.style.display = 'none';

	var parent_id = sel.options[sel.selectedIndex].value;

	// If it's not 'none'
	if (parent_id) {
		var callback = {
			success: handle_cat_change_success,
			argument: { parent_id: parent_id, el_select: sel }
		}

		var transaction = YAHOO.util.Connect.asyncRequest('GET', '../rpc/editticket.php?do=subcats&parent=' + parent_id + '&default_sel=' + default_sel, callback);
	}
}

function handle_cat_change_success(o) {

	// Make sure the same parent is selected
	// in case user chose two, might be a race condition
	var el_select = o.argument.el_select;
	var cur_parent_id = el_select.options[el_select.selectedIndex].value;
	var old_parent_id = o.argument.parent_id;

	if (cur_parent_id != old_parent_id) {
		return;
	}

	// Show/hide the subcats
	var el_contain = document.getElementById('contain_sub_cats');

	if (o.responseText.length > 1) {
		el_contain.innerHTML = o.responseText;
		el_contain.style.display = '';
	} else {
		el_contain.style.display = 'none';
	}

}

function showhide_link_init(showId, hideId, toggleId) {

	$('#' + showId).click(function() {
		$('#' + toggleId).show();
		$('#' + showId).hide();
		$('#' + hideId).show();
	});
	$('#' + hideId).click(function() {
		$('#' + toggleId).hide()
		$('#' + showId).show();
		$('#' + hideId).hide();
	});

}


function showWhenNotSelected(selectId, showId, notVal) {

	var sel = $('#' + selectId);
	var show = $('#' + showId);

	sel.change(function() {
		if (sel.val() != notVal) {
			show.show();
		} else {
			show.hide();
		}
	});

}