/*
  $Id: general.js 1739 2007-12-20 00:52:16Z hpdl $

  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;
}

//String functions to emulate php's left and right 
function Left(str, n){
	if (n <= 0) { return ""; }
	else if (n > String(str).length) { return str; }
	else { return String(str).substring(0,n); }
}

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);
    }
}


//AJAX functions
function createRequestObject() {
     var ro;
     var browser = navigator.appName;
     if(browser == "Microsoft Internet Explorer"){
          ro = new ActiveXObject("Microsoft.XMLHTTP");
     }else{
          ro = new XMLHttpRequest();
     }
     return ro;
}
var AJAXhttp = createRequestObject();
function AJAXsndReq(action) {
     AJAXhttp.open('get', 'AJAX.php?action='+action);
     AJAXhttp.onreadystatechange = handleResponse;
     AJAXhttp.send(null);
}
function handleResponse() {
     if(AJAXhttp.readyState == 4){
          var response = AJAXhttp.responseText;
          var update = new Array();
          if(response.indexOf('|') != -1) {
               update = response.split('|');
               document.getElementById(update[0]).innerHTML = update[1];
          }
     }
}


//Javascript cookie functions
function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}
//Only name and value are required
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );
  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}



	function trim(stringToTrim) {
		return stringToTrim.replace(/^\s+|\s+$/g,"");
	}



	function form_get_params()
	{
		var content = "";
		var f = document.getElementById( 'cms_form' ); 
		for( var i = 0; i < f.elements.length; i++ ) 
			{ content += "" + f.elements[i].name + "=" + f.elements[i].value + "&"; }
		return content;
	}
	
	// used to dynamically change the contents of any div with an ID
	function changeDiv(divName, content) {
		divName = trim(divName);
		if(document.getElementById(divName))
		{
			var divelem = document.getElementById(divName);
			divelem.innerHTML = trim(content);
		}
	}

	/* AJAX Funtionality */
	function menuRequest(url)
	{
		var arg = url;
		url = "AJAX.php?tg_cms_randnum="+ String( Math.random() ) + "&" + url;
		var http_request = false;
		
		if (window.XMLHttpRequest) 
			{ // Mozilla, Safari,...
				http_request = new XMLHttpRequest();
				if (http_request.overrideMimeType) 
					{ http_request.overrideMimeType('text/xml'); }
			} 
		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 an XMLHTTP instance');
			return false;
		}
		
		http_request.onreadystatechange = function() { alertContents(http_request); };
		http_request.open('GET', url, true);
		http_request.send(null);
	}
	function alertContents(http_request) 
	{
		 if(http_request.readyState == 4){
			if (http_request.status == 200) 	
			{
			  var response = http_request.responseText;
			  var updates = new Array();
			  var temp_update = new Array();
			  var update = new Array();
			  if(response.indexOf('V|V') != -1) {
				  updates = response.split('~|~');
				  for (var i = 0; i < updates.length; i++)
				  {
					  update = updates[i];
					  temp_update = update.split('V|V');
					  changeDiv(temp_update[0], temp_update[1]);
				  }
			  }
		 	}
			else
				{ alert('There was a problem with the request.'); }			
		 }
	}
	
	
	/* -----------------------------------------------
   Floating layer - v.1
   (c) 2006 www.haan.net
   contact: jeroen@haan.net
   You may use this script but please leave the credits on top intact.
   Please inform us of any improvements made.
   When usefull we will add your credits.
  ------------------------------------------------ */

	function setVisible(obj)
	{
		obj = document.getElementById(obj);
		obj.style.visibility = (obj.style.visibility == 'visible') ? 'hidden' : 'visible';
	}

	
	
	
	function fv_isSame(elem1,elem2, helperMsg){
		if(elem1.value == elem2.value){
			return true;
		}else{
			alert(helperMsg);
			elem2.focus(); // set the focus to this input
			return false;
		}
	}
	
	function fv_isEmpty(elem, helperMsg){
		if(elem.value.length == 0){
			alert(helperMsg);
			elem.focus(); // set the focus to this input
			return true;
		}
		return false;
	}
	
	function fv_isNumeric(elem, helperMsg){
		var numericExpression = /^[0-9]+$/;
		if(elem.value.match(numericExpression)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	
	function fv_isAlphabet(elem, helperMsg){
		var alphaExp = /^[a-zA-Z ]+$/;
		if(elem.value.match(alphaExp)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	
	function fv_isAlphanumeric(elem, helperMsg){
		var alphaExp = /^[0-9a-zA-Z]+$/;
		if(elem.value.match(alphaExp)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	
	function fv_lengthRestriction(elem, min, max){
		var uInput = elem.value;
		if(uInput.length >= min && uInput.length <= max){
			return true;
		}else{
			alert("Please enter between " +min+ " and " +max+ " characters");
			elem.focus();
			return false;
		}
	}
	
	function fv_madeSelection(elem, helperMsg){
		if(elem.value == "Please Choose"){
			alert(helperMsg);
			elem.focus();
			return false;
		}else{
			return true;
		}
	}
	
	function fv_emailValidator(elem, helperMsg){
		var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
		if(elem.value.match(emailExp)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	
 	function ValidateNewsletterForm(){
		// Make quick references to our fields
		var name = document.getElementById('name');
		var from = document.getElementById('from');
	
		// Check each input in the order that it appears in the form!

		if(!fv_isEmpty(name,"You must enter your name")){
			if(!fv_isEmpty(from,"You must enter your email address")){
				if(fv_emailValidator(from, "Please enter a valid email address")){
					return true;
				}
			}
		}
		return false;
	}
	
	function ValidateTellFriendForm(){
		// Make quick references to our fields
		var from = document.getElementById('to_email_address');
	
		// Check each input in the order that it appears in the form!

		if(!fv_isEmpty(from,"You must enter your email address")){
			if(fv_emailValidator(from, "Please enter a valid email address")){
				return true;
			}
		}
		return false;
	}
