// file: util.js
// JavaScript Utility functions
// Copyright (c) 2001 IQ Commerce Corporation.  All Rights Reserved.

///////////////////////////////////////
// Return IE for Internet Explorer or NS for Netscape
///////////////////////////////////////
function iq_getBrowserType()
{
	var s = navigator.appName.substring(0, 8).toLowerCase();
	if (s == "microsof")
		return "IE";
	else if (s == "netscape")
		return "NS";
	else
		return "";
}

///////////////////////////////////////
// Return the browser version (3 or 4)
///////////////////////////////////////
function iq_getBrowserVersion()
{
	var ver = parseInt(navigator.appVersion.substring(0, 1));

	// IE3 returns version 2.0, so we need a hack
	if (iq_getBrowserType() == "IE" && ver < 4)//[levka] changed for future IE releases
		return 3;
		
	if (ver == null)
		return 0;
	else
		return ver;
}


function iq_selfFocus()
{
	if (iq_getBrowserVersion() >= 4)
	{
		self.focus();
	}
}

/*
Find the first form on this page -
Within that form, find the first text, password or textarea and give it focus.
*/
function iq_focusOnFirstForm()
{
	var form = document.forms[0];
	if (form == null)
		return;
	var i;
	for (i = 0; i < form.elements.length; i++) {
		var element = form.elements[i];
		if (element.type == "textarea" || element.type == "text" || element.type == "password") {
			element.select();
			element.focus();
			return;
		}
	}
}


/*
 * A page's form can only be submitted once.  This serves as a poor man's lock.
 */
 
function waitmore()
{
	alert("get waitsick");
}

function waitsick()
{
	//setTimeout('waitmore()', 5000);
	alert("get waitsick");
}

var isSubmitting = false;

function iq_submitFormOrGoToDest(url, flowId, buttonName, program, shouldValidate, timeGenerated, prevOfferPageMapId)
{
	// DAC FIXME temp hack to make buttons work
	// before proceeding, make sure that the body frame is "ours"
	if (typeof(top.body.isSubmitting) != "boolean") // if it's not "ours" do the button action "GoToDest" part of iq_submitFormOrGoToDest()
	{
			var full_url = url + "?_flowId=" + escape(flowId)
							   + "&_name=" + escape(buttonName)
							   + "&_program=" + escape(program)
							   + "&_genTime=" + escape(timeGenerated);
			if (prevOfferPageMapId != null && prevOfferPageMapId != "")
				full_url += "&_prevOfferPageMapId=" + escape(prevOfferPageMapId);
			top.location = full_url;
	}else if (!top.bottom.isSubmitting) {
		top.bottom.isSubmitting = true;  // poor-man's JavaScript lock
		if (top.body.document.forms.length == 0) {
			var full_url = url + "?_flowId=" + escape(flowId) 
			                   + "&_name=" + escape(buttonName)
			                   + "&_program=" + escape(program)
			                   + "&_genTime=" + escape(timeGenerated);
			if (prevOfferPageMapId != null && prevOfferPageMapId != "")
				full_url += "&_prevOfferPageMapId=" + escape(prevOfferPageMapId);
			top.location = full_url;
		} else {
			var form = top.body.document.forms[0];
			var i;
			
			for (i = 0; i < form.elements.length; i++) {
				var element = form.elements[i];
				if (element.name == "_flowId")
					element.value = flowId;
				else if (element.name == "_name")
					element.value = buttonName;		
				else if (element.name == "_program")
					element.value = program;	
				else if (element.name == "_genTime")
					element.value = timeGenerated;		
			}

			var validated = true;
			if (shouldValidate == "true") {
				if (typeof(top.body.validateForm) == "function") {
					validated = top.body.validateForm(form);
				} else {
					validated = top.body.iq_validateForm(form);
				}
			}
			if (validated) {
				form.target = "_top";
				if (prevOfferPageMapId != null && prevOfferPageMapId != "")
					url += "?_prevOfferPageMapId=" + escape(prevOfferPageMapId);
				form.action = url; // + "?t=" + (new Date()).getTime();
				
			/*	form.action = url + "?_flowId=" + flowId 
							+ "&_name" + buttonName
							+ "&_program" + program
							+ "&_genTime" + timeGenerated;	*/
				

				form.method = "POST";
				form.submit();	
			} else {
				top.submitInProgress = "false";
				top.bottom.isSubmitting = false;
			}
		}
		if(typeof(top.body.setMyOwnFocus) != "boolean") { window.focus(); }
	}
}

/**
 * This is the same trim as Java's String.trim() ported over to JScript.
 * Note that this trim will trim from the left and right side of the
 * string and it trims out all whitespace characters and not just spaces.
 */
function trim(str)
{
	if (str == null)
		return null;
			
	var space = 32; // space.
	var count = str.length;
	var len = str.length;
	var st = 0;
	while (st < len && str.charCodeAt(st) <= space)
	    st++;
		
	while (st < len && str.charCodeAt(len - 1) <= space)
	    len--;

	return ((st > 0) || (len < count)) ? str.substring(st, len) : str;
}

function getDateString(year, month, day) {
	var months = new Array("January", "February", "March", "April", "May", "June",
		"July", "August", "September", "October", "November", "December");
	//return (month + 1) + "/" + day + "/" + year;
	return months[month] + " " + day + ", " + year;
}

function iq_openNew(urlToGoTo)
{
	window.open(urlToGoTo);
}

function escapeHtml(str)
{
	if (str == null)
		return "";
	var ret = "";
		
	for (var i = 0; i < str.length; i++)
	{
		var ch = str.charAt(i);


		// [10-31-00 mek] Check char. after '&'; if it is a '#' this indicates a UTF8
		// double-byte string.  Do not escape char in this case
		var ch2 = '0';	// default value
		if (i < str.length - 1)	// if there is a subsequent char
			ch2 = str.charAt(i + 1);


		if (ch == '<')
			ret += "&lt;";
		else if (ch == '>')
			ret += "&gt;";
		else if (ch == '&')
			if (ch2 != '#')
				ret += "&amp;";
			else
				ret += ch;
		else if (ch == '"')
			ret += "&quot;";
		else if (ch == '\'')
			ret += ("&#039;");
		else if (ch == '+')
			ret += ("&#043;");
		else
			ret += ch;
	}

	return ret;
}

// needed for Mac NS not to endless loop resize -> onload -> iq_resize -> resize
function macNSSize(width, height)
{
	if (top.innerWidth != width) // height is not a reliable check
	{
		top.innerHeight = height;
		top.innerWidth = width;
	}
}

function iq_resizeGoTo(width, height, destinationURL)
{
//alert("destinationURL: " + destinationURL);
	var leftEdgeOfPopup = (screen.width - width) / 2; // center popup on screen
	if (iq_getBrowserType() == "NS")
	{
		if ((navigator.userAgent.indexOf("Mozilla/4.") == -1) || (destinationURL!=null && trim(destinationURL) != ""))  { // if it's NOT NS 4.x, OR there is a destinationURL, do this stuff, otherwize don't do any resize or moveto. Avoid ns < 6 Data Missing bug#10600 and bug#10576 and 10578 unwanted scrollbars on mac
			if (navigator.platform.indexOf("Mac") >= 0) {
				setTimeout("macNSSize(" + width + ", " + height + ");", 50); // must have a timeout for mac to know it has been resized
			} else { // not in Mac
				// don't resize if we don't have to, it flickers
				if (top.innerHeight != height || top.innerWidth != width )
				{
					top.innerHeight = height;
					top.innerWidth = width;
				}
			}
			// only move if we have to
			if (top.screenX != leftEdgeOfPopup || top.screenY != (screen.availHeight - top.outerHeight) / 2)
			{
				top.moveTo(leftEdgeOfPopup, (screen.availHeight - top.outerHeight) / 2);
			}
		}
	}
	// don't moveTo for AOL - they don't like it:) #9373
	else if ((iq_getBrowserType() == "IE") && (navigator.userAgent.indexOf("AOL") == -1))
	{
		//this is for bug 10249
		if (navigator.platform.indexOf("Mac") >= 0) {
			top.resizeBy(1,1);
			top.resizeTo(width,height);
			topEdgeOfPopup = (screen.availHeight - height)/2;
			top.moveTo(leftEdgeOfPopup, topEdgeOfPopup);
		}else { // else not Mac IE
			var rW = width - top.document.body.clientWidth - 0;
			var rH = height - top.document.body.clientHeight - 0;
			// only move if we have to
			if (rW != 0 || rH != 0){
				top.resizeBy(rW, rH);
			}

		// Next we set the X = offscreen (past the width of the screeen)
		// and Y = zero.
		// screenTop gets the Y of the INNER window (not supported in IE 4.0)
		// Since the window is now at the top of the screen,
		// screenTop reveals how many pixels of menu/toolbars your browser has.
			if (typeof(window.screenLeft) == "undefined") { // this is IE 4.0. screenLeft and screenTop = "undefined"
				top.moveTo(screen.width + 10,0);
				topEdgeOfPopup = (screen.availHeight - height)/2;
				topEdgeOfPopup = topEdgeOfPopup < 5 ? 5 : topEdgeOfPopup;
				top.moveTo(leftEdgeOfPopup, topEdgeOfPopup);
				// Checking current win position. Don't move if you don't have to.
				// and else not IE 4.0
			}else if (rW != 0 || rH != 0 || window.screenLeft > screen.availwidth){
				top.moveTo(screen.width + 10,0);
				var tSpace = screenTop + 26; // add 26 to compensate for status bar which is present when "fullBrowserOptions" is true.
				topEdgeOfPopup = (screen.availHeight - (height + tSpace))/2;
				topEdgeOfPopup = topEdgeOfPopup < 5 ? 5 : topEdgeOfPopup;
				top.moveTo(leftEdgeOfPopup, topEdgeOfPopup);
			}
		} // end else not Mac IE
	}
	if (destinationURL!=null &&
		trim(destinationURL) != "")
		top.location = destinationURL;
}

function iq_goTopToUrl(url) // this function added to fix IE 5.5 bug 7383
{
	top.location = url;
}

function iq_isMac()
{
	var agt = navigator.userAgent.toLowerCase();
	return (agt.indexOf("mac")!=-1);
}

function iq_canDoPrint()
{
	if (iq_isMac() || window.print == null)
		return false;
	return true;
}

function iq_createPrintWindow(url)
{
	window.open(url, "print_image",
		"toolbar=yes,location=no,directories=no,status=no,menubar=yes," +
		"resizable=yes,width=600,height=400");
}

