//
var tipsDiv;
function showedit() {
	var divBlock = getId("editBlock");
	divBlock.style.visibility = "visible";
	showPageDimmer();
}
function showPageDimmer() {
    //var scrollComp = document.getElementsByTagName("html").item(0).scrollTop;
	var dimBlock = getId("pageDimmer");
	dimBlock.style.visibility = "visible";
	//dimBlock.style.height = (1024 + scrollComp) + "px";
	dimBlock.style.height = screen.height + "px";
}
//trim spaces from string
function trim(stringValue)
{
  return stringValue.replace(/(^\s*|\s*$)/, "");
} 
//clean strings for xml
function xmlClean(stringValue)
{
    stringValue = stringValue.replace(/</gi, "$lt");
    stringValue = stringValue.replace(/>/gi, "$gt");
    stringValue = stringValue.replace(/&/gi, "$am");    
    return stringValue;
}
QueryStrings = new Array();
// Get all query string prams
CollectQuerystrings();
function CollectQuerystrings()
{
	var queryString = window.location.href.substring((window.location.href.indexOf('?') + 1));
	var array1 = queryString.split('&'); // Each array element is in format "fieldname=value"
	for(var i = 0; i < array1.length; i++){
		var tempArray = array1[i].split('='); // Separate fieldname and value
		eval("QueryStrings[\"" + tempArray[0] + "\"] = \"" + tempArray[1] + "\"");
	}
}

function updateTips(t) {
    tipsDiv
		.text(t)
		.addClass("ui-state-highlight");
    setTimeout(function () {
        tipsDiv.removeClass("ui-state-highlight", 1500);
    }, 500);
}

function checkLength(o, n, min, max) {
    if (o.val().length > max || o.val().length < min) {
        o.addClass("ui-state-error");
        updateTips("Length of " + n + " must be between " +
					min + " and " + max + " characters. (Length of your " + n + ": " + o.val().length + " chars.)");
        return false;
    } else {
        return true;
    }
}

function checkRegexp(o, regexp, n) {
    if (!(regexp.test(o.val()))) {
        o.addClass("ui-state-error");
        updateTips(n);
        return false;
    } else {
        return true;
    }
}

/** checks if the passed parameter is a sku. 
    if its a sku, it fires pickSku(sku);
    used to process site search key words
    uses connection.js and checkIFsku.asp
 */
function processQ(sku)
{
    var d = new Date();  
    data = "sku="+sku;       
    url = "/utils/checkifsku/?"+ data;       
    url = url + "&t=" + d.getTime();   
    isSKU = getDataSync(url); 
    if(isSKU == "1")
        pickSku(sku);
}
 


/**
 * Places the div at the center of the viewport (770 x 600px).
 */ 
function centerDiv(div)
{
  var div = getId(div);
 	var windowWidth, windowHeight;
	var arrayWinSize = getWinSize();
	//width is set to 770px by wrapper div
    var width = 770;
    var height = 600;//arrayWinSize[1];
  
  var divWidth = div.offsetWidth;
  var divHeight = div.offsetHeight;

  var offsetX = (divWidth/2);
  var offsetY = (divHeight/2);
  
  var left = (width / 2) - offsetX;
  var top = (height / 2) - offsetY;

  div.style.left = left + "px";
  div.style.top = top + "px";
}
 
/**
 * set overlay (page dimmer) size.
 */ 
function resizeOverlay(div)
{
  var div = getId(div);
  var arrayPageSize = getPageSize();  
  div.style.width = arrayPageSize[0] + "px";
  div.style.height = arrayPageSize[1] + "px";
}


/**
 *	Help functions
 */
function goto(url)
{
	window.location = url;
}
//
// returns the file name out of the full url
//
function getFileName(fullfilepath) {
    if (fullfilepath) {
        var startIndex = (fullfilepath.indexOf('\\') >= 0 ? fullfilepath.lastIndexOf('\\') : fullfilepath.lastIndexOf('/'));
        var filename = fullfilepath.substring(startIndex);
        if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
            filename = filename.substring(1);
        }
        return (filename);
    }

}
//
//  getPageSize
//
function getPageSize() 
{
     var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	var arrayWinSize = getWinSize();
    var windowWidth = arrayWinSize[0];
    var windowHeight = arrayWinSize[1];
	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

function getWinSize() {

    var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	

    return [windowWidth,windowHeight];
}
 
function getId(id) {
  return document.getElementById(id);
}

function dimPage()
{
    showdiv("pageDimmer");
    resizeOverlay("pageDimmer");
}

function waitUntil(cond, ThenExecuteFunc, reCheckTime){
    if(eval(cond))
        waitTill=setTimeout("waitUntil("+cond+", "+ThenExecuteFunc+", "+reCheckTime+")", reCheckTime);
    else
        eval(ThenExecuteFunc);
} 

function getNames(name) {
  return document.getElementsByName(name);
}

function getRandomInt() {
  return parseInt(Math.random() * 10000000);
}

function showdiv(div){
    if(getId(div))
    {
	if(getId(div).style.display != "")
        getId(div).style.display = "";
        
    if(getId(div).style.visibility != "visible")
	    getId(div).style.visibility = "visible";
	}
}
function hidediv(div){
    if(getId(div))
    {
    if(getId(div).style.display != "none")
	    getId(div).style.display = "none";
	    
	if(getId(div).style.visibility != "hidden")
	    getId(div).style.visibility = "hidden";
	}
}

function showhidediv(div){
	if(getId(div).style.display == "none")
        getId(div).style.display = "";
    else
	    getId(div).style.display = "none";
    }

//string1.split("(")[0].replace(/\s+$/,"") <-- Removes everthing after "("

function addOption(selectbox,text,value)
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options[selectbox.length] = optn;
    //selectbox.options.add(optn); //does not work with firefox

}

function checknumber(testData){
   var anum=/(^\d+$)|(^\d+\.\d+$)/
    if (anum.test(testData))
           return true;
    else
           return false;
}

function checkEmail(theEmailAddBox)
{
    theEmailAdd = getId(theEmailAddBox).value;
    emailAddLen = theEmailAdd.length;
    MySplitEmailAdd = theEmailAdd.split("@");
    MySplitEmailAdd2 = theEmailAdd.split(".");
    locAT =theEmailAdd.indexOf("@")  
    getId(theEmailAddBox).focus();      

  
    if((MySplitEmailAdd[0] == null) || (MySplitEmailAdd[0] == "") ||
	        (MySplitEmailAdd[1] == null) || (MySplitEmailAdd[1] == ""))
	        {
	            alert("Please enter a valid email address");		            
		        return false;
	        }		
	else if((MySplitEmailAdd2[0] == null) || (MySplitEmailAdd2[0] == "") ||
	        (MySplitEmailAdd2[1] == null) || (MySplitEmailAdd2[1] == ""))
	        {
	            alert("Please enter a valid email address");
		        return false;
	        }
	else if ((theEmailAdd.charAt(emailAddLen-1) == "@") 
	        || (theEmailAdd.charAt(emailAddLen-1) == ".")
	        || (theEmailAdd.substring(locAT-1,locAT)==".")
	        || (theEmailAdd.substring(locAT+1,locAT+2)=="."))
	        {
	            alert("Please enter a valid email address");
		        return false;
	        }
	else if (theEmailAdd.indexOf(" ")!=-1)
	        {
	            alert("Please enter a valid email address");
	            return false;
	        }
	else
	    return true;
		    
}

function checkName(theNameBox)
{  
  theName = getId(theNameBox).value;
  if ((theName.length <= 0) ||(theName.length == null))
    {
        alert("Please enter a valid recipient name");
        getId(theNameBox).focus(); 
        return false;
    }
 return true;   
}      

//checks if the image exists on the server using AJAX, replace if missing with given image
function replaceMissingImages(ImgSrc, ReplImgSRC){
   if (FileStatus(ImgSrc.src) == "404")
             ImgSrc.src = ReplImgSRC;
}

//replaces broken images in a given div with a given image. POST LOAD
function ReplaceBrokenImages(div, imagesrc)
{
	div = getId(div);
	imgs = div.getElementsByTagName("img");
	for (var i = 0; i < imgs.length; i++) {
   		if (FileStatus(imgs[i].src) == "404")
             imgs[i].src = imagesrc; 
     }
}


/**
Javascript Eval 

**/
function sethtml(div,content) {
         var search = content;
         var script;
         
         var is_singleq = 0; var singleq = "'";
         var is_doubleq = 0; var doubleq = '"';
         var is_escaped = 0; var escap = "\\";
         var layer = 0;
               
         while( script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/)) {
            search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length);
            if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break;
            block = search.substr(0, search.indexOf(RegExp.$1));
            search = search.substring(block.length + RegExp.$1.length);
            
            while(func = block.match(/(function(.+?)\((.*?)\)\s*\{)/)) {
               eval(block.substr(0,block.indexOf(RegExp.$1)));
               // for evaluating non functions
               
               block = block.substr(block.indexOf(RegExp.$1) + RegExp.$1.length);
               name = RegExp.$2;
               param = RegExp.$3;
               
               is_singleq = 0;
               is_doubleq = 0;
               is_escaped = 0;
               layer = 0;
               
               
               for(i=0;i<block.length;i++) {
                  c = block.substr(i,1);
                  
                  if ((is_singleq || is_doubleq) && is_escaped) {
                     is_escaped = 0;
                  } else if (!is_doubleq && (c==singleq)) {
                     is_singleq = !is_singleq;
                  } else if (!is_singleq && (c==doubleq)) {
                     is_doubleq = !is_doubleq;
                  } else if ((is_singleq || is_doubleq) && (c==escap)) {
                     is_escaped = 1;
                  } else if ( c=="{") {
                     layer++;
                  } else if ( c=="}") {
                     if ( layer==0 ) {
                        break;
                     }
                     layer--;
                  }
               }
               
               code = block.substr(0,i-1);
               block = block.substr(i +1);
               
               code = code.replace(/\n/g, '\\n');
               code = code.replace(/\r/g, '\\r');
               code = code.replace(/'/g,"\\'");
               
               eval(name + " = new Function('"+param+"','"+code+"');");
            }
            eval(block); // for evaluating non functions
         }
         document.getElementById(div).innerHTML=content;
      } 
