/*
  $Id: general.js,v 1.3 2003/02/10 22:30:55 hpdl Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

function SetFocus(TargetFormName) {
  var target = 0;
  if (TargetFormName != "") {
    for (i=0; i<document.forms.length; i++) {
      if (document.forms[i].name == TargetFormName) {
        target = i;
        break;
      }
    }
  }

  var TargetForm = document.forms[target];
    
  for (i=0; i<TargetForm.length; i++) {
    if ( (TargetForm.elements[i].type != "image") && (TargetForm.elements[i].type != "hidden") && (TargetForm.elements[i].type != "reset") && (TargetForm.elements[i].type != "submit") ) {
      TargetForm.elements[i].focus();

      if ( (TargetForm.elements[i].type == "text") || (TargetForm.elements[i].type == "password") ) {
        TargetForm.elements[i].select();
      }

      break;
    }
  }
}

function RemoveFormatString(TargetElement, FormatString) {
  if (TargetElement.value == FormatString) {
    TargetElement.value = "";
  }

  TargetElement.select();
}

function CheckDateRange(from, to) {
  if (Date.parse(from.value) <= Date.parse(to.value)) {
    return true;
  } else {
    return false;
  }
}

function IsValidDate(DateToCheck, FormatString) {
  var strDateToCheck;
  var strDateToCheckArray;
  var strFormatArray;
  var strFormatString;
  var strDay;
  var strMonth;
  var strYear;
  var intday;
  var intMonth;
  var intYear;
  var intDateSeparatorIdx = -1;
  var intFormatSeparatorIdx = -1;
  var strSeparatorArray = new Array("-"," ","/",".");
  var strMonthArray = new Array("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec");
  var intDaysArray = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

  strDateToCheck = DateToCheck.toLowerCase();
  strFormatString = FormatString.toLowerCase();
  
  if (strDateToCheck.length != strFormatString.length) {
    return false;
  }

  for (i=0; i<strSeparatorArray.length; i++) {
    if (strFormatString.indexOf(strSeparatorArray[i]) != -1) {
      intFormatSeparatorIdx = i;
      break;
    }
  }

  for (i=0; i<strSeparatorArray.length; i++) {
    if (strDateToCheck.indexOf(strSeparatorArray[i]) != -1) {
      intDateSeparatorIdx = i;
      break;
    }
  }

  if (intDateSeparatorIdx != intFormatSeparatorIdx) {
    return false;
  }

  if (intDateSeparatorIdx != -1) {
    strFormatArray = strFormatString.split(strSeparatorArray[intFormatSeparatorIdx]);
    if (strFormatArray.length != 3) {
      return false;
    }

    strDateToCheckArray = strDateToCheck.split(strSeparatorArray[intDateSeparatorIdx]);
    if (strDateToCheckArray.length != 3) {
      return false;
    }

    for (i=0; i<strFormatArray.length; i++) {
      if (strFormatArray[i] == 'mm' || strFormatArray[i] == 'mmm') {
        strMonth = strDateToCheckArray[i];
      }

      if (strFormatArray[i] == 'dd') {
        strDay = strDateToCheckArray[i];
      }

      if (strFormatArray[i] == 'yyyy') {
        strYear = strDateToCheckArray[i];
      }
    }
  } else {
    if (FormatString.length > 7) {
      if (strFormatString.indexOf('mmm') == -1) {
        strMonth = strDateToCheck.substring(strFormatString.indexOf('mm'), 2);
      } else {
        strMonth = strDateToCheck.substring(strFormatString.indexOf('mmm'), 3);
      }

      strDay = strDateToCheck.substring(strFormatString.indexOf('dd'), 2);
      strYear = strDateToCheck.substring(strFormatString.indexOf('yyyy'), 2);
    } else {
      return false;
    }
  }

  if (strYear.length != 4) {
    return false;
  }

  intday = parseInt(strDay, 10);
  if (isNaN(intday)) {
    return false;
  }
  if (intday < 1) {
    return false;
  }

  intMonth = parseInt(strMonth, 10);
  if (isNaN(intMonth)) {
    for (i=0; i<strMonthArray.length; i++) {
      if (strMonth == strMonthArray[i]) {
        intMonth = i+1;
        break;
      }
    }
    if (isNaN(intMonth)) {
      return false;
    }
  }
  if (intMonth > 12 || intMonth < 1) {
    return false;
  }

  intYear = parseInt(strYear, 10);
  if (isNaN(intYear)) {
    return false;
  }
  if (IsLeapYear(intYear) == true) {
    intDaysArray[1] = 29;
  }

  if (intday > intDaysArray[intMonth - 1]) {
    return false;
  }
  
  return true;
}

function IsLeapYear(intYear) {
  if (intYear % 100 == 0) {
    if (intYear % 400 == 0) {
      return true;
    }
  } else {
    if ((intYear % 4) == 0) {
      return true;
    }
  }

  return false;
}


function newTableToggle(idTD, idImg){
	var td = document.getElementById(idTD);
	var img = document.getElementById(idImg);
	if(td != null && img != null){
		var isHidden = td.style.display == "none" ? true : false;
		img.src = isHidden ? "images/icon_hide.gif" : "images/icon_show.gif";
		img.alt = isHidden ? langHide : langShow;
		td.style.display = isHidden ? "" : "none";
	}
}

// text counter for message box
/*  function textCounter(field, countfield, maxlimit, totfield, engfield, products_price, base_price, base_threshold, price_per_char, max_rows) {
	var running_total = 0.0000;
	var engraving_total = 0.0000;
	var multipler;
	var max_length;
	
	if (field.value.length > 0)
	{
		running_total = parseFloat(products_price) + parseFloat(base_price);
		engraving_total = base_price;
	} else {
		running_total = products_price;
		engraving_total = 0.0000;
	}
// if too many rows trim it!
	if (escape(field.value).split('%0A').length > max_rows) {
		alert('You have entered to many new lines in the message for this gift');
		return false;

		while (escape(field.value).split('%0A').length > max_rows)
		{
			max_length = field.value.length - 1;
			field.value = field.value.substring(0, max_length);   }
		}

	if (field.value.length > maxlimit){ // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		alert('You have entered to many characters in the message for this gift');
		return false;
		
	// otherwise, update 'characters left' counter
	} else {
		countfield.value = maxlimit - field.value.length;
		// you get a certain number of characters included in the base price. This is set by the baseprice threshold. Once this has been exceeded add on the cost per char
		if (field.value.length > base_threshold)
		{
			multipler = field.value.length - base_threshold;
			running_total  = running_total + (multipler * price_per_char);
			engraving_total = engraving_total + (multipler * price_per_char);
		}
	
	totfield.value = Math.round(running_total*100)/100;
	
	engfield.value = Math.round((engraving_total*100)* 1.175)/100;
		
	}

}*/

function replaceSubString(text, expression, value){
  //Uses regular expressions. This code was written for JavaScript 1.2+ browsers
  //Use the replaceSubstring or replaceSubstring2 functions if 1.0 & 1.1 browsers.
  //
  //replaceSubstring("hellothere","l","x") = "hexxothere"
//  var exp = new RegExp(expression)
    var expr = new RegExp(expression)
	return text.replace(expr,value);
}

// newline (depending on platform)
function populate(textareaObject){
   if (navigator.appVersion.lastIndexOf('Win') != -1)
      newline="\r\n"
      else newline="\n"
   textareaObject.value="line 1" + newline + "line 2" + newline 
   + "line 3"
}


//display currencie
function displaycurrency(value)
{
	value = new String(value);

	//Math.round(value*100)/100

	myArr = value.split(".");
	
	if (myArr.length==1){
		value = "\u00a3"+value + ".00";
	}else
		if(myArr.length >1){
			value = "\u00a3"+value + "0";
		} else {
			value = "\u00a3"+value + "0";
		}
	return value;
}



// word wrap function
function wordwrap(text, rows, cols)
{
	var strTemp = "";
	var strLineCounter = 0;
	var strCharCounter = 0;
	var tmpWrd = "";
	var strTemporary = replaceSubString(text, /(\r\n|\r|\n)/g,"\n");
	var tmpSub = "";
	var tmpWord = "";
	var idx =0;
	
	for (var i = 0; i < text.length; i++)
	{
		var strChar = text.substring(i, i + 1 );
		var strCharTest = text.substring(i + 1, i + 2);
		
		if (strChar == '\n')
		{
			//alert("p1 : " + strCharTest);
			strTemp += strChar;
			strCharCounter = 0;
			strLineCounter += 1;
			
		}
		else if (strCharCounter == (cols-1))
		{
			if (strCharTest != "\n"){
/*				if(strCharTest == ' ')
				{
					strTemp += '\n' + strChar;
					strCharCounter = 0;
				}else{*/
					
					idx = strTemp.lastIndexOf(" ");
					if((idx>0)||(idx==0)){
						tmpWrd = strTemp.substring(idx+1,strTemp.length);
						
						tmpWrd = tmpWrd + strChar;
						
						tmpSub = strTemp.substring(0,idx+1);
					
						tmpSub = tmpSub+ '\n' + tmpWrd;
										
						strTemp = tmpSub;
					
						strCharCounter = tmpWrd.length;
						tmpWrd = "";
						tmpSub = "";
						idx =0;
					}
					else
					{
						strTemp += '\n' + strChar;
						strCharCounter = 0;
					}
				//}
			} else {
				strTemp += strChar;
				strCharCounter = 0;
			}
			
			strLineCounter += 1;
		}
		else
		{
			strTemp += strChar;
			strCharCounter ++;
		}
	}

	strTemp = replaceSubString(strTemp, /(\r\n|\r|\n)/g,"\n");

	return strTemp;
}


// text counter for message box
 function textCounter(field, countfield, maxlimit, totfield, engfield, products_price, base_price, base_threshold, price_per_char, max_rows, totincfield, quantity, grandfield) {
	var running_total = 0.0000;
	var engraving_total = 0.0000;
	var multipler;
	var max_length;
	var newString = '';
	var char_check;
	var myArr;
	var strTemp;
	var display_price;
	var display_engraving_price;

	var maxperline = (maxlimit / max_rows) + 1;
	//alert ('max chars per line:' . maxperline);

	//strTemp = replaceSubString(field.value, /(\r\n|\r|\n)/g,"\n");
	//alert('message:' . strTemp);
	//return true;

// remove characters not chargable (commented out for now, uncomment for script to work)
   	for (var i = 0; i < field.value.length; i++) {
// regex addcharcter to newstring if not equal to expression	
	var re = new RegExp('[ \";:\\-.~,\r\n|\r|\n]');
	var m = re.exec(field.value.charAt(i));
		if (m == null) {
			newString += field.value.charAt(i);
		}
   }

	field.value = wordwrap(field.value, max_rows, maxperline);

// default values
	if (newString.length > 0)
	{
		running_total = parseFloat(products_price) + parseFloat(base_price);
		engraving_total = base_price;
	} else {
		running_total = products_price;
		engraving_total = 0.0000;
	}

	// now check how many lines are there for lines max 2 there should be 1 \n and lines left 3 there should be 2 \n's
	myArr = (field.value).split('\n');

// remove extra lines
	if ((myArr.length) > max_rows){
		//alert("The text you entered is too long for this item.\n it will be truncated");
		// remove last line
		strTemp = "";
		for (var i = 0; i < max_rows; i++)
		{
			if (i == max_rows){
			strTemp += myArr[i];
			} else {
			strTemp += myArr[i] + '\n';
			}
		}

		strTemp = strTemp.substring(0, strTemp.length - 1);
		field.value = strTemp;
	}

// if too long... trim it to maximum
	if (newString.length > maxlimit){

		field.value = field.value.substring(0, field.value.length - 1);

		/*alert('You have entered to many characters in your message');*/
		return true;

	// otherwise, update 'characters left' counter
	} else {
		countfield.value = maxlimit - newString.length;
		// you get a certain number of characters included in the base price.
		// This is set by the baseprice threshold.
		// Once this has been exceeded add on the cost per char.
		if (newString.length > base_threshold)
	{
		multipler = newString.length - base_threshold;
		running_total  = running_total + (multipler * price_per_char);
		engraving_total = engraving_total + (multipler * price_per_char);
	}
	
	display_price = running_total;
	display_engraving_price = engraving_total;

	totfield.value = display_price;
	
	totincfield.value = displaycurrency(Math.round((display_price* 1.175)*100)/100);

	engfield.value = displaycurrency(Math.round((display_engraving_price * 1.175)*100)/100);

	grandfield.value = displaycurrency(Math.round(((display_price * quantity)* 1.175)*100)/100);

	//Math.round(original*100)/100
		
	}

return true;
}

