
// ------------------------------------
// Generic Cookie Rotines
// ------------------------------------

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 var 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 DumpCookies()
{
//	document.write("<p><b>Cookies on Client</b><br>\n")
	var allcookies = document.cookie;
	document.write("Cookies.Count = " + allcookies.count + "<br>\n");

	// Get all the cookies pairs in an array
	cookiearray  = allcookies.split(';');

	// Now take key value pair out of this array
	for(var i=0; i<cookiearray.length; i++)
	{
		name = cookiearray[i].split('=')[0];
		value = cookiearray[i].split('=')[1];
		document.write(name + ": " + value + "<br>\n");
	}
	document.write("</p>\n")
}

function EraseCookies()
{
	// Get all the cookie pairs in an array
	var allcookies = document.cookie;
	cookiearray  = allcookies.split(';');

	// Now take key value pair out of this array
	for(var i=0; i<cookiearray.length; i++)
	{
		name = cookiearray[i].split('=')[0];
		value = cookiearray[i].split('=')[1];
		eraseCookie(name);
	}
}

// ------------------------------------
// Generic Currency Routines
// ------------------------------------

function FixCurrency(n)
{
	//return n.ToFixed(2);
	return n;
}

function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

// ------------------------------------
// Pop-Ups (using window open (boring)
// ------------------------------------

function PopPage(url, w, h, x, y)
{
	var wnd = window.open(url, 'POP', 'width=' + w + ',height=' + h + ',left=' + x + ',top=' + y + ',status=0,location=0,menubar=0,toolbar=0,scrollbars=1,resizable=1');
	wnd.focus();
}

// ------------------------------------

function ShowImage(url, x, y, w, h, title)
{
	var wnd = window.open(url, "IMAGE", 'width=' + (w + 20) + ',height=' + (h + 32) + ',left=' + x + ',top=' + y + ',status=0,location=0,menubar=0,toolbar=0,scrollbars=0,resizable=1');
	wnd.focus();
}

// ------------------------------------
// Ajax
// ------------------------------------

// GetFile(): By default file is cached
function GetFile(url, target) {GetFile(url, target, false);}
function GetFile(url, target, nocache) {

	var sWait = "<img src='../images/popbox/spinner40.gif'>"
	document.getElementById(target).innerHTML = sWait;
	  
	if (window.XMLHttpRequest)
		req = new XMLHttpRequest();
	else if (window.ActiveXObject)
		req = new ActiveXObject("Microsoft.XMLHTTP");
	if (req != undefined)
	{
		req.onreadystatechange = function() {GetFileDone(url, target);};

		var newurl = url;
		if(nocache == true)
		{
			if(url.indexOf('?') != -1)
				newurl += "&";
			else
				newurl += "?";
			newurl += 'qqq=' + Math.random();
		}	
//		alert(newurl);

		req.open("GET", newurl, true);
		
		if (nocache == true)
			req.setRequestHeader("Cache-Control", "no-cache"); 

		req.send("");
	}
}  

function GetFileDone(url, target) {
	if (req.readyState == 4) { // only if req is "loaded"
		if (req.status == 200) { // only if "OK"
			document.getElementById(target).innerHTML = req.responseText;
		} else {
      	document.getElementById(target).innerHTML=" Error:\n"+ req.status + "\n" +req.statusText;
		}
	}
}

// GetFileReady(): By default file is cached
function GetFileReady(url, target, func) {return GetFileReady(url, target, func, false);}
function GetFileReady(url, target, func, nocache)
{
	var sWait = "<img src='../images/popbox/spinner40.gif'>"
	document.getElementById(target).innerHTML = sWait;

	if (window.XMLHttpRequest)
		req = new XMLHttpRequest();
	else if (window.ActiveXObject)
		req = new ActiveXObject("Microsoft.XMLHTTP");
	if (req != undefined)
	{
		req.onreadystatechange = func;
		
		var newurl = url;
		if(nocache == true)
		{
			if(url.indexOf('?') != -1)
				newurl += "&";
			else
				newurl += "?";
			newurl += 'qqq=' + Math.random();
		}	
//		alert(newurl);

		req.open("GET", newurl, true);
		
		if (nocache == true)
			req.setRequestHeader("Cache-Control", "no-cache"); 

		req.send("");
	}
}  

// ------------------------------------
// LoadObjs(): Load passed list of .css and/or .js files

function LoadObjs()
{
	if (!document.getElementById)
		return;
	
	// Loop thru passed aruments
	for (i = 0; i < arguments.length; i++)
	{
		// Get the filename
		var file = arguments[i];
		var fileref = "";

//		alert(file);

		// Check to see if this object has not already been added to page before proceeding
		if (loadedobjects.indexOf(file) == -1)
		{
			// See if this is a .js  or .css file
			if (file.indexOf(".js") != -1)
			{
				fileref = document.createElement('script');
				fileref.setAttribute("type", "text/javascript");
				fileref.setAttribute("src", file);
			}
			else if (file.indexOf(".css") != -1)
			{
				fileref = document.createElement("link");
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}

		// Add the object to the page (if not already added)
		if (fileref != "")
		{
			// Remember this object as being already added to page
			document.getElementsByTagName("head").item(0).appendChild(fileref);
			loadedobjects += file + " ";
		}
	}
}

// ------------------------------------
// Dialogs
// ------------------------------------

function Center(target)
{
	// Make the DIV displayed but hidden so its size can be measured
	var e = document.getElementById(target);
	e.style.visibility = 'hidden';
	e.style.display = 'block';
	
	// Center it
	CenterVert(target);
	CenterHorz(target);
	
	// Show it
	e.style.display = 'block';
	e.style.visibility = 'visible';
}

function CenterVert(target)
{
	var e = document.getElementById(target);
	
	var y1 = f_scrollTop();
	var y2 = y1;
	
	var h1 = f_clientHeight();

	// If the client height is less than the screen's height, use the screen height
	// This does not take into consideration tool bar heights (so estimate it - for now)
	if (h1 < screen.height) h1 = (screen.height - 200);

	var h2 = e.offsetHeight;
	if (h1 > h2)
		y2 = y1 + Math.round(((h1 - h2) / 2));

//	e.style.top = y2;						// this works in IE, but not FireFox
	e.style.top = y2.toString() + "px";
	
//	alert('\ny1:' + y1 + '\ny2:' + y2 + '\nh1:' + h1 + '\nh2:' + h2);
}

function CenterHorz(target)
{
	var e = document.getElementById(target);

	var x1 = f_scrollLeft();
	var x2 = x1;
	
	var w1 = f_clientWidth();
	var w2 = e.offsetWidth;
	if (w1 > w2)
		x2 = x1 + Math.round(((w1 - w2) / 2));

//	e.style.left = x2;						// this works in IE, but not FireFox
	e.style.left = x2.toString() + "px";
	
//	alert('\nx1:' + x1 + '\nx2:' + x2 + '\nw1:' + w1 + '\nw2:' + w2);
}

// ------------------------------------
// ShowDialog(): Display popup dialog in div
//
// I should create a routine that will display a dialog using passed
// x,y and width and height
//				
function ShowDialog(url, target)
{
	// Get the dialog file
	GetFileReady(url, target, function() {DialogReadyCenter(url, target);}, true)

	// Show it
	Popup.showModal(target);
	
	// Set the class
	e = document.getElementById(target);
	e.className = 'popupdialog';
}

function DialogReadyCenter(url, target)
{
	// Check if req is loaded
	if (req.readyState == 4)
	{
		// Check if status is OK
		if (req.status == 200)
			document.getElementById(target).innerHTML = req.responseText;
		else
			document.getElementById(target).innerHTML = " Error:\n" + req.status + "\n" + req.statusText;
			
		Center(target);
	}
}

// ------------------------------------
// Window Position
// ------------------------------------

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

// ------------------------------------
// Catalog
// ------------------------------------

function InitCatalogFilters(page, pagecount, pagesize, sort)
{
	var e, s, i, n;

	// Init Items Per Page
	n = document.frmFilter1.items1.length;
	for(i=0; i<n; i++)
	{
		if(document.frmFilter1.items1[i].value == pagesize)
		{
			document.frmFilter1.items1.selectedIndex = i;
			document.frmFilter2.items2.selectedIndex = i;
			break;
		}	
	}
	
	// Init Sort Filter
	n = document.frmFilter1.sort1.length;
	for(i=0; i<n; i++)
	{
		if(document.frmFilter1.sort1[i].value == sort)
		{
			document.frmFilter1.sort1.selectedIndex = i;
			document.frmFilter2.sort2.selectedIndex = i;
			break;
		}	
	}

	// Init Pages
	document.frmFilter1.page1.length = 0;
	document.frmFilter2.page2.length = 0;
	
	var nPages = pagecount;
	var nPage, selected;
	for(i=0; i<nPages; i++)
	{
		nPage = i + 1;
		selected = (nPage == page) ? true : false;
		document.frmFilter1.page1.options[i] = new Option(nPage.toString(), nPage, false, selected)
		document.frmFilter2.page2.options[i] = new Option(nPage.toString(), nPage, false, selected)
	}

	s = " of " + nPages.toString() + "  ";
	e = document.getElementById("pages1");
	if (e.innerText)
		e.innerText = s;
	else if (e.textContent)
		e.textContent = s;

	e = document.getElementById("pages2");
	if (e.innerText)
		e.innerText = s;
	else if (e.textContent)
		e.textContent = s;
}

function CatalogReload(n)
{
	var i, pagesize, sort;
	
	if(n == 1)
	{
		i = document.frmFilter1.items1.selectedIndex;
		pagesize = document.frmFilter1.items1.options[i].value;

		i = document.frmFilter1.sort1.selectedIndex;
		sort = document.frmFilter1.sort1.options[i].value;
	}
	else
	{
		i = document.frmFilter2.items2.selectedIndex;
		pagesize = document.frmFilter2.items2.options[i].value;

		i = document.frmFilter2.sort2.selectedIndex;
		sort = document.frmFilter2.sort2.options[i].value;
	}

	var url = window.location.href;
	var n1 = url.indexOf("&pos=");
	if(n1 != -1)
		url = url.substring(0, n1);
	url += "&pos=0";
	url += "&size=" + pagesize;
	url += "&sort=" + sort;
	url += "&page=1";
	window.location.href = url;
}

function CatalogPageChanged(n)
{
	var i, pos, page, pagesize, sort;
	
	if(n == 1)
	{
		i = document.frmFilter1.items1.selectedIndex;
		pagesize = document.frmFilter1.items1.options[i].value;

		i = document.frmFilter1.sort1.selectedIndex;
		sort = document.frmFilter1.sort1.options[i].value;

		i = document.frmFilter1.page1.selectedIndex;
		page = document.frmFilter1.page1.options[i].value;
		
	}
	else
	{
		i = document.frmFilter2.page2.selectedIndex;
		page = document.frmFilter2.page2.options[i].value;
		
		i = document.frmFilter2.items2.selectedIndex;
		pagesize = document.frmFilter2.items2.options[i].value;
	
		i = document.frmFilter2.sort2.selectedIndex;
		sort = document.frmFilter2.sort2.options[i].value;
	}

	pos = (page - 1) * pagesize;

	var url = window.location.href;
	var n1 = url.indexOf("&pos=");
	if(n1 != -1)
		url = url.substring(0, n1);
	url += "&pos=" + pos;
	url += "&size=" + pagesize;
	url += "&sort=" + sort;
	url += "&page=" + page;
	window.location.href = url;
}

function CatalogNextPage(total)
{
	var i, pos, page, pagesize, sort;
	
	i = document.frmFilter1.items1.selectedIndex;
	pagesize = document.frmFilter1.items1.options[i].value;

	i = document.frmFilter1.sort1.selectedIndex;
	sort = document.frmFilter1.sort1.options[i].value;

	i = document.frmFilter1.page1.selectedIndex;
	page = document.frmFilter1.page1.options[i].value;
	if((page * pagesize) >= total)
		return;

	page++;

	pos = (page - 1) * pagesize;

	var url = window.location.href;
	var n1 = url.indexOf("&pos=");
	if(n1 != -1)
		url = url.substring(0, n1);
	url += "&pos=" + pos;
	url += "&size=" + pagesize;
	url += "&sort=" + sort;
	url += "&page=" + page;
	window.location.href = url;
}

function CatalogPrevPage()
{
	var i, pos, page, pagesize, sort;

	i = document.frmFilter1.items1.selectedIndex;
	pagesize = document.frmFilter1.items1.options[i].value;

	i = document.frmFilter1.sort1.selectedIndex;
	sort = document.frmFilter1.sort1.options[i].value;

	i = document.frmFilter1.page1.selectedIndex;
	page = document.frmFilter1.page1.options[i].value;
	page--;

	if(page == 0)
		return;

	pos = (page - 1) * pagesize;

	var url = window.location.href;
	var n1 = url.indexOf("&pos=");
	if(n1 != -1)
		url = url.substring(0, n1);
	url += "&pos=" + pos;
	url += "&size=" + pagesize;
	url += "&sort=" + sort;
	url += "&page=" + page;
	window.location.href = url;
}

