// Place your application-specific JavaScript functions and classes here

var useAlphaHack = false;
if((BrowserDetect.browser == "Explorer")&&(BrowserDetect.version < 7.0)&&(BrowserDetect.version >= 5.5)) {
	useAlphaHack = true;
}

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;
}

function windowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {w: myWidth + f_scrollLeft(), h:myHeight + f_scrollTop()};
}

var hiddenSelects = [];

var currentPopupId = null;
var popupStack = [];

function popup(divId, mode, callback) {
	
	log("popup(" + divId + ")");
	var div = $(divId);
	if(div==null) {
		alert("unable to get element:" + divId);
		return;
	}
	
	var bgdiv = $('popupbackground');
	if(bgdiv==null) {
		alert("unable to get element:popupbackground");
		return;
	}
	
	var height = f_clientHeight();
	var width = f_clientWidth();
	
	var ws = windowSize();
	
	if(width < document.body.clientWidth) {
		width = document.body.clientWidth;
	}
	
	/*if (document.body.scrollHeight>document.body.offsetHeight){ 
		bgdiv.style.height=document.body.scrollHeight+"px"; 
	}else{
		bgdiv.style.height=document.body.offsetHeight+"px";
	}*/
	
	bgdiv.show();
	
	div.style.zIndex = 3001;
	
	if(mode==1) {
		
	} else {
		div.style.position="absolute";
		div.style.display="block";
		div.style.visibility="hidden";
		log("scrolltop =" +  f_scrollTop() + ", f_clientHeight()=" + f_clientHeight());
		if( ((((f_clientHeight() / 2) - (div.clientHeight/2))) + f_scrollTop()) <10 ) {
			div.style.top = "10px";
		} else {
			div.style.top = parseInt(((f_clientHeight() / 2) - (div.clientHeight/2)),10) + f_scrollTop() + "px";
			log("div.style.top=" + div.style.top);
		}
		
		div.style.left = parseInt(((f_clientWidth()  / 2) - (div.clientWidth/2)),10) + f_scrollLeft() + "px";
		div.style.visibility="visible";
	}
	
	if(currentPopupId != null) {
	  restoreHiddenSelects();
	  if(currentPopupCallback != null) {
	    currentPopupCallback("hide");  
	  }
		popupStack.push([currentPopupId, currentPopupCallback]);
		$(currentPopupId).style.display="none";
	}
	
	currentPopupId = divId;
	currentPopupCallback = callback;
	storeBackgroundSelects(div);
	
	return {t: div.style.top, l: div.style.left};
}

function storeBackgroundSelects(div) {
	var sels = document.getElementsByTagName("SELECT");
	for(var i=0;i < sels.length;i++) {
		if(!$(sels[i]).descendantOf(div)) {
			hiddenSelects.push(sels[i]);
			sels[i].style.visibility="hidden";
		}
	}
}

function restoreHiddenSelects() {
	while(hiddenSelects.size() > 0) {
		var el = hiddenSelects.pop();
		el.style.visibility = "visible";
	}
}

function swapPopup(oldDivId, newDivId, reposition) {
	var oldDiv = $(oldDivId);
	var newDiv = $(newDivId);
	
	newDiv.style.zIndex = oldDiv.style.zIndex;
	
	if(reposition == true) {
		newDiv.style.visibility="hidden";
		newDiv.style.display="";
		repositionPopup(newDivId);
	} else {
		newDiv.style.top = oldDiv.style.top;
		newDiv.style.left = oldDiv.style.left;
		newDiv.style.width = oldDiv.style.width;
		newDiv.style.height = oldDiv.style.height;
	}
	newDiv.style.display="";
	newDiv.style.visibility="visible";
	oldDiv.style.display="none";
	
	currentPopupId = newDivId;
	if(currentPopupCallback != null) {
    currentPopupCallback("swap");
  }
}

function closePopup(divId, mode) {
	
	if(divId == null) {
		divId = currentPopupId;
	}
	log("closePopup(" + divId + ")");
	var div = $(divId);
	if(div==null) {
		alert("unable to get popup element");
		return;
	}
	var bgdiv = $('popupbackground');
	if(bgdiv==null) {
		alert("unable to get background element");
		return;
	}
	
	if(mode != 1) {
		log(div);
		div.style.visibility="hidden";
		div.style.display="none";
		log(div);
	}
	
	restoreHiddenSelects();
	
	if(popupStack.length > 0) {
	  var psData = popupStack.pop();
		currentPopupId = psData[0];
		currentPopupCallback = psData[1];
		$(currentPopupId).style.display="";
		storeBackgroundSelects($(currentPopupId)) ;
		if(currentPopupCallback != null) {
		  currentPopupCallback("restore");
		}
	} else {
		log(bgdiv);
		//bgdiv.className="popupclose";
		bgdiv.hide();
		log(bgdiv);
		currentPopupId = null;
		currentPopupCallback = null;
	}
	
}

function repositionPopup(divId) {
	var div = $(divId);
	if(div==null) {
		alert("unable to get popup element");
		return;
	}
	
	if( ((((f_clientHeight() / 2) - (div.clientHeight/2))) + f_scrollTop()) <10 ) {
		div.style.top = "10px";
	} else {
		div.style.top = (((f_clientHeight() / 2) - (div.clientHeight/2))) + f_scrollTop() + "px";
	}
	
	div.style.left = (((f_clientWidth()  / 2) - (div.clientWidth/2))) + f_scrollLeft() + "px";
	if(currentPopupCallback != null) {
    currentPopupCallback("reposition");
  }
}


var msgBoxCallback = null;
var msgboxId = null;

function msgBox(title, message, icon, yes, no, cancel, callback) {
	msgBoxCallback = callback;
	msgboxId = getNextId();
	var html="";
	if(icon != null) { html += '<img src="' + icon + '" align="left"/>'; }
	html+="<div>";
	html+='<h3>' + title + '</h3>';
	
	html += '<span class="msgbox_text">' + message + '</span><br/><div class="submit msgbox_buttons">';
	if(cancel != null) {
		html += '<b class="action cancel"><input type="button" value="' + cancel + '" onclick="msgBoxFinish(2);" class="button cancel"/></b>';
	}
	if(yes != null) {
		html += '<b class="action"><input type="button" value="' + yes + '" onclick="msgBoxFinish(0);" class="button"/></b>';
	}
	if(no != null) {
		html += '<b class="action"><input type="button" value="' + no + '" onclick="msgBoxFinish(1);" class="button"/></b>';
	}
	html += "</div>";
	html += "</div>";
	var div = document.createElement("DIV");
	div.className = "popup msgbox";
	div.style.display="none";
	div.id = "msgbox_" + msgboxId;
	div.innerHTML = html;
	
	document.body.appendChild(div);
	popup("msgbox_" + msgboxId);
}

function msgBoxFinish(result) {
	closePopup("msgbox_" + msgboxId);
	var div = document.getElementById("msgbox_" + msgboxId);
	document.body.removeChild(div);
  if(msgBoxCallback != null) {
    msgBoxCallback(result);
  }
}


var promptCallback = null;
var promptId = null;

function promptNew(title, message, icon, ok, cancel, defaultValue, callback) {
	promptCallback = callback;
	promptId = getNextId();
	var html="";
	if(icon != null) {
		html += '<img src="' + icon + '" align="left"/>'; 
	}
	html+='<div>';
	html += '<h3>' + title + '</h3>';
	
	html += '<span class="msgbox_text">' + message + ' <input id="propt_val_' + promptId + '" value="' + defaultValue + '"/></span><br/><div class="submit msgbox_buttons">';
	if(cancel != null) {
		html += '<b class="action cancel"><input type="button" value="' + cancel + '" onclick="promptFinish(1);" class="button cancel"/></b>';
	}
	if(ok != null) {
		html += '<b class="action"><input type="button" value="' + ok + '" onclick="promptFinish(0);" class="button"/></b>';
	}
	
	html += "</div>";
	html += "</div>";
	var div = document.createElement("DIV");
	div.className = "popup msgbox";
	div.style.display="none";
	div.id = "prompt_" + promptId;
	div.innerHTML = html;
	
	document.body.appendChild(div);
	popup("prompt_" + promptId);
	$('propt_val_' + promptId).focus();
	var el = document.getElementById("propt_val_" + promptId);
	el.focus();
}

function promptFinish(result) {
	var val = null;
	closePopup("prompt_" + promptId);
	if(result == 0) {
		var el = document.getElementById("propt_val_" + promptId);
		val = el.value;
	}
	var div = document.getElementById("prompt_" + promptId);
	document.body.removeChild(div);
	promptCallback(result, val);
}

var nextId = 0;
function getNextId() {
	nextId --;
	return nextId;
}

function getElId(el) {
	if(el.id != null) {
		return el.id;
	}
	el.id = "tmp_id_" + getNextId();
	return el.id;
}

var asyncActions = new Hash();

function asyncStart(container) {
  var containerEl = $(container);
  var containerId = getElId(containerEl);
  
  log("asyncStart:" + containerId);
  
  //there can only be one async action per container...
  if(asyncActions[containerId] != null) {
    log("Stopping existing async action " + containerId);
    asyncFinish({id:containerId, v: asyncActions[containerId].v});
  }
  
  var divB = document.createElement("DIV");
  divB.style.display = "none";
  divB.className = "async_action_background";
  
  var div = document.createElement("DIV");
  div.style.display = "none";
  div.className = "async_action";
  
  div.innerHTML="<img src='../../images/spinner_no_bg.gif' alt='[]' />";
  var oldPositioning = null;
  

  var dims = Element.getDimensions(container);
  var offset = Position.cumulativeOffset(containerEl);
  log(offset);
  
  divB.style.position = "absolute";
  divB.style.top = offset[1] + "px";
  divB.style.left = offset[0] + "px";
  divB.style.height = dims.height + "px";
  divB.style.width = dims.width + "px";
  divB.style.display="none";
  document.body.appendChild(divB);
  divB.id = "aa_" + containerId + "_bg";
  
  div.style.position = "absolute";
  div.style.top = offset[1] + "px";
  div.style.left = offset[0] + "px";
  div.style.height = dims.height + "px";
  div.style.width = dims.width + "px";
  div.backgroundColor="#000000";
  div.style.display="none";
  document.body.appendChild(div);
  //Effect.Appear(div, { duration: 0.2 });
  
  div.id = "aa_" + containerId;
  
  $(divB).show();
  $(div).show();
  var v = getNextId();
  asyncActions[containerId] = {d:div, db:divB, c:container, p:oldPositioning, v:v};
  return {id: containerId, v:v};
}

function asyncFinish(key) {
  if(key == null) {
    return;
  }
  var containerId = key.id;
  
  var aa = asyncActions[containerId];
  if(aa == null) {
    log("asyncFinish ignored (" + containerId + " not in asyncActions)");
  } else {
    if(aa.v != key.v) {
      log("asyncFinish ignored (" + aa.v + " != " + key.v + ")");
    } else {
      delete asyncActions[containerId];
      try {
        // Check to make sure the object exists before removing it (because this is run twice and may not still exist)
        if($(aa.d.id)){
         // Effect.Fade(aa.d, { 
          //  duration: 0.2, 
          //  afterFinish: function asyncFinishAfterFinish(){document.body.removeChild(aa.d);}
         // });
         document.body.removeChild(aa.d);
        }
        if($(aa.db.id)){
          document.body.removeChild(aa.db);
        }
      } catch(e) {}
    }
  }
}

function setImageUrl(container, img, url, callback) {
	var cbimg = null;
	if(img!= null) {
		cbimg = img; 
	} else {
		var cbimg = document.createElement("IMG");
		cbimg.style.display = "none";
		document.body.appendChild(cbimg);
		log("appended async img");
	}
	var callbackDone = false;
	var asyncKey = null;
	cbimg.onload = function() {
			log("async img loaded: " + callbackDone);
			if(callbackDone) {
				return;
			}
			callbackDone = true;
			/*
			if(img!=null) {
				log("si");
				img.src = cbimg.src;
				log("sd");
			}
			*/
			if(callback!=null) {
				callback(cbimg.src);
			}
			asyncFinish(asyncKey);
			if(img==null) {
				document.body.removeChild(cbimg);
			}
		};
		
	cbimg.src = url;
	if(BrowserDetect.browser == "Explorer") {
		if(cbimg.complete) {
			log("async img complete: " + callbackDone);
			/*
			if(img!=null) {
				img.src = cbimg.src;
			}
			*/
			if(callbackDone) {
				return;
			}
			callbackDone = true;
			if(callback!=null) {
				callback(cbimg.src);
			}
			if(img==null) {
				document.body.removeChild(cbimg);
			}
		} else {
			asyncKey = asyncStart(container);
			
		}
	} else {
		//other browsers call onload properly...
		asyncKey = asyncStart(container);
	}
}

function setBackgroundImage(container, div, url) {
	setImageUrl(container, null, url, function(nUrl) {
		log("setting background image to " + nUrl);
		div.style.backgroundImage = "url(" + nUrl + ")";
	});
}


function setTransImage(el, src, w, h) {
	if(useAlphaHack) {
		el.src = "/ppr/images/trans.gif";
		el.style.fontSize = "1px";
		el.style.width = w + "px";
		el.style.height = h + "px";
		el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '", sizingMethod="scale")';
	} else {
		el.src = src;
		el.width = w;
		el.height = h;
	}
}

function updateStatesFromEl(countryEl, stateControlId) {
	//alert("getting updateStatesFromEl..");
	updateStates(countryEl.value, stateControlId);
}

function updateStates(countryId, stateControlId) {
	//alert("getting states..");
	//alert(stateControlId);
	var sb = document.getElementById(stateControlId);
	//alert("got el");
	//alert(sb);
	if(sb==null) {
		alert("unable to get states element (" + stateControlId + ") to populate it");
		return;
	}
	//alert("1");
	sb.options.length = 0;
	//alert("2");
	sb.options[0] = new Option("Updating...","");
	
	//alert("asyncStart..");
	var aKey = asyncStart(stateControlId);
	
	//alert("calling..");
	var t2 = new Ajax.Request("/ppr/countries/get_states?id=" + countryId + "&ctl=" + stateControlId, {asynchronous:true, evalScripts:true, onComplete: function() { asyncFinish(aKey);},
			onException: function(t,e) {
				alert(e.name);
				alert(e.message);
	}});
}

function updatePostcode(countryId, postcodeControlId) {
  var pc = $(postcodeControlId);
  
  if (pc == null) {
    alert("Unable to get postcode control (" + postcodeControlId + ") to update");
    return;
  }
  
  var aKey = asyncStart(postcodeControlId);
  
  var t2 = new Ajax.Request("/ppr/countries/check_postcode_usage?id=" + countryId + "&ctl=" + postcodeControlId, {asynchronous:true, evalScripts:true, onComplete: function() { asyncFinish(aKey);},
			onException: function(t,e) {
				alert(e.name);
				alert(e.message);
	}});
}

function toggle_faq(fid) {
	var el = $("a_" + fid);
	if(el.style.display=="none") {
		el.style.display="";
	} else {
		el.style.display="none";
	}
}

function showDesignerFaq() {
	myLightWindow.activateWindow({
			href: "/ppr/product_info/pop/tshirt_faq", 
			title: 'FAQs',
			width: 650,
			height: 550
		});
	
}

function showCv2Info() {
	myLightWindow.activateWindow({
			href: "/ppr/product_info/pop/cv2", 
			title: 'CV2 Numbers',
			width: 400,
			height: 400
		});
	
}
	
function showDesignerShipping() {
	myLightWindow.activateWindow({
			href: "/ppr/product_info/pop/shipping", 
			title: 'Shippping Information',
			width: 650,
			height: 550
		});
	
}


var ttCurrentPopup = null;
var ttTimer = null;

function ttMouseOver(el, popEl) {
	if(ttCurrentPopup==popEl) {
		ttClearTimeout();
		return;
	}
	if(ttCurrentPopup!=null) {
		ttCurrentPopup.style.display="none";
	}
	//position the new popup
	
	pos = Position.cumulativeOffset(el);
	popEl.style.left = (pos[0] + 10) + "px";
	popEl.style.top = (pos[1] + 10) + "px";
	popEl.style.display="block";
	
	ttClearTimeout();
	ttCurrentPopup = popEl;
	
}

function ttMouseLeave(el, popEl) {
	if(ttCurrentPopup==popEl) {
		ttSetCloseTimeout(ttCurrentPopup);
		return;
	}
}

function ttSetCloseTimeout(popEl) {
	ttClearTimeout();
	//log("ttSetCloseTimeout()");
	ttTimer = window.setTimeout( function () { 
			popEl.style.display="none";
			ttCurrentPopup = null;
	}, 1000);
}

function ttClearTimeout() {
	if(ttTimer != null) {
		window.clearTimeout(ttTimer);
		ttTimer = null;
	}
}

//quick version of $ that does not extend
function $q(element) {
  if (typeof element == 'string')
    element = document.getElementById(element);
  return element;
}

//quick version that does not extend
function firstChildElement(element) {
	var el = element.firstChild;
	while((el != null)&&(el.nodeType != 1)) {
		el = el.nextSibling;
	}
	return el;
}

//quick version that does not extend
function nextSiblingElement(element) {
	var el = element.nextSibling;
	while((el != null)&&(el.nodeType != 1)) {
		el = el.nextSibling;
	}
	return el;
}

//quick version that does not extend
function prevSiblingElement(element) {
	var el = element.previousSibling;
	while((el != null)&&(el.nodeType != 1)) {
		el = el.previousSibling;
	}
	return el;
}





function hashCopy(src) {
	var dst = {};
	for(k in src) {
		dst[k] = src[k];
	}
	return dst;
}

function hashSize(hash) {
	var cnt = 0;
	for(k in hash) {
		cnt++;
	}
	return cnt;
}

function hashEmpty(hash) {
	var cnt = 0;
	for(k in hash) {
		return false;
	}
	return true;
}

function hashClearEmpty(src) {
	var dst = {};
	for(k in src) {
		if((src[k]!=null)&&(src[k] != "")) {
			dst[k] = src[k];
		}
	}
	return dst;
}


var debug = null;

function log(msg, trace) {
	//if(BrowserDetect.browser == "Firefox") {
		try {
			console.debug(msg);
			if(trace) {
				console.trace();
			}
		} catch(e) {}
	//}
	if((debug!=null)&&(debug.style.display != 'none')) {
		debug.value = msg + "\n" + debug.value;
	}
	/* else if(debug==null) {
		alert("no debug: " + msg);
	} else {
		alert(debug.style.display);
	}
	*/
}

function imageRollover(){
	var a=document.getElementsByTagName('li');
	for(x=0; x<a.length; x++){
		if(a[x].className=="display"){
			var b=a[x].getElementsByTagName('a');
			b[0].onmouseover=function(){ 
				var c=this.getElementsByTagName('img');
				if(c.length==2){
					c[0].style.display="none";
					c[1].style.display="inline";
				}
			}
			b[0].onmouseout=function(){
				var c=this.getElementsByTagName('img');
				if(c.length==2){
					c[1].style.display="none";
					c[0].style.display="inline";
				}
			}
		}
	}
}

var asyncProgressKey = null;
var asyncProgressStartingText = null;
var asyncProgressOptions = null;

function startAsyncProgress(key, title, initialStartingText, options) {
  asyncProgressOptions = options;
  if(asyncProgressOptions == null) asyncProgressOptions = {};
  asyncProgressKey = key;
  if($("async_progress_dialog") == null) {
    alert("Unable to display progress: async_progress_dialog missing");
    return
  }
  $("async_progress_title").update(title);
  if(initialStartingText == null) {
    initialStartingText = "starting..";
  }
  asyncProgressStartingText = initialStartingText;
  $("async_progress_actions").hide();
  updateAsyncProgress(initialStartingText, 0, true, null, null);
  
  var actions = [];
  if(asyncProgressOptions.actions != null) {
    for(k in asyncProgressOptions.actions) {
      var action = asyncProgressOptions.actions[k];
      var clz = action.className == null ? '' : ' class="' + action.className + '"';
      actions.push('<input ' + clz + ' type="button" value="' + action.caption + '" onclick="callAsyncProgressAction(\'' + k + '\');"/>');
    }
  } else if(asyncProgressOptions.requireOk) {
    actions.push('<input type="button" value="OK" onclick="updateAsyncProgressOk();"/>');
  }
  $('async_progress_actions').update(actions.join(''));
  
  popup("async_progress_dialog");
}

function continueAsyncProgress(key, initialStartingText) {
  if(initialStartingText == null) {
    initialStartingText = asyncProgressStartingText;
  }
  asyncProgressKey = key;
  updateAsyncProgress(initialStartingText, 0, true, null, null);
}

function updateAsyncProgress(statusText, percent, doRefresh, warnings, errors, notes, metaData) {
  
  var totalWidth = parseInt($("async_progress_status_bar").offsetWidth);
	var barWidth = parseFloat(totalWidth * percent) / 100.0;
	$("async_progress_indicator").style.width = parseInt(barWidth) + "px";
	$("async_progress_message").update(statusText);
	
  if((notes == null)||(notes.length == 0)) {
    $("async_progress_notes").hide();
  } else {
    $("async_progress_notes").show();
    var html = "";
    for(var i=0; i < notes.length; i++) {
      html += "<li>" + notes[i] + "</li>";
    }
    $("async_progress_note_list").update(html);
  }
  
  if((warnings == null)||(warnings.length == 0)) {
    $("async_progress_warnings").hide();
  } else {
    $("async_progress_warnings").show();
    var html = "";
    for(var i=0; i < warnings.length; i++) {
      html += "<li>" + warnings[i] + "</li>";
    }
    $("async_progress_warning_list").update(html);
    $("async_progress_actions").show();
  }
  if((errors == null)||(errors.length == 0)) {
    $("async_progress_errors").hide()
  } else {
    $("async_progress_errors").show();
    var html = "";
    for(var i=0; i < errors.length; i++) {
      html += "<li>" + errors[i] + "</li>";
    }
    $("async_progress_error_list").update(html);
    $("async_progress_actions").show();
  }
  
	if(doRefresh) {
    if(asyncProgressKey != null) { //this lets us start the dialog before we have a key...
      window.setTimeout( function() {
        var ajax = new Ajax.Request("/shared/lookups/async_progress?key=" + encodeURIComponent(asyncProgressKey) + "&ts=" + new Date().getTime(), {asynchronous:true, evalScripts:true, method:'get', 
          onFailure: function() {
            updateAsyncProgress(caption, percent, doRefresh, warnings, errors); //retry....
          }
        });
      }, 500);
    }
	} else {
    if(asyncProgressOptions.onFinish != null) asyncProgressOptions.onFinish(warnings, errors, notes, metaData);
    if((asyncProgressOptions.requireOk != true)&&((asyncProgressOptions.actions == null)||(asyncProgressOptions.actions.length == 0))) {
      window.setTimeout( function() {
        closePopup("async_progress_dialog");
      }, 1000);
    } else {
      $("async_progress_actions").show();
    }
	}
}

function updateAsyncProgressOk() {
  closePopup("async_progress_dialog");
  if(asyncProgressOptions.onOK != null) asyncProgressOptions.onOK();
}

function callAsyncProgressAction(action) {
  closePopup("async_progress_dialog");
  var actionData = asyncProgressOptions.actions[action];
  if(actionData != null) {
    actionData.callback();
  }
}

// monitors whether changes made to the current page
var page_dirty = false;

function setPageDirty() {
  page_dirty = true;
}

function isPageDirty() {
  return page_dirty;
}

function pageDirtyCheck() {
  if (isPageDirty()) {
    return confirm("Changes are not saved. Do you still want to leave this page?");
  }
}


// prevent double click submit button
function stopDoubleClick(timeout) {
  var f;
  var d = document.createElement('DIV');
  d.style.height = document.body.offsetHeight + 'px';
  d.style.width = document.body.offsetWidth + 'px';
  d.style.top = d.style.left = 0;
  d.className = "screen_guard";
  d.id = "screen_guard";
  d.style.display = "none";
  document.body.appendChild(d);
  
  for (var i=0; i<document.forms.length; i++) {
    document.forms[i].onkeypress = "return false;";
  }
  $(d).show();
  setTimeout("disableSubmit();", 10);
  if (timeout != 0) setTimeout("enableForms();", timeout);
  
  return true;
}

function disableSubmit() {
  for (var i=0; i<document.forms.length; i++) {
    for (var j=0; j<document.forms[i].elements.length; j++) {
      if (document.forms[i].elements[j].type == "submit") {
        document.forms[i].elements[j].disabled = "disabled";
      }
    }
  }
}

function enableForms() {
  var sg = $("screen_guard")
  if (sg != null) sg.remove();
  
  for (var i=0; i<document.forms.length; i++) {
    document.forms[i].onkeypress = "";
    for (var j=0; j<document.forms[i].elements.length; j++) {
      if (document.forms[i].elements[j].type == "submit") {
        document.forms[i].elements[j].disabled = "";
      }
    }
  }
}


