// =====================================================================
// INITIALIZATION SCRIPT
// =====================================================================
// initialize website
function init() {
	// quit if this function has already been called
    if (arguments.callee.done) return;
    arguments.callee.done = true;
	document.getElementById('loading_image').style.display='none';
	document.getElementById('mainbody').style.overflow='auto';
	document.getElementById('mainbody').style.height='auto';
}
window.onbeforeunload = function(){
	document.getElementById('loading_image').style.display = 'block';	
}
var Spell_Win_Name;
var Work_Form_Name;
var Work_Field_Name;

function dc(s){c='';for (i=0;i<s.length;i++){c+=String.fromCharCode(s.charCodeAt(i)-1);}document.write(c)}

function SpellCheck(form_name,field_name) {
	var textform = self.document[form_name][field_name].value;
	if ( ! Spell_Win_Name || Spell_Win_Name.closed || (Work_Form_Name != form_name || Work_Field_Name != field_name)) {
		Spell_Win_Name = win_pop('');
		if (Spell_Win_Name.focus) { Spell_Win_Name.focus(); }  
		self.document.hidden_form.form_name.value = form_name;
		self.document.hidden_form.field_name.value = field_name;
		self.document.hidden_form.first_time_text.value = textform;
		self.document.hidden_form.submit();
		Work_Form_Name=form_name;
		Work_Field_Name=field_name;
	}
	else {
		if (Spell_Win_Name.focus) { Spell_Win_Name.focus(); }
	}
}
function win_pop(URL){	
	winname=window.open(URL,'WIN','width=600,height=307,left=210,top=210,resizable=yes,scrollbars=yes,status=yes'); 
	return winname;
}
// alert coming soon function
function inProgress(){
	alert("Functionality Coming Soon...");
}
// get rid of overlay after 5 secs if not already gone
var start=new Date();
start=Date.parse(start)/1000;
var counts=5;
function countDownToHideLoader(){
	var now=new Date();
	now=Date.parse(now)/1000;
	var x=parseInt(counts-(now-start),10);
	if(x>0){
		timerID=setTimeout("countDownToHideLoader()", 100)
	} else {
		if(document.getElementById('loading_image').style.display != 'none'){
			document.getElementById('loading_image').style.display='none';
			document.getElementById('mainbody').style.overflow='auto';
			document.getElementById('mainbody').style.height='auto';
		}
	}
}
countDownToHideLoader();
function addDOMLoadEvent(func) {
   if (!window.__load_events) {
	  var init = function () {
		  // quit if this function has already been called
		  if (arguments.callee.done) return;
	  
		  // flag this function so we don't do the same thing twice
		  arguments.callee.done = true;
	  
		  // kill the timer
		  if (window.__load_timer) {
			  clearInterval(window.__load_timer);
			  window.__load_timer = null;
		  }
		  
		  // execute each function in the stack in the order they were added
		  for (var i=0;i < window.__load_events.length;i++) {
			  window.__load_events[i]();
		  }
		  window.__load_events = null;
	  };
   
	  // for Mozilla/Opera9
	  if (document.addEventListener) {
		  document.addEventListener("DOMContentLoaded", init, false);
	  }
	  
	  // for Internet Explorer
	  /*@cc_on @*/
	  /*@if (@_win32)
		  document.write("<scr"+"ipt id=__ie_onload defer src=javascript:void(0)><\/scr"+"ipt>");
		  var script = document.getElementById("__ie_onload");
		  script.onreadystatechange = function() {
			  if (this.readyState == "complete") {
				  init(); // call the onload handler
			  }
		  };
	  /*@end @*/
	  
	  // for Safari
	  if (/WebKit/i.test(navigator.userAgent)) { // sniff
		  window.__load_timer = setInterval(function() {
			  if (/loaded|complete/.test(document.readyState)) {
				  init(); // call the onload handler
			  }
		  }, 10);
	  }
	  
	  // for other browsers
	  window.onload = init;
	  window.__load_events = [];
   }
   window.__load_events.push(func);
}
addDOMLoadEvent(init);

// =====================================================================
// COMMON FUNCTIONS USED ON MOST PAGES
// =====================================================================
function charcount(whichForm,whichInput,whichSpan,newText,maxChar) {
  var whichInputObj = eval('document.'+whichForm+'.'+whichInput);
  var whichSpanObj = document.getElementById(whichSpan);
  var longitud = maxChar - whichInputObj.value.length;
  if(longitud <= 0) {
    longitud=0;
    newText='<span class="disable" style="color:#FF0000"> '+newText+' </span>';
    whichInputObj.value=whichInputObj.value.substr(0,maxChar);
  }
  whichSpanObj.innerHTML = newText.replace("{CHAR}",longitud);
}
function validateSearch(){
	f = document.quickfind;
	if(f.r.value == ''){
		alert('Please select how far you are willing to travel');
		f.r.focus();
		return false;
	}
	else if(f.p.value == ''){
		alert('Please enter your postal code');
		f.p.focus();
		return false;
	}
}
function toggleDisplay(id){
	var displayName = document.getElementById(id);
	if(displayName.style.display == 'none'){
		displayName.style.display = '';
	} else {
		displayName.style.display = 'none';
	}
}
function checkCapsLock(e,element,form) {
	if( !e ) { e = window.event; } if( !e ) { MWJ_say_Caps( false ); return; }
	var theKey = e.which ? e.which : ( e.keyCode ? e.keyCode : ( e.charCode ? e.charCode : 0 ) );
	var theShift = e.shiftKey || ( e.modifiers && ( e.modifiers & 4 ) );
	MWJ_say_Caps( ( theKey > 64 && theKey < 91 && !theShift ) || ( theKey > 96 && theKey < 123 && theShift ),element,form);
}
function MWJ_say_Caps(oC,element,form) {
	if( typeof( capsError ) == 'string' ) { if( oC ) { alert( capsError ); } } else { capsError(oC,element,form); }
}
function capsError(capsEngaged,element,form) {
	var myMsg='Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';
	if( capsEngaged ) {
		//do something to warn the user that caps lock is engaged
		eval("document."+form+"."+element).style.background = 'url(http://www.gigoit.org/images/common/capslockon.gif) right center no-repeat #FFFFFF';
	} else {
		//remove any warnings that caps lock is engaged
		eval("document."+form+"."+element).style.background = '#FFFFFF';
	}
}
// alert netscape 4.79 users
if (navigator.appName == "Netscape" && parseInt(navigator.appVersion) == 4) {
 	alert("** ATTENTION **\n\nThis website uses programming not compatible with Netscape 4.79.");
}
// open new sized window with no address, status or menu bar -----------
function NewWindow(mypage, myname, w, h, scroll) {
	winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',toolbar=no,status=no,resizable=yes,menubar=no,location=no'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}
// onload event handler ------------------------------------------------
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
// onunload event handler ----------------------------------------------
function addUnLoadEvent(func) {
  var oldonunload = window.unonload;
  if (typeof window.unonload != 'function') {
    window.unonload = func;
  } else {
    window.unonload = function() {
      oldonunload();
      func();
    }
  }
}
// set innerHTML of an item by it's ID ---------------------------------
function setInnerHTML(mydiv,mytext){
	document.getElementById(mydiv).innerHTML = mytext;
}
// set and control custom style sheet for user -------------------------
function setActiveStyleSheet(title) {
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if(a.getAttribute("title") == title){ 
				a.disabled = false;
				var domain = document.location.toString().split('http://www.').join('').split('http://').join('').split('/')[0];
				setCookie("theme", title, ( new Date("December 31, 3000 23:59:59") ), "/", domain, null);		
			}
		}
	}
}
function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}
function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}
function initStyleSheetSwitcher(e) {
  var cookie = getCookie("theme");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}
function unInitStyleSheetSwitcher(e) {
	var title = getActiveStyleSheet();
	var domain = document.location.toString().split('http://www.').join('').split('http://').join('').split('/')[0];
	setCookie("theme", title, ( new Date("December 31, 3000 23:59:59") ), "/", domain, null);		
}
// text counter/limiter ------------------------------------------------
function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit){
		field.value = field.value.substring(0, maxlimit);
	} else {
	cntfield.value = maxlimit - field.value.length;
	}
}
// block javascript errors ---------------------------------------------
/* disabled for testing (peter)
function blockError(){return true;}
window.onerror = blockError;
*/
// set field to only accept numbers for zip codes ----------------------
function numbersonly(myfield, e, dec){
	var key;
	var keychar;
	if (window.event){
		key = event.keyCode;
	}
	else if (e) {
		key = e.which;
	}
	else {
		return true;
	}
	keychar = String.fromCharCode(key);

	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)){
		return true;
	}
	else if ((("0123456789").indexOf(keychar) > -1) || (key >= 96 && key <= 105)){
		return true;	
	}
	else {
		s = myfield.value;
		filteredValues = "1234567890";     // Characters stripped out
		var i;
		var returnString = "";
		for (i = 0; i < s.length; i++) {
			var c = s.charAt(i);
			if (filteredValues.indexOf(c) != -1){
				returnString += c;
			}
		}
		myfield.value = returnString;
   		return false;
	}
}
// remove spaces from text string
function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++){
		tstring += splitstring[i];
	}
	if(splitstring.length > 1){
		alert("This field contained spaces which have been removed.");
	}
	return tstring;
}
// set and control cookies ---------------------------------------------
function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+"="+escape( value ) +
    ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}
function deleteCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
/*
// populate zipcode and radius data if exists --------------------------
function populateZipCode(){
	if(getCookie('GigoitPostalCode')){
		var zipCode = getCookie('GigoitPostalCode');
		if(document.getElementById('quickfind')){
			document.quickfind.z.value = zipCode;
		}
		if(document.getElementById('add_offer')){
			document.add_offer.fk_zip.value = zipCode;
		}
		if(document.getElementById('getitem')){
			document.getitem.p.value = zipCode;
		}
	}
	if(getCookie('GigoitRadius')){
		var radius = getCookie('GigoitRadius');
		if(document.getElementById('quickfind')){
			setSelectedValue('quickfind.r',radius);
		}
		if(document.getElementById('getitem')){
			setSelectedValue('getitem.r',radius);
		}
	}
}
*/
function setRadiusCookie(targ,selObj,restore){
	setCookie('GigoitRadius',selObj.options[selObj.selectedIndex].value,360,'','','');
}
function setSelectedValue(selectBoxName,newValue) {
	eval('selectedObject = document.' + selectBoxName + ';');
	for(i = 0; i < selectedObject.length; i++) {
		if(selectedObject[i].value == newValue){
			selectedObject.selectedIndex = i;
		}
	}
}
// -----------------------------------------------------------------------------------
// DREAMWEAVER FUNCTIONS TO SWAP IMAGES
// -----------------------------------------------------------------------------------
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// -----------------------------------------------------------------------------------
// CUSTOM AJAX CLASS
// -----------------------------------------------------------------------------------
function ajaxClass() {
	var xhr = false;

	this.fetchXML= function(url, postdata, callback) {

		if (xhr){ 
			// delete xhr;
			xhr = false;
		}

	    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	        xhr = new XMLHttpRequest();
	    } else if (window.ActiveXObject) { // IE
	        try {
	            xhr = new ActiveXObject("Msxml2.XMLHTTP");
	        } catch (e) {
	            try {
	                xhr = new ActiveXObject("Microsoft.XMLHTTP");
	            } catch (e) {}
	        }
	    }

	    if (!xhr) {
	        //alert('Giving up :( Cannot create an XMLHTTP instance');
	        return false;
	    }

		xhr.onreadystatechange = function() {
			try {
			    if (xhr.readyState == 4) {
			        if (xhr.status == 200) {
			            callback(xhr.responseXML);
			        } else {
			            //alert('There was a problem with the request.');
			        }
			    }
			} catch( e ) {
			    //alert('Error contacting server: ' + e.message);
			}
		}

		xhr.open('POST', url, true);
	    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    xhr.send(postdata);		
	}
}

// -----------------------------------------------------------------------------------
// Validate Postal Codes
// -----------------------------------------------------------------------------------
var doregister=false;
var AJAX = new ajaxClass();

function checkPostalCode(theCountry,thePostalCode,theLanguage,theElement) {
	if (!doregister) {
		AJAX.fetchXML ('includes/validate.postal_code.php', 'c='+theCountry + '&p='+thePostalCode + '&l='+theLanguage + '&e='+theElement, checkPostalCode_Callback);
	}
}

checkPostalCode_Callback = function(xmldata) {
	if (xmldata) {
		var response = '';
		if(xmldata.getElementsByTagName('validationstatus').item(0).firstChild){
			var response = xmldata.getElementsByTagName('validationstatus').item(0).firstChild.data;
			var thisData = response.split('|');
		}
		if (thisData[0] != '') {
			document.getElementById(thisData[1]).innerHTML = thisData[0];
		} else {
			document.getElementById(thisData[1]).innerHTML = '';
		}
	} else {
		alert('Cannot verify username with the server. Please try again.');
	}
}

/*
checkPostalCode_Callback = function(xmldata) {
	
	if (xmldata) {
			
		var response = '';
		var element = '';
		
		if(xmldata.getElementsByTagName('thestatus').item(0).firstChild){
			var response = xmldata.getElementsByTagName('thestatus').item(0).firstChild.data;
			alert('response = '+response);
		}
		
		/*
		if(xmldata.getElementsByTagName('theelement').item(0).firstChild){
			var element = xmldata.getElementsByTagName('theelement').item(0).firstChild.data;
			alert('element = '+element);
		}
		
		
		if (response != '' && element != '') {
			document.getElementById('zip_status').innerHTML = response;
		}
		
	} else {
		alert('Cannot verify postal code with the server. Please try again.');
	}				
}
*/