//-----( Global functions )------------------------------------
var hideBgHandle;


Ajax.Responders.register({
    onException:function(o_Requester, o_Exception, o_JSON){
      if (Ajax.getTransport()== false ){
        var errorMsg ='Unable to get an AJAX transport.  ' 
                      + '\nIf using MSIE 6.x please ensure ActiveX controls marked safe for scripting are enabled.';
        alert(errorMsg);
      }
      //console.info(o_Requester, o_Exception, o_JSON);
    }
  }
);


function ajaxExceptionHandler(transport, e){
  try {
    if ( Ajax.getTransport()== false ) {
      //let the global handler deal with this.
      //todo need a better way to interact with global handler?
      return;
    }
  } catch(e) {
  }
  
  try {
    var hdr = 'Ajax Handler\n' 
            + 'An exception occurred. Please provide this information to support.\n\n'
    var transportPart = 'State: ' + transport.readyState + "\n"
                      + 'Status: ' + transport.status + "\n\n";
    var exception = 'Exception Info\n     ' + e + '\n\n';
    try {
      var parts = 
          'Description:         ' + e.description + '\n' 
        + 'FileName:            ' + e.fileName + '\n' 
        + 'LineNumber:          ' + e.lineNumber + '\n' 
        + 'Message:             ' + e.message + '\n'
        + 'Name:                ' + e.name + '\n'
        + 'Number:              ' + e.number + '\n'
        + 'Prototype:           ' + e.prototype + '\n'
        + 'Stack:               ' + e.stack + '\n';
        
      var responseText = transport.responseText;      
    }  catch(e) {
    }
  
    var message = hdr + transportPart + exception + parts + '\n\n\n' + responseText;
    alert(message);
  } catch (e) {
  }
  
  /*
  alert('Ajax Handler\n'
        + 'An exception occurred. Please provide this information to sgaustad@fastenal.com\n\n' 
        + 'Status:' + transport.status + '\n\n'
        + 'Exception Info\n     ' + e + '\n\n'
        );
*/        
  //console.info('', e, '');
}


// go to a location
function gotoUrl(url) {
	window.location.href = url;
}

// open a popup window with params
function popupUrl(url, name, features) {
	var newWindow = window.open(url, name, features);
	newWindow.focus();
}

// element toggler
function toggle(id) {
	var element = $(id);
	if (element.style.display == "block") {
		element.style.display = "none";
	} else {
		element.style.display = "block";
	}
} // toggle

// toggle the visibility property -- combine with toggle function
function toggleVisibility(id) {
	var el = $(id);
	if (el.style.visibility == "visible" 
	|| el.style.visibility == "") {
		el.style.visibility = "hidden";
	} else {
		el.style.visibility = "visible";
	}
	
}

// toggle the display property -- combine with toggle function
function toggleDisplay(id) {
	var el = $(id);
	if (el.style.display == "block" 
	|| el.style.display == "") {
		el.style.display = "none";
	} else {
		el.style.display = "block";
	}
}

// encode urls
function urlEncode(str){
	str = escape(str);
	str = str.replace(new RegExp('\\+','g'),'%2B');
	return str.replace(new RegExp('%20','g'),'+');
} // urlEncode

// decode urls
function urlDecode(str){
	str = str.replace(new RegExp('\\+','g'),' ');
	return unescape(str);
} // urlDecode

// get the left n characters from a string
function left(str, n){
  if (n <= 0) {
	  return "";
	} else if (n > String(str).length) {
    return str;
	} else {
	  return String(str).substring(0, n);
  }
} // left

// get the right n characters from a string
function right(str, n){
  if (n <= 0) { 
    return "";
  } else if (n > String(str).length) {
    return str;
  } else {
    var iLen = String(str).length;
    return String(str).substring(iLen, iLen - n);
  }
} // right

// trim the leading and trailing spaces from a string
function trim(str) {
	str = str.replace(/^\s*|\s*$/g,"");
	return str;
} // trim

// looks in array for a specified value
function inArray(array, value) {
	for (var i=0; i<array.length; i++) {
		if (array[i] == value) {
			return true;
		}
	}
	return false;
}

// remove an element
function removeElement(el) {       
	if (el.parentNode) {
		el.parentNode.removeChild(el);
	}
} // removeElement

// insert content after an existing element
function insertAfter(newElement, existingElement) {
	var parentElement = existingElement.parentNode;
	if (parentElement.lastChild == existingElement) {
		return parentElement.appendChild(newElement);
	} else {
		return parentElement.insertBefore(newElement, existingElement.nextSibling);
	}
} // insertAfter

// this function is needed to work around 
// a bug in IE related to element attributes
function hasClass(obj) {
	var result = false;
	var classAttr = obj.getAttribute("class");
	if (classAttr != null) {
		result = classAttr.value;
	}
	return result;
}



// determine if the string is alpha numeric only
function isAlphaNumeric(string) {
  var matcher = string.match(/^\w+$/);
  if (matcher != null) { return true; } else { return false; }
} // isAlphaNumeric

// determines if the year is a leap year
function isLeapYear(year) {
  if (year%4 == 0 && year%100 != 0 || year%400 == 0) { return true; } else { return false; }
} // isLeapYear

// enable/disable elements
function enable(el) { $(el.id).disabled = false; }
function disable(el) { $(el.id).disabled = true; }
function enableThis(el) { el.disabled = false; }
function disableThis(el) { el.disabled = true; }

/* deprecated
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}

function preloadImages(imageArray) {
	var tempImages = new Array();
	for (var i=0; i<imageArray.length; i++) {
		tempImages[i] = new Image();
		tempImages[i].src = imageArray[i];
	}
}

*/
//-----( END )-------------------------------------------------


//-----( @Prototypes )-----------------------------------------
// Summary: prototype implementations of existing javascript functions

// prototype implementation of the trim function
String.prototype.trim = function() {
  var x = this;
  return trim(x);
}

// prototype implementation of the left function
String.prototype.left = function(n) {
	var x = this;
	return left(x, n);
};

// prototype implementation of the right function
String.prototype.right = function(n) {
	var x = this;
	return right(x, n);
};

Array.prototype.inArray = function(n) {
	var x = this;
	return inArray(x, n);
};

Array.prototype.shuffle = function() {
  var len = this.length;
  var rand, temp, i;
  for (i = 0; i < len; i++){
    rand = Math.floor(Math.random() * len);
    temp = this[i];
    this[i] = this[rand];
    this[rand] = temp;
  }
};

Array.prototype.copy = function() {
  return this.slice();
};

Array.prototype.indexOf = function(value) {
  var i = 0;
  while(i < this.length){
    if(this[i] == value) return i;
    i++;
  }
  return -1;
}

Array.prototype.lastIndexOf = function(value) {
  var i = this.length;
  while (--i){
    if (this[i] == value) {
			return i;
		}
  }
  return -1;
}
//-----( END )-------------------------------------------------


// determines if the link has a # in it, then highlights the area
function doHighlight(href) {
  if (href.indexOf('#') != -1) {
    var pos = href.indexOf('#');
    pos = href.length - pos;
    href = right(href, pos -1);
    new Effect.Highlight(href);
  }
}


// sets the value of a select list
function setSelected(el, value) {
  var listObj = $(el);
  var length = listObj.length;
  for (var i=0; i<length; i++) {
    if (listObj.options[i].text == value
    || listObj.options[i].value == value) {
      listObj.options[i].selected = true;
    }
  }
} // setSelected


// show MSDS popup window
function viewMsds(url) {
	var name = "fcom_msds_popup";
	var features = "width=785,height=589,";
	features += "directories=no,location=yes,menubar=yes,";
  features += "resizable=yes,scrollbars=yes,status=yes,toolbar=yes";
	popupUrl(url, name, features);
} // viewMsds


// IE6 only, all other browsers will ignore.
// This is used to imitate the css :hover 
// use: applyHover($("NAMEOFCONTAINER"), 'TYPEOFTAG');
// css mod: #NAMEOFCONTAINER TYPEOFTAG:hover {} -> #NAMEOFCONTAINER TYPEOFTAG:hover, #NAMEOFCONTAINER TYPEOFTAG.hover {} 
function applyHover(container, tagType){
  if (document.all&&container.getElementsByTagName&&!window.XMLHttpRequest) {
    var elementsToHover = container.getElementsByTagName(tagType);
    for (i=0; i<elementsToHover.length; i++) {
      node = elementsToHover[i];
      node.onmouseover=function() {
        this.className+=" hover";
      }
      node.onmouseout=function() {
        this.className=this.className.replace(" hover", "");
      }
    }
  }
}// applyHover


function checkTimeOut(errorHTML, redirect) {
	errorHTML = errorHTML.stripTags();
	errorHTML = errorHTML.strip();
	var timeout = false;
	errorHTML.scan(/\w+/, function(match){ if(match[0] == 'timeout') timeout = true; });
	if (timeout == true){
		var sURL = redirect; //'../accounts.ex';
		window.location.href = sURL;
		return false;
	}
	return true;
} //end checkTimeOut

function checkResponseForErrors(transport) {
	var status = true;
	
	try{
    var urlLocation = transport.getResponseHeader("Content-Location");
    //alert(urlLocation);
    if (urlLocation.indexOf('login') > 0){
      //window.location.href = '/web/products.ex';
      var pageFrom = "?pageFrom=" + $('pageFrom').value;
      var sURL = '/web/login/signin.ex';
      window.location.href = sURL + pageFrom;
      status = false;
    }
  }catch (e){
    
  }finally{
    return status;
  }
  
  
	
} //end checkResponseForErrors


function handleErrorForwarding(urlLocation){
	
	  if (urlLocation.indexOf('products') > 0){
		window.location.href = '/web/products.ex';
	  }
	
	
	  if (urlLocation.indexOf('pohistory') > 0){
		window.location.href = '/web/history.ex';
	  }
		
		
	  if (urlLocation.indexOf('login') > 0){
		var pageFrom = "?pageFrom=" + $('pageFrom').value;
		var sURL = '/web/login/signin.ex';
		window.location.href = sURL + pageFrom;
	  }
	
}

  function showPopInBackground(){
    try{
        if(hideBgHandle){
          //clear setInterval for hiding bg see hidePopInBackground()
          clearInterval(hideBgHandle);
          hideBGHanle=null;
        }//end if
    }catch(e){
    }

  $("shadeOutBackground").style.visibility = 'visible';
  $("loadingBar").style.display = 'block';
  //when the background is made visible, IE6 needs this to make it fill up the whole page
  if (!window.XMLHttpRequest) {//IE6 and other older browsers only
    var wrapHeight = $("wrap").getHeight() + 'px';
    $("shadeOutBackground").style.height = wrapHeight;
    $("loadingBar").style.height = wrapHeight;
  }
} //end showPopInBackground


function hidePopInBackground() {
  //alert('hidePopInBackground begin');
  //$("shadeOutBackground").style.visibility = 'hidden';
  //$("loadingBar").style.display = 'none';
  //alert('hidePopInBackground end');
  
  //ensure background is hidden by looping until it is.
  hideBgHandle = setInterval (hidePopInBackgroundInterval,500);
}
//run repeatedly until the background is hidden
//once hidden exectute clearInterval
function hidePopInBackgroundInterval(){
  $("shadeOutBackground").style.visibility = 'hidden';
  $("loadingBar").style.display = 'none';
  if(isBackgroundHidden() ){
    clearInterval(hideBgHandle);
    hideBgHandle=null;
  };
}
//returns true if pop in bg is hidden
function isBackgroundHidden(){
  if ($("shadeOutBackground").style.visibility == 'hidden'
      && $("loadingBar").style.display == 'none'){
      return true;
  }else{
    return false;
  }
}

function openPopIn(section, clickedElement) {
  showPopInBackground();
  $(section + "PopIn").centerOn(clickedElement);
  Effect.Appear(section + "PopIn", {duration:.5});
  Effect.Fade("loadingBar", {duration:.5});
  $("display" + section + "Errors").innerHTML = "";
  if ($(section + "Errors") != null) {
    $(section + "Errors").innerHTML = ""; 
  }
}


function popupEdit(section) {
  openPopIn(section, $(section));
}


function sendSavePopIn(section, url, formSubmitted) {
  disable($('submit' + section));
  if ( formSubmitted == null ) {
    formSubmitted = $("form" + section);
  }
  
  if ( $(section + "PopIn") != null ) {
    Effect.Fade(section + "PopIn", {duration:.2});
  }
  
  Effect.Appear("loadingBar", {duration:.2});
  $('temp' + section).innerHTML = '';
  new Ajax.Updater( {success:'temp' + section}
                  , url
                  , { 
                      asynchronous:true
                    , parameters:Form.serialize(formSubmitted)
                    , onComplete:function(transport){savePopIn(transport, section);}
                    , onException:function(transport,e ){failedSendSavePopIn(transport, section,e);} 
                    
                    } );
} //end sendSavePopIn


function savePopIn(transport, section) {
  //alert('save popIn: ' + section);
	var response = transport.responseText;
	//alert("response: " + response);
  //alert('savePopin: ' + transport.status);
  
  if (transport.status>1000){
    //alert('savePopin abort, crazy status code: ' + transport.status);
    failedPopIn(transport, section, 'Status code: ' + transport.status);
    return;
  }
  
  try{
  if ($('temp' + section).innerHTML != null && $('temp' + section).innerHTML != '') {
		var errorHTML = 'none';
		if ($(section + "Errors") != null) { 
			errorHTML = $(section + "Errors").innerHTML; 
		}
		errorHTML = errorHTML.stripTags();
		errorHTML = errorHTML.strip();
    //alert('check transport for errors');
		if (checkResponseForErrors(transport)) {
			if (errorHTML == "none") {
				$(section).innerHTML = $('temp' + section).innerHTML;
				Effect.Fade(section + "PopIn", {duration:.5});
				Effect.Fade("loadingBar", {duration:.5});
				setTimeout("popInCleanup('" + section + "', true)", 500);
			} else {
				Effect.Appear(section + "PopIn", {duration:.5});
				Effect.Fade("loadingBar", {duration:.5});
				$("display" + section + "Errors").innerHTML = $(section + "Errors").innerHTML;
				$("display" + section + "Errors").style.display = "block";
			}
			$(section + "Errors").innerHTML = "";
			$('temp' + section).innerHTML = "";
		}
		enable($('submit' + section));
	} else { //something failed in the ajax call, clean up the code
		//alert("failedPopIn was called from savePopIn."+ "\n response: " + response); //Error tracking
    failedPopIn(transport, section);
	}
  }catch(e){
    //throw e;
  }finally{
    //alert('finally');
  }
} //end savePopIn

function failedSendSavePopIn(transport, section,e) {
  failedPopIn(transport, section,e);
  if(e){
    //setTimeout("popInCleanup('" + section + "', true)", 500);
    hidePopInBackground();
  }
}


function failedPopIn(transport, section,e) {
  //alert('failed popin');
  enable($('submit' + section));
	ajaxExceptionHandler(transport, e);
  popInCleanup( 'failed', false );
  
  
  
  
  //throw e;
  //todo, reset form?
}


function cancelPopIn(section) {
  Effect.Fade(section + "PopIn", {duration:.5});
  $("shadeOutBackground").style.visibility = 'hidden';

  $("form" + section).reset();

  setTimeout("popInCleanup('" + section + "', false)", 500);
}


function resetDefaultValues(form) {
  var iMaxElements = form.elements.length;
  for (var i = 0; i < iMaxElements; i++) {
    myType = form.elements[i].type;
    if (myType == 'checkbox' || myType == 'radio') {
      form.elements[i].defaultChecked = form.elements[i].checked;
    }
    
    if (myType == 'hidden' || myType == 'password' || myType == 'text' || myType == 'textarea') {
      form.elements[i].defaultValue = form.elements[i].value;
    }
    
    if (myType == 'select-one' || myType == 'select-multiple') {
      var iMaxElementsOptions = form.elements[i].options.length;
      for (var j = 0; j < iMaxElementsOptions; j++) {
        form.elements[i].options[j].defaultSelected = form.elements[i].options[j].selected;
      }
    }
  }
} //end resetDefaultValues


function copyAllValues(className, newValue) {
  if(confirm('Are you sure you want to update all values to: ' + newValue + '?')){
		var classInputs = getElementsByClassName(className, "input");
		classInputs.each(function(classInput) {
      classInput.value = newValue;
		});
  }
}


//Error tracking
function exceptionInSendSavePopIn() {
  alert("There was an exception in sendSavePopIn.")
}