/*
PShelper.com Commonly Used Javascript functions
For use with ProStores e-commerce platform
v1.0 published 03/19/2009
Derek Decker
*/


/* remove spaces

@words = string input
*/
function trim(words){
     return words.replace(/\s+/g,'');
}


/*convert " and ' symbols to html friendly ascii code

@str = string input
*/
function convertquotes( str ) {
    return (str+'').replace(/([\\"'])/g, "&quot;").replace(/\0/g, "\\0");
}

/* builds and returns a querystring in format parameter=value&parameter2=value2

@postParameters = array of querystring parameters
@postParameterValues = array of associated parameter values
*/
function buildQuerystring(postParameters,postParameterValues){	
	  var poststr = '';
	  for(var i=0;i<postParameters.length;i++){
		poststr += escape(postParameters[i].replace(/[\$\.]/g,'')) + '=' + escape(postParameterValues[i]);
			if((postParameters.length-1)!=i){
				poststr += '&';
				}
		}
		return poststr;
}	

/* print a hidden image (used to post information to an off-domain external script)

@baseSrc = rootUrl of image
@postformid = form to gather variables from
@spantoprintimage = id attribute value of html tag to print the image in
*/
function printHiddenImage(baseSrc,postformid,spantoprintimage){
	var postedParameters=Array();
	var postedParameterValues=Array();
	var postedVars=false;
	var postform = document.getElementById(postformid);
	
	for(var i=0;i<postform.elements.length;i++){
		postedParameters[i]=postform.elements[i].name;
		postedParameterValues[i]=postform.elements[i].value;
	}
	postedVars = buildQuerystring(postedParameters,postedParameterValues);
    document.getElementById(spantoprintimage).innerHTML = '<img src="'+baseSrc+'?'+postedVars+'" style="display:none;"/>';
	//document.getElementById(spantoprintimage).innerHTML += baseSrc+'?'+postedVars;
	return true;
}


/* disable the confirm button on invoice confirm page

@disableIt = boolean true false
@changeText = string change value to string
//@additionalFunctionsToCall [array] = array of additional functions to call upon click
*/
function modifyInvoiceButtonOnClick(disableIt,changeText){
   document.invoiceconfirm.elements[2].disabled=disableIt;
   document.invoiceconfirm.elements[2].value=changeText;
   return true;
}


/* for use with the terms agreement product
  disable/enables the checkout buttons on the modified Checkout template
  called as such  onClick="enableCheckoutButtons(Array('','',''),'')"
  
@idsOfButtons [array] = ids of the buttons to enable / disable based on the status of checkboxId
@checkboxId = the id of the checkbox which controls the buttons 
*/
function enableCheckoutButtons(idsOfButtons,checkboxId){
 if(document.getElementById(checkboxId).checked){
	for(var i in idsOfButtons)
  		if(document.getElementById(idsOfButtons[i])) document.getElementById(idsOfButtons[i]).disabled=false;
 }else{
	for(var i in idsOfButtons)
  		if(document.getElementById(idsOfButtons[i])) document.getElementById(idsOfButtons[i]).disabled=true;
 }
}

/* vanquish a cookie
  
@name = name of cookie to slay
*/
function killCookie(name){    
   document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT; "; //kill the cookie
}

/* resurrect a cookie

@name = name of cookie to summon
@value = value of cookie being conjured
*/
function setCookie(name, value){
	killCookie();
	var path = '/';
	var today = new Date();
	var expires = new Date();
	expires.setTime(today.getTime() + 1000*60*60*24*30); // expires in a month
	document.cookie = name + "=" + value + "; expires=" + expires.toGMTString() + "; path="+path+";"; //set it anew
	return true;
}

/* access a cookies' value

@n = name of cookie being accessed
*/
function readCookie(n) {
	var cookiecontent = new String();
	if(document.cookie.length > 0) {
		var cookiename = n+ '=';
		var cookiebegin = document.cookie.indexOf(cookiename);
		var cookieend = 0;
		if(cookiebegin > -1) {
			cookiebegin += cookiename.length;
			cookieend = document.cookie.indexOf(";",cookiebegin);
			if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
			cookiecontent = document.cookie.substring(cookiebegin,cookieend);
			}
		}else{
				 return false;
		}
	return cookiecontent;
} 

/* check for key being pressed onKeyPress="checkKeyPressed(event)"
return true if matched

@e = event
@code = numerical code to check for match (13 being enter)
*/
function checkKeyPressed(e,code){ //e is event object passed from function invocation
	var characterCode; //literal character code will be stored in this variable
	
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	}else{
		e = event;
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}
	
	if(characterCode == code){ //if generated character code is equal to ascii 13 (if enter key)
		return true;
	}else{
		return false;
	}
}


/* return the y px coordinate of the browsers current viewable area */
function getBrowserYPxLocation(){
	if (window.innerHeight) return window.pageYOffset+window.innerHeight;
	else if (document.documentElement.clientHeight){ return document.documentElement.scrollTop+document.documentElement.clientHeight; }
	return document.body.scrollTop+document.getElementsByTagName('body')[0].clientHeight;
}

/* PROCESSES THE FLOATING CART'S LOCATION FOR IE  */
if(document.getElementById('floatCartOverlayContainer')){ //if using the floatcart
	window.onscroll=function(){ //on window scroll move the floating cart
		document.getElementById('floatCartOverlayContainer').style.top=getBrowserYPxLocation()+'px';
	}
}


/* primary ajax function */
function makePOSTRequest(url, parameters, spanIdentity) {

       function alertContents(spanIdentity) {
          if (http_request.readyState == 4) {
             if (http_request.status == 200) {
                document.getElementById(spanIdentity).innerHTML = 'Yes'; 
             } else {
                alert('There was a problem with the request.');
             }
          }
       }


  var http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
     http_request = new XMLHttpRequest();
     if (http_request.overrideMimeType) {
        // set type accordingly to anticipated content type
        //http_request.overrideMimeType('text/xml');
        http_request.overrideMimeType('text/html');
     }
  } else if (window.ActiveXObject) { // IE
     try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
        try {
           http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
     }
  }
  if (!http_request) {
     alert('Cannot create XMLHTTP instance');
     return false;
  }
  http_request.open('GET', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
  http_request.onreadystatechange = function(){ alertContents(spanIdentity) };  
}

/* build a div popup tooltip from any element

@fromElement = typically (this), where the tooltip is being linked from
@toolTipInnerHtml = the text inside the tooltip
@textStyle = css style attribute list
@internalStyle = the external wrapper style attribute list
*/
function buildToolTip(fromElement,toolTipInnerHtml,textStyle,internalStyle){
	//set the toolTip wrapping div
		var baseStyle = 'display:inline-block;position:relative;';
		internalHtml = document.createTextNode(toolTipInnerHtml);
		fromElement.style.cssText=baseStyle;
		
	//set the toolTip internal div
		tooltipInternal = document.createElement('div');
		internalStyle += 'display:block;position:absolute;top:-16px;left:100%;padding:3px;z-index:990;';
		tooltipInternal.style.cssText=internalStyle;
		
	//set the toolTip internal span font formatting
		tooltipInternalSpan = document.createElement('span');
		tooltipInternalSpan.style.cssText=textStyle;		
		
		tooltipInternalSpan.appendChild(internalHtml);
		tooltipInternal.appendChild(tooltipInternalSpan);
		fromElement.appendChild(tooltipInternal);
		
		fromElement.onmouseout = function(){ fromElement.removeChild(tooltipInternal); };
}
