/*
 * Common javascript functions
 *
 */
 
function toLocalTime(date, format) {
	var output = format;
	var timeZoneDiffInMinutes = new Date().getTimezoneOffset();
	
	date.setMinutes(date.getMinutes() - timeZoneDiffInMinutes);
	
	var month = "0" + date.getMonth();
	var day = "0" + date.getDate();
	var hour = "0" + date.getHours();
	var minute = "0" + date.getMinutes();

	output = output.replace(/y+/, date.getFullYear());
	output = output.replace(/M+/, month.substr(month.length - 2, 2));
	output = output.replace(/d+/, day.substr(day.length - 2, 2));
	output = output.replace(/h+/, hour.substr(hour.length - 2, 2));
	output = output.replace(/m+/, minute.substr(minute.length - 2, 2));
	return output;
}

/**
 * Reloads the current page with specified URL parameter set to specified value
 */
function reloadPageWithParam(name, value) {
	window.location = getUrlWithParam(document.URL, name, value);
}

function getUrlWithParam(url, paramName, paramValue) {
	var baseURL = url.replace(new RegExp("(&|\\?)" + name + "=.*?(?=$|&)"), "");

	if (baseURL.indexOf("?") == -1 && baseURL.indexOf("&") > -1)
		baseURL = baseURL.replace("&", "?");

	var token = baseURL.indexOf("?") == -1 ? "?" : "&";

	return baseURL + token + paramName + "=" + paramValue;
}

function submitForm(form, eventTarget, eventArgument) {
    if (!form.onsubmit || (form.onsubmit() != false)) {
        form.__EVENTTARGET.value = eventTarget;
        form.__EVENTARGUMENT.value = eventArgument;
        form.submit();
    }
}

function replaceHeadline(tagId, source, width, height) {
	var headlineTag = document.getElementById (tagId);
	if (headlineTag != null && headlineTag.childNodes.length > 0) {
		var imgTag = document.createElement("img");
		imgTag.src = source;
		imgTag.border = 0;
		imgTag.alt = headlineTag.childNodes[0].nodeValue;
		imgTag.width = width;
		imgTag.height = height;
		for (var i=headlineTag.childNodes.length - 1 ; i >= 0 ; i --) {
		    headlineTag.removeChild(headlineTag.childNodes[i]);
		}
		headlineTag.appendChild(imgTag);
	}
}

function popImage(title, src, width, height) {
    
    //Add some margins    
    width = parseInt(width) + 60;
    height = parseInt(height) + 60;
    
	var winl = (screen.width - width) / 2;
	var wint = (screen.height - height) / 2;
	
	var winprops = 'height='+height+',width='+width+',top='+wint+',left='+winl+',scrollbars=\"yes\",resizable';
	var win = window.open("","", winprops);	
		
	win.document.write('<html><head><style> BODY { margin: 0px; } TABLE { width: 100%; height: 100%; cursor: pointer; } TABLE TD { vertical-align: middle; text-align: center; width: 100%; height: 100%;}</style></head><body><table onclick=\"window.close();\"><tr><td><img src=\"'+src+'\"></td></tr></table></body></html>');    
	win.document.close();
	win.document.title = title;
	
	if (parseInt(navigator.appVersion) >= 4) { 
	    win.window.focus(); 
	}
}

function makePrintPage(id, width, height, customScript) {	
	var winprops    = 'height='+height+',width='+width+',scrollbars=1, resizable=1, status=0, location=0';
	var win         = window.open("","", winprops);	
	
	var script = "<script type='text/javascript'> function start() { $('a').removeAttr('href'); $('*[onclick]').removeAttr('onclick'); $('form').attr({onsubmit: 'return false;'}); "+ customScript +" window.print(); }</script>";
	
    win.document.write('<html><head>'+ $("head").html() + script +'</head><body style="background-color: white; background-image: none; padding: 20px;" onload="start();">'+ $("#"+id).html() +'</body></html>');   
	win.document.close();	
	win.moveTo(100,100);
}

function enableTextBoxHint(textbox) {
	var hint = textbox.attr("title");
	if(!hint) return;
	
	// clear hint on focus
	textbox.focus(function() {
		if(textbox.val() == hint) {
			textbox.val("");
			textbox.removeClass("blur");
		}
	});
	
	// reset hint on blur
	textbox.blur(function() {
		if(textbox.val() == "") {
			textbox.val(hint);
			textbox.addClass("blur");
		}
	});

	// clear hint on form submit
	textbox.parents("form:first()").submit(function() {
		if(textbox.val() == hint) {
			textbox.val("");
			textbox.removeClass("blur");
		}
	});

	textbox.blur();
}

function toggleCheckbox(id) {
    var box = document.getElementById(id);
    if(box)
        box.checked = box.checked ? false : true;
}
 
function ensureFrameset(redirectUrl) {
  if(top.location == location) {
    top.location.href = redirectUrl;
  }  
}
  
function breakFrameset() {  
  if (top.location != location) {
    top.location.href = document.location.href;
  }
}

function getElementById(elementId) {
	return (document.getElementById) ? document.getElementById(elementId) : ((document.all) ? document.all[elementId] : null);
}

function toggleVisibility(elementId) {
	var element = getElementById(elementId);
	if(element && element.style) {
		element.style.display = element.style.display == 'none' ? 'block' : 'none';
	}
}

function setVisibility(elementId, show) {
	var element = getElementById(elementId);
	if(element && element.style) {
		element.style.display = show ? 'block' : 'none';
	}
}

function setElementClass(elementId, classname) {
	var element = getElementById(elementId);
	if(element) {
		element.className = classname;
	}
}

function fixOrderForm() {
    setTimeout("reallyfixOrderForm()",200);
}

function reallyfixOrderForm() {
	document.forms[0].confirm_order.disabled=!(document.forms[0].proofreadingversion[0].checked||document.forms[0].proofreadingversion[1].checked);
    document.forms[0].confirm_order.checked=false;
    if(document.forms[0].distribute_through_HQ!=null){
        setVisibility('distributorpanel',!document.forms[0].distribute_through_HQ.checked);
    }
}

function popupWindow(name, w, h, x, y, loc, men, res, scr, sta, too) {
  var e='',c=',',xf='left=',yf='top='; this.n = name;
  if (document.layers) {xf='screenX='; yf='screenY=';}
  this.f = (w?'width='+w+c:e)+(h?'height='+h+c:e)+(x>=0?xf+x+c:e)+
    (y>=0?yf+y+c:e)+'location='+loc+',menubar='+men+',resizable='+res+
    ',scrollbars='+scr+',status='+sta+',toolbar='+too;
  this.opened = function() {return this.w && !this.w.closed;};
  this.close = function() {if(this.opened()) this.w.close();};
  this.focus = function() {if(this.opened()) this.w.focus();};
  this.load = function(sUrl) {
    if (this.opened()) this.w.location.href = sUrl;
    else this.w = window.open(sUrl,this.n,this.f);
    this.focus();
    return false;
  };
}

var popup = new popupWindow(
  'popup',              // target name
  screen.width/2, screen.height-200,  // size: width, height
  screen.width/4, 100, // position: left, top
  0,                      // location field
  0,                      // menubar
  1,                      // resizable
  1,                      // scrollbars
  0,                      // statusbar
  0);                     // toolbar
  
var internalpopup = new popupWindow(
  'internalpopup',              // target name
  812, screen.height-200,  // size: width, height
  Math.max((screen.width-812)/2,0), 100, // position: left, top
  0,                      // location field
  0,                      // menubar
  1,                      // resizable
  1,                      // scrollbars
  0,                      // statusbar
  0);                     // toolbar 

// Shows a popup window
function showPopup(url, width, height) {
    var settings = 'toolbar=no,directories=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no';
    if(width)
        settings += ',width=' + width;
    if(height)
        settings += ',height=' + height;

	var wnd = window.open(url, 'popup', settings);
	if(wnd)
		wnd.focus();
}

/* 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    Cookie related code
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*/

function setCookie (name, value) {
	document.cookie = name + "=" + escape(value);
}
		
function getCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieValue (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}

function getCookieValue (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  
  if (endstr == -1) 
	endstr = document.cookie.length;
	
  return unescape(document.cookie.substring(offset, endstr));
 }
