
var YOJIMG = {};
var gPopUp = null;
var gPopUpName = '';

function openWindow(URL, height, width, windowName, features) 
{
	var win = null;

	if (openWindow.arguments.length < 5 || openWindow.arguments[4] == "")
		features = "resizeable=no,scrollbars=no,menubar=no";

	var name = windowName + width + "x" + height;

	if (window.location.protocol != "https:")
		name += "xhttps";

	if (gPopUp != null && !gPopUp.closed && name == gPopUpName) {
		gPopUp.location.replace(URL);
		win = gPopUp;
	} 
	else {
		features += ',width=' + width + ',height=' + height;
		win = window.open(URL, name, features);

		if(win==null)
		{
			throw(1);
		}

		gPopUp = win;
		gPopUpName = name;
	}
		
	if (win && win.focus)
	{
		try
		{
			win.focus();
		}
		catch(e)
		{
			throw(2);
		}
	}
}



function showIt(ele) {
  if (ele.style.display == 'none')
    ele.style.display = 'block';
  else
    ele.style.display = 'none';
}



// format email links to protect against email-harvesting bots
function drawMailToLink(domain, name, linkedText, subject, body)
{
  var emailURL = 'mailto:'+name+"@"+domain;
  if (subject)
    emailURL += '?subject=' + escape(subject); 
  if (body){
    if (subject)
      emailURL += '&';
    else
      emailURL += '?';
    
    emailURL += 'body=' + escape(body);
  }

  if (!linkedText)
    location.href = emailURL;
  else{
    document.write('<A HREF="' + emailURL  + '">' + linkedText + '</A>');
  }  
}


function updatePosition(oBox, e) {
 
	var posx = 0;
	var posy = 0;
	if (!e) e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
  
  
  if (posy < 400) posy = posy + 400;
  
  oBox.style.top = (posy - 350) + 'px';
  oBox.style.left = posx + 'px'; 
  oBox.style.display = 'block';
  return false;
}

function drawContactBox(oEvent) {
	
    oEvent = oEvent || window.event;
    
    if (!document.createElement || !document.createTextNode) {
        return true;
    }
    
    var formName = 'contactFrm';	
    var exists = document.getElementById(formName);
  
    //check for query subject in passed in event href
    var u = oEvent.srcElement || oEvent.target;

    var qq = {};
    if (u && u.href && /subject=/.test(u.href)) {
        var ua = u.href.split('?')[1];
        if (ua) {
          ua = ua.split('&');
          if (ua.length > 0) {
            for (var i=0; i < ua.length; i++) {
              var t = ua[i].split('=');
              qq[t[0]] = t[1]; 
            }
          }
        }
    }
  
    var sub = (qq['subject'])? decodeURIComponent(qq['subject']) : '[enter subject]';
  
  
    // reuse any existing contact form 
	if (exists) {
        resetForm();
        if (sub) {
            document.getElementById('cFormSubject').value = sub;
        }
        updatePosition(exists, oEvent);
        return false; 
    }
	
    var cFrm = document.createElement('form');
    cFrm.name = formName;
    cFrm.id = formName;
    cFrm.onsubmit = function() {return sendMessage(this);};
    
    var cH1 = document.createElement('h1');
    var cTxt1 = document.createTextNode('make contact');
    cH1.appendChild(cTxt1);
    
    var cDiv1 = document.createElement('div');
    cDiv1.id = 'errorBox';
    cDiv1.style.textAlign = 'center';
    cDiv1.className = 'error';
    window.contactErrorBox = cDiv1;
    
    var cInput1 = document.createElement('input');
    cInput1.type = 'text';
    cInput1.name = 'from';
    cInput1.id = 'cFormFrom';
  
    //setInputName(cInput1, 'from');
    cInput1.value = '[your email]';
    cInput1.onfocus = function () {clearMe(this);};
    cInput1.size = "32";
    cInput1.origText = cInput1.value;
    
    var cBr1 = document.createElement('br');
    
    var cInput2 = document.createElement('input');
    cInput2.type = 'text';
    cInput2.name = 'subject';
    cInput2.id = 'cFormSubject';
    //setInputName(cInput2, 'subject');
    cInput2.value = sub || '[enter subject]';
    //if (sub) cInput2.touched = true;
    // if a value for the subject field has been prefilled, do
    // not clear it.
    if (!sub) {
        cInput2.onfocus = function () {clearMe(this);};
    }
    else {
        cInput2.touched = true;
    }
    
    cInput2.size = "32";
    cInput2.origText = cInput2.value;
  
    var cBr2 = document.createElement('br');
    
    var cTextArea = document.createElement('textarea');
    cTextArea.rows = '10';
    cTextArea.cols = '30';
    cTextArea.name = 'msg';
    cTextArea.id = 'cFormMsg';
    cTextArea.onfocus = function () {clearMe(this);};
    
    var cTextAreaTxt = document.createTextNode('[enter message]');
    cTextArea.appendChild(cTextAreaTxt);
    
    var cBr3 = document.createElement('br');
    
    var cReset = document.createElement('input');
    cReset.type = 'reset';
    cReset.value = 'oops';
    cReset.onclick = function () {
        resetForm();
    };
	
    var cSubmit = document.createElement('input');
    cSubmit.type = 'submit';
    cSubmit.value = 'make contact';
    
    var cClose = document.createElement('a');
    cClose.href = window.location.href;
    cClose.title = 'close window';
    cClose.className = 'close';
    cClose.id = 'contactBoxClose';
    cClose.onclick = function () {return deleteForm();}
    
    var cBr4 = document.createElement('br');
    
    cClose.appendChild(document.createTextNode('close'));
    
    cFrm.appendChild(cH1);
    cFrm.appendChild(cClose);
    cFrm.appendChild(cDiv1);
    cFrm.appendChild(cInput1);
    cFrm.appendChild(cBr1);
    cFrm.appendChild(cInput2);
    cFrm.appendChild(cBr2);
    cFrm.appendChild(cTextArea);
    cFrm.appendChild(cBr3);
    cFrm.appendChild(cReset);
    cFrm.appendChild(cSubmit);
    cFrm.appendChild(cBr4);
    //cFrm.appendChild(cClose);
    
    document.body.appendChild(cFrm);
    
    updatePosition(cFrm, oEvent);
    
    new Mover(formName, false);
    
    return false;
}

// preload "loading" image
var img = new Image(18,18);
img.src = '/images/loading.gif';
var contactHttpReq;
var errorHttpReq;

function sendMessage(frm) {
	window.contactErrorBox.innerHTML = '<img align="absmiddle" src="/images/loading.gif" width="18" height="18" alt="loading..."/>';
  
	var from = $('cFormFrom');
	var subject = $('cFormSubject');
	var message = $('cFormMsg');

  
	if ( !from.touched || !from.value || !subject.touched || !subject.value
		|| !message.touched || !message.value ) {
		window.contactErrorBox.innerHTML = 'please complete all fields';
		return false;
	}

	if ( message.value.length > 400 ) {
		window.contactErrorBox.innerHTML = 'Message too long!';
		return false;
	}

	
	contactHttpReq = new AjaxEvent('contactForm', '/message_handler.php', handleResponse, 'POST');
	contactHttpReq.run(['from=' + from.value, 'subject=' + subject.value, 'message=' + message.value, 'submit=1']);
	
	// so form doesn't submit
	return false; 
}

function handleResponse() {
	var error;
	var success;
	
	if (contactHttpReq && contactHttpReq.isComplete()) {
		var entries = contactHttpReq.HTTPObject.responseXML.getElementsByTagName('responseMsg');
		error = GetElementText(entries[0], 'error');
		success = GetElementText(entries[0], 'success');
		if (error != 0)
			window.contactErrorBox.innerHTML = error;
		else if (success == 1) {
			window.contactErrorBox.innerHTML = 'thanks!';
			//window.setTimeout('resetForm();toggle("contactFrm");', 1000 * 2);
			window.setTimeout('deleteForm();', 1000 * 2);
		}					
	}
}
			
function clearMe(obj) {
	if (!obj.touched) 
		obj.value = '';

	obj.touched = true;
}

						
function resetForm() {
	var frm = document.forms.contactFrm;

	var from = $('cFormFrom');
	var subject = $('cFormSubject');
	var message = $('cFormMsg');
  
	from.touched = false;				
	subject.touched = false;
	message.touched = false;

	window.contactErrorBox.innerHTML = '';
	
    frm.reset();
}

function deleteForm() {
	var frm = $('contactFrm');
	//document.body.removeChild(frm);
	toggle(frm);
	return false;
}


// cookie functions

var gCookieLife = '1 year'; // cookies will expire in 1 year by default
var gMajorDelim = '|'; // delimiter for sub-cookies in meta cookies
var gMinorDelim = '='; // delimiter between key-value pairs for sub-cookies w/in meta cookies
var gDomain = '.yojimg.net';

// set a cookie	
function setCookie(name, value, expires, path, domain, secure) {

	if (!name || !value) {
		alert ("ERROR: missing name or value for [" + name + "] -- cookie not set!");
		return false;
	}
	
	var cookieUnits = 24 * 60 * 60 * 1000; // default to day units
	var permCookie = true;
	var expDate = new Date();
	
	if (!expires) expires = gCookieLife;
	
	if (expires.match(/year/))
		expires	= parseInt(expires) * 365 * cookieUnits;
	else if (expires.match(/month/))
		expires = parseInt(expires) * 30 * cookieUnits;
	else if (expires.match(/kill|remove|delete/))
		expires = -1 * 365 * cookieUnits;
	else
		permCookie = false;
		
	if (permCookie)
		expDate.setTime(expDate.getTime() + expires);
		
	
	var cookieStr = name + "=" + escape(value) 
		+ ((permCookie) ? "; expires=" + expDate.toGMTString() : "") 
		+ "; path=" + ((path) ? path : "/")
		+ "; domain=" + ((domain) ? domain : gDomain)
		+ ((secure) ? "; secure" : "");
	
	//alert(cookieStr);
	
	document.cookie = cookieStr;
	
	return true;
}


// retrieve a cookie by name
function getCookie(name) {
	var cookieStr = document.cookie;
	var cookies = new Array();
	var result;
	
	if (cookieStr) cookies = cookieStr.split(/;\s*/);
	
	result = splitFind(cookies, name, '=');
	
	return(unescape(result));
}


function deleteCookie(name) {
  return setCookie(name, -1, 'kill');
}

// sort through a given array, splitting up each
// element by a given delimiter into key/value pairs,
// then find the value that corresponds to a given key.
// (used to parse cookies)
function splitFind(list, key, delim) {
	var result, 
		fields, 
		tmp, 
		len = list.length;
	
	for (var i=0; i < len; i++) {
		tmp = list[i];
		if (tmp) {	
			fields = tmp.split(delim);
			if (fields[0] == key) {
				result = fields[1];
				break;		
			}	
		}
	}
	
	return(result);
}

// retrieve the value for a subcookie in a meta cookie.
function getMetaCookie(subName, name) {
	var cookieStr = getCookie(name);
	return(splitFind(cookieStr.split(gMajorDelim), subName, gMinorDelim));

}

// set a sub cookie within a meta cookie.
function setMetaCookie(subName, name, value) {
	var currentCookieVal = getCookie(name);
	var subCookies = new Array();
	var temp = new Array();
	var newCookieVal = '';
	
	if (currentCookieVal) 
		subCookies = currentCookieVal.split(gMajorDelim);
		
	// get all existing sub cookies
	for (var i in subCookies) {
		var fields = subCookies[i].split(gMinorDelim);
		if (fields[0] && fields[1])
			temp[fields[0]] = fields[1]; // build hash
	}
		
	// set or reset sub cookie
	if (subName)
		temp[subName] = value;
	
	// rebuild cookie string
	for (var i in temp) {
		if (temp[i]) // don't rebuild null values
			newCookieVal += gMajorDelim + i + gMinorDelim + temp[i]; 
	}
	
	return(setCookie(name, newCookieVal));
}

// removes a sub cookie within a meta cookie
function deleteMetaCookie(subName, name) {
	// set value to null so it's subcookie doesn't get re-added
	return(setMetaCookie(subName, name, null));
}


function hideTop(oAnchor){
        toggle(document.getElementById('top'));
        toggle(document.getElementsByTagName('h1')[0]);
        
        if (!oAnchor.touched){
                oAnchor.touched = true;
                oAnchor.innerHTML = '[+] show header';
                setCookie('hdr', 'hide');
        }
        else{
                oAnchor.touched = false;
                oAnchor.innerHTML = '[-] hide header';
                deleteCookie('hdr');
        }
        return false;
}

/*
  toggle panel a, if opening a hide b, pointer focus onto c
*/
function toggle(a, b, c) {
  a = $(a);
	if (b) {
    b = $(b);
  }
  if (c) {
    c = $(c);
  }

  if (a && a.style) {
  	if (a.style.display == 'none') {
  		a.style.display = 'block';
      if (b && b.style.display == 'block'){
        b.style.display = 'none';	
      }
      if (c) {
        c.focus();
      }
  		return true;
  	}	
  	else {
  		a.style.display = 'none';	
    }
  }
  
	return false;
}



function $ (s){
	if(s && typeof(s) == 'string') {
		s = document.getElementById(s);
	}
  return (s);
}

var handleJSError = function(e) {
  errorHttpReq = new AjaxEvent('jsError', '/message_handler.php', function(){}, 'POST');
  errorHttpReq.run(['from=errors@yojimg.net', 'subject=YOJIMG.NET_JS_ERROR', 'message=ERROR: ' + e + '\nPAGE: ' + window.location + '\nUSER_AGENT: ' + navigator.userAgent, 'submit=1']); 
  alert("Sorry, an error has occurred: \n\n" + e + "\n\nThe webmaster has been notified and will address this problem shortly!");
}

//window.onerror = handleJSError;


function setInputName (oInput, inputName) {

  //oInput.setAttribute('name',inputName); 
  
  // browser does not support the W3C DOM method for assigning name attribute 
  //if (oInput.getAttribute('name') != inputName) { 
    oInput = document.createElement('<input name="' + inputName + '">'); 
  //} 
}


YOJIMG.utils = {

  addClass: function (e, n){
    var i,
      result = {},
      output = '',
      classes = e.className.split(' '),
      clen = classes.length;
        
    // propagate result list with existing classes
    for (i = 0; i < clen; i++) {
      result[classes[i]] = 1;
    }
    
    // add in desired class
    result[n] = 1;
    
    for (var k in result) {
      output += k + ' ';
    }
    
    e.className = output;
  },

  removeClass: function (e, n){
    var i,
      classN,
      classes,
      clen;
      
      
    classN = e.className;
    if (classN) {
	  classes = classN.split(' ');
      clen = classes.length;
    
    
    	for (i = 0; i < clen; i++) {
    	  if (classes[i] == n){
    	    classes.splice(i, 1);
    	    break;
    	  }
    	}
    
    	e.className = classes.join(' ');
    }
  },

  hasClass: function (e, n) {
    var ik
      classes = e.className.split(' '),
      clen = classes.length;
        
    for (i = 0; i < clen; i++) {
      if (classes[i] === n) {
        return true;
      }
    }

    return false;
   
  },

  toggleClass: function (e, n) {
    if (YOJIMG.utils.hasClass(e, n)) {
      YOJIMG.utils.removeClass(e, n);
    }
    else {
      YOJIMG.utils.addClass(e, n);
    }
  }, 

  
  '$': function (s) {
	if(s && typeof(s) == 'string') {
      s = document.getElementById(s);
	}
    return (s);
  },

  '$$': function(s) {
    return document.getElementsByClassName(s);
  }
}
