/**
 * 
 * @author Stratus Development Team
 * @package entice
 * @version $Id: functions.js,v 1.9 2010/08/09 21:55:19 lsmith Exp $
 * @copyright (c) 2007 Stratus Technologies
 * @license Stratus Technologies
 * 
 */


var log = log4javascript.getLogger();
log4javascript.setEnabled(false);
// Create a PopUpAppender with default options
var popUpAppender = new log4javascript.PopUpAppender();
// Change the desired configuration options
popUpAppender.setFocusPopUp(true);
popUpAppender.setNewestMessageAtTop(true);
// Add the appender to the logger
log.addAppender(popUpAppender);
/*
 * log.trace("Trace message"); log.debug("Hello world!"); log.info("This is an
 * info"); log.warn("this is a warning"); log.error("This is an error");
 * log.fatal("And fatal at that");
 */

function ensLog() {
    if (window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

// select and deselect all checkboxes (dial_code_maintenance.html has a working
// example)
function select_all(name, value)
{
	var formblock;
	var forminputs;

	formblock= document.getElementById('dial_codes');
	forminputs = formblock.getElementsByTagName('input');

	if (value == 'toggle')
	{
		if (document.getElementById(name).checked == false)
		{
			value = 0;
		}
		else
		{
			value = 1;
		}
	}

	for (i = 0; i < forminputs.length; i++)
	{
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name')))
		{
			if (value == '1')
			{
				forminputs[i].checked = true;
			}
			else
			{
				forminputs[i].checked = false;
			}
		}
	}
	return;
}

/*
 * vars for edit function (example) var $form_name = 'add_dial_code';
 * 
 * //the fields to grab info from var $edit_fields = 'code--name';
 * 
 * //the fields to put the info into for editing var $put_fields =
 * 'dial_code--display_name';
 * 
 * //holds the code so once it's been edited, we know what's been edited var
 * $hold_code = '';
 * 
 * //these 3 have to match up. find - replace - type (innerHTML, name, value etc
 * (anything else will need to be added to the function)) var $find_replace =
 * 'add_dial_code2--add--add'; var $replace_find =
 * '{L_EDIT_DIAL_CODE}--{L_MODIFY}--modify'; var $replace_type =
 * 'innerHTML--value--name';
 */

function edit($code)
{
	// hold the code for later use
	$hold_code		= $code;

	// split get and put fields into an array
	$request_fields = $edit_fields.split('--');
	$put_field		= $put_fields.split('--');

	// split the find and replace fields into an array
	$find			= $find_replace.split('--');
	$replace		= $replace_find.split('--');
	$type			= $replace_type.split('--');

	// first take the data we need to edit and put it in the var'd fields
	for ($i = 0; $i < $request_fields.length; $i++)
	{
		document.forms[$form_name][$put_field[$i]].value = document.getElementById($request_fields[$i] + $code).innerHTML;
	}

	// add the code to the hold code so we know which field we edited
	document.forms[$form_name]['hold_code'].value = $hold_code;

	// find and replace fields to change everything from add to modify
	for ($i = 0; $i < $find.length; $i++)
	{
		switch($type[$i])
		{
			case 'innerHTML':
				document.getElementById($find[$i]).innerHTML = $replace[$i];
			break;
			case 'value':
				document.forms[$form_name][$find[$i]].value = $replace[$i];
			break;
			case 'name':
				document.forms[$form_name][$find[$i]].name = $replace[$i];
			break;
		}
	}
	return false;
}

/**
 * Shor or Hide a div tag (not useful for tables)
 * 
 * @param $div_name -
 *            div ID to toggle show or hide
 * @param $toggle -
 *            'show' or 'hide' -- default is 'hide'
 */
function toggle_div($div_name, $toggle)
{
    $this_div = document.getElementById($div_name);
    if ($this_div)
	{
		if ($toggle)
		{
			if ($toggle == 'hide')
			{
				$this_div.style.display = 'none';
			}
	        else if ($this_div.style.display == 'none' || $toggle == 'show')
			{
	            $this_div.style.display = 'block';
	        }
		}
		else
		{
			if ($this_div.style.display == 'none' || !$this_div.style.display)
			{
				$this_div.style.display = 'block';
			}
			else
			{
				$this_div.style.display = 'none';
			}
		}
		return;
    }
}

/**
 * Change opacity of an HTML element (div) in a specified amount of time
 * 
 * @param $id -
 *            Div ID to change opacity for.
 * @param $opac_start -
 *            Start opacity of div element (will overwrite any existing opacity)
 * @param $opac_end -
 *            Ending opacity you want to change the div to.
 * @param $millisec -
 *            The amount of time you want to take to change the opacity, higher
 *            number = slower opacity change
 */
function opacity($id, $opac_start, $opac_end, $millisec)
{
	// $speed for each frame
	var $speed = Math.round($millisec / 100);
	var $timer = 0;

	// determine the direction for the blending, if start and end are the same
	// nothing happens
	if ($opac_start > $opac_end)
	{
		for ($i = $opac_start; $i >= $opac_end; $i--)
		{
			setTimeout("change_opac(" + $i + ",'" + $id + "')", ($timer * $speed));
			$timer++;
		}
	}
	else if ($opac_start < $opac_end)
	{
		for ($i = $opac_start; $i <= $opac_end; $i++)
		{
			setTimeout("change_opac(" + $i + ",'" + $id + "')", ($timer * $speed));
			$timer++;
		}
	}
}

/**
 * Change the opacity for different browsers
 * 
 * @param $opacity -
 *            Opacity you want to set for the Div element
 * @param $id -
 *            ID of div you want to set opacity for.
 */
function change_opac($opacity, $id)
{
	var $object = document.getElementById($id).style;
	$object.opacity = ($opacity / 100);
	$object.MozOpacity = ($opacity / 100);
	$object.KhtmlOpacity = ($opacity / 100);
	$object.filter = "alpha(opacity=" + $opacity + ")";
}

/**
 * Open a CSS layer diolog box. "blackout" will dim the screen to emphasise the
 * front-most diolog box <code>
 * <div id="blackout"></div>
 *	<div id="stadium">
 *		<div id="showbox" class="simple_body">Content of Box
 *			<a href="javascript:void(0);" onclick="close_box('stadium');">Close Window Link</a>
 *		</div>
 *	</div>
 *	<a href="javascript:void(0);" onclick="open_box('stadium');">Opwn Window Link</a>
 * </code>
 * 
 * @param $container
 *            Container Div ID Name of the diolog box you want to open.
 */
var $county = 0;
function open_box($container, $width, $height)
{
	var blackout = document.getElementById('blackout');
	$div = document.getElementById($container);

	// set height and width of blackout
	page_size = get_page_size();
		
	page_size[0] = page_size[0] - 20;
	page_size[1] = page_size[1] - 20;
	
	$scrolltop = 0;
	if (document.documentElement && document.documentElement.scrollTop)
	{
		$scrolltop = document.documentElement.scrollTop;
	}
	else if (document.body && document.body.scrollTop)
	{
		$scrolltop = document.body.scrollTop;
	}
	else if (window.scrollY) 
	{
		$scrolltop = window.scrollY;
	}
	
	blackout.style.height = ($scrolltop + page_size[1] + 400) + 'px';
	blackout.style.width = (page_size[0] + 100) + 'px';

	if (!$width)
	{
		$width = 300;
	}
	$div.style.marginLeft = '-' + ($width / 2) + 'px';

	/*
	 * * this may be good at some point if it can work reliably** if ($height) {
	 * $div.style.position = 'fixed'; $div.style.top = '50%';
	 * $div.style.marginTop = '-' + ($height / 2) + 'px'; blackout.style.height =
	 * ($scrolltop + $height + page_size[1]) + 'px'; if ($height > page_size[1]) {
	 * $div.style.marginTop = ($scrolltop - 150) + 'px'; $div.style.position =
	 * ''; } } else {
	 */
		$div.style.top = ($scrolltop + (page_size[1] / 5)) + 'px';
	// }

	setTimeout('toggle_div("blackout", "show");', 150);
	setTimeout('toggle_div("' + $container + '", "show");', 500);
	opacity('blackout', 0, 70, 1000);
}

function get_page_size()
{
	if (self.innerWidth)
	{
		$width = self.innerWidth;
		$height = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		$width = document.documentElement.clientWidth;
		$height = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		$width = document.body.clientWidth;
		$height = document.body.clientHeight;
	}
	
	return new Array($width, $height);
}

/*
 * function get_page_size() { if (window.innerHeight && window.scrollMaxY) { //
 * Firefox yWithScroll = window.innerHeight + window.scrollMaxY; xWithScroll =
 * window.innerWidth + window.scrollMaxX; } else if (document.body.scrollHeight >
 * document.body.offsetHeight) { // all but Explorer Mac yWithScroll =
 * document.body.scrollHeight; xWithScroll = document.body.scrollWidth; } else { //
 * works in Explorer 6 Strict, Mozilla (not FF) and Safari yWithScroll =
 * document.body.offsetHeight; xWithScroll = document.body.offsetWidth; }
 * 
 * page_size = new Array(xWithScroll, yWithScroll); return page_size; }
 * 
 * /** Close a CSS layer diolog box. turns "blackout" off as well ("blackout" is
 * turned on by the open_box(); function)
 * 
 * @param $container Container Div ID Name of the diolog box you want to close.
 */
function close_box($container)
{
	opacity('blackout', 70, 0, 600);
	setTimeout('toggle_div("blackout", "hide");', 600);
	setTimeout('toggle_div("' + $container + '", "hide");', 600);
}


/**
 * Jump to page
 */
function jumpto()
{
	var page = prompt(jump_page, on_page);

	if (page !== null && !isNaN(page) && page > 0)
	{
		document.location.href = base_url.replace(/&amp;/g, '&') + '&start=' + ((page - 1) * per_page);
	}
}

function fill_dates($id, $type)
{
	$string = '';
	if ($type > 3)
	{
		$year = document.getElementById('year').value;
		$type = $type - 4;
	}
	if ($type > 1)
	{
		$day = document.getElementById('day').value;
		$type = $type - 2;
	}
	if ($type > 0)
	{
		$month = document.getElementById('month').value;
		$type = $type - 1;
	}

	document.getElementById($id).value = $month + '/' + $day + '/' + $year;

	$row = $select.split('--');

	if ($row[2] == 'checked')
	{
		document.getElementById($row[0] + $row[1]).checked = $row[2];
	}
}

/**
 * Inspired by: javascript for Bubble Tooltips by Alessandro Fulciniti -
 * http://pro.html.it - http://web-graphics.com
 * 
 * Enable (grab) tooltips and send the to process.
 */
function enableTooltips(id)
{
	var links,i,h,a;

	if (!document.getElementById || !document.getElementsByTagName)
	{
		return;
	}

	h = document.createElement("span");
	h.id = "btc";
	h.setAttribute("id", "btc");
	h.style.position = "absolute";

	document.getElementsByTagName("body")[0].appendChild(h);

	if (id == null)
	{
		links = document.getElementsByTagName("a");
	}
	else
	{
		links = document.getElementById(id).getElementsByTagName("a");
	}

	for (i = 0; i < links.length; i++)
	{
		if (links[i].getAttribute("title") != null)
		{
			Prepare(links[i]);
		}
	}
}

/**
 * Create the HTML elements to show tooltips
 */
function Prepare(el)
{
	var tooltip,t,b,s,l;
	t = el.getAttribute("title");

	el.removeAttribute("title");
	tooltip = CreateEl("span", "tooltip");

	s = CreateEl("span","top");
	s.appendChild(document.createTextNode(t));
	tooltip.appendChild(s);

	b = CreateEl("b", "bottom");
	tooltip.appendChild(b);
	setOpacity(tooltip);
	el.tooltip = tooltip;
	el.onmouseover = showTooltip;
	el.onmouseout = hideTooltip;
	el.onmousemove = Locate;
}

/**
 * Display tooltip
 */
function showTooltip(e)
{
	document.getElementById("btc").appendChild(this.tooltip);
	Locate(e);
}

/**
 * Hide tooltip
 */
function hideTooltip(e)
{
	var d = document.getElementById("btc");

	if (d.childNodes.length > 0)
	{
		d.removeChild(d.firstChild);
	}
}

/**
 * Set Opacity of Element to 95 -- add an option later opacity values: 0 - 99
 * (100 is not valid)
 */
function setOpacity(el, opacity)
{
	if (opacity == null)
	{
		opacity = 95;
	}

	el.style.filter = "alpha(opacity:" + opacity + ")";
	el.style.KHTMLOpacity = "0." + opacity;
	el.style.MozOpacity = "0." + opacity;
	el.style.opacity = "0." + opacity;
}

/**
 * Create an HTML Element
 */
function CreateEl(t, c)
{
	var x = document.createElement(t);
	x.className = c;
	x.style.display = "block";

	return(x);
}

/**
 * Set the location of the mouse/page
 */
function Locate(e, id, offset_y, offset_x)
{
	var posx = 0, posy = 0;

	if (e == null)
	{
		e = window.event;
	}

	if (id == null)
	{
		id = 'btc';
	}

	if (offset_y == null)
	{
		offset_y = 10;
	}

	if (offset_x == null)
	{
		offset_x = 20;
	}

	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		if (document.documentElement.scrollTop)
		{
			posx = e.clientX + document.documentElement.scrollLeft;
			posy = e.clientY + document.documentElement.scrollTop;
		}
		else
		{
			posx = e.clientX + document.body.scrollLeft;
			posy = e.clientY + document.body.scrollTop;
		}
	}

	document.getElementById(id).style.top = (posy + offset_y) + "px";
	document.getElementById(id).style.left = (posx - offset_x) + "px";
}

// change cursor to a pointer if we can click on this row or cell
function change_pointer()
{
	$object_ary = new Array();
	// tr, td and div is all I can think of now
	$object_ary.push(document.getElementsByTagName('tr'));
	$object_ary.push(document.getElementsByTagName('td'));
	$object_ary.push(document.getElementsByTagName('div'));

	for ($i = 0; $i < $object_ary.length; $i++)
	{
		for ($x = 0; $x < $object_ary[$i].length; $x++)
		{
			$attributes = $object_ary[$i][$x].getAttribute('onclick');
			if ($attributes)
			{
				$object_ary[$i][$x].style.cursor = 'pointer';
			}
		}
	}

}
onload_functions.push(setTimeout('change_pointer();', 1000));

/**
 * Alternate display of subPanels
 */
function subPanels(p)
{
	var i, e, t;

	if (typeof(p) == 'string')
	{
		show_panel = p;
	}

	for (i = 0; i < panels.length; i++)
	{
		e = document.getElementById(panels[i]);
		t = document.getElementById(panels[i] + '-tab');

		if (e)
		{
			if (panels[i] == show_panel)
			{
				e.style.display = 'block';
				if (t)
				{
					t.className = 'ui-corner-top activetab';
				}
			}
			else
			{
				e.style.display = 'none';
				if (t)
				{
					t.className = 'ui-corner-top';
				}
			}
		}
	}
}

/**
 * Search Functions
 */

/**
 * add_option int $id current option id used for adding more search criteria
 */
function add_option($id, $pre)
{
	$div = $id + 1;
	
	toggle_div('option' + $pre + $div, 'show');
	return false;
}

/**
 * remove_option int $id current option id used for removing search criteria
 */
function remove_option($id, $pre)
{
	toggle_div('option' + $pre + $id);
	document.forms['search-panel'].elements['input' + $id].value = '';
	document.forms['search-panel'].elements['select' + $id].value = 'select';
	document.forms['search-panel'].elements['value' + $id].value = '=';
	return false;
}

/**
 * clear_search used for clearing data from searches
 */
function clear_search()
{
	$form = document.forms['search-panel'].elements;
	$length = $form.length / 3;
	
	for ($i = 0; $i < $length; $i++)
	{
		if (!$form['input' + $i])
		{
			return false;
		}
		$form['input' + $i].value = '';
		$form['select' + $i].value = 'select';
		$form['value' + $i].value = '=';
		
		if ($i > 0)
		{
			toggle_div('option' + $i, 'hide');
		}		
	}

	return false;
}

/**
 * AJAX Functions
 */
var $xmlhttp = http_object();
var $finished = 0;
var $send_queue = new Array();
var $running = false;

var $divname;
var $newform;
var $newurl;

function http_object()
{
	if (window.XMLHttpRequest)
	{
		return new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
}

function send($action, $url, $form, $div, $clear)
{
	$image = '<img src="./styles/theme/images/ajax-loader.gif" />';
	
	$newform = $form;
	$newurl = $url;
	
	switch ($action)
	{
		case 'submit':
			$send_queue.push("handle_send($newurl, $newform)");

			$divname = document.getElementById($div);
			$newdiv = document.createElement('div');
			$newdiv.setAttribute('id', 'indicator');
			$newdiv.setAttribute('style', 'margin-left: auto; margin-right: auto; width: 100%; text-align:center;');
			$newdiv.innerHTML = $image;
			$divname.appendChild($newdiv);
			$divname = $div;
		break;
		default:
			document.getElementById($div).innerHTML = '<div id="indicator" style="margin-left: auto; margin-right: auto; width: 100%; text-align:center;">' + $image + '</div>';
			$divname = $div;
			$send_queue.push("handle_send($newurl, $newform)");
		break;
	}
	
	if (!$running)
	{
		run_ajax();
	}
	
	return;
}

function run_ajax()
{
	$running = true;
	for ($i = 0; $i < $send_queue.length; $i++)
	{
		if ($xmlhttp.readyState == 4 || $xmlhttp.readyState == 0)
		{
			eval($send_queue[$i]);
		}
		else
		{
			$xmlhttp.onreadystatechange = check_state;
		}
	}
}

function check_state()
{
	if ($xmlhttp.readyState == 4 || $xmlhtt.readyState == 0)
	{
		eval($send_queue[$finished]);
	}
	else
	{
		$xmlhttp.onreadystatechange = check_state;
	}
}

function handle_send($url, $f)
{
	if ($xmlhttp.readyState == 4 || $xmlhttp.readyState == 0)
	{
		$param = '';
		if ($f)
		{
			for ($i = 0; $i < $f.elements.length; $i++)
			{
				$elem = $f.elements[$i];
				switch ($elem.type)
				{
					case 'checkbox':
					case 'radio':
						if ($elem.checked)
						{
							$param += '&' + $elem.name + '=' + encodeURIComponent($elem.value);
						}
					break;
					default:
						$param += '&' + $elem.name + '=' + encodeURIComponent($elem.value);
					break;
				}
			}
		}

		$xmlhttp.open('POST', $url, true);
		$xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		$xmlhttp.onreadystatechange = handle_return;
		$xmlhttp.send($param);
	}

	return;
}

function handle_return()
{
	if ($xmlhttp.readyState == 4)
	{
		log.debug($xmlhttp.responseText);
		$response_ary = $xmlhttp.responseText.split('---');
		if ($response_ary[0].substr(0,5) == "<!DOC" ) {
		   log.warn("Should be new page");
		   location.href = document.URL;
		   return;
		}
		else if ($response_ary[0].substr(0,5) == "docum" ) {
			log.debug("Should be pop up");
			eval($response_ary[0]);
		}
		else if ($response_ary[0].substr(0,5) == "$tabl" ) {
			log.debug("Should be pop up");
			eval($response_ary[0]);
		}
		else {
			log.error("Unknown error.");
			alert("Unknown error");
			location.href = document.URL;
		    return;
		}
		$finished++;
		
		if ($send_queue[$finished])
		{
			check_state();
		}
		else
		{
			$send_queue = new Array();
			$finished = 0;
			$running = false;
		}
	}
	return;
}


function loadDialog(src, data) {
	//console.log(src);
    $('#Dialog').load( src, data,
            function(data){  
    			//console.log(data);
    			return _showMaintDiv(data);
            } );
    return true;
}

function _showMaintDiv(src) {
    $("#Dialog").dialog("option", "modal", true );
    $('#Dialog').dialog('open');
    $('#Dialog').dialog('option', 'title', $("h2",src).text());
    $("#Dialog h2").remove();
    $('#Dialog').dialog( "option", "width", 'auto' );
    $('#Dialog').dialog( "option", "position", 'auto' );
    return true;
}
