/*
  $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 makeGuaranteeWindow(page, height, width, scrollbars)
{
	window.open(page, '','toolbar=0,scrollbars=' + scrollbars + ',location=0,statusbar=1,menubar=0,resizable=0,width=' + width + ',height=' + height+ ',top=10,left=100');
}

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, toDate) {
  if (Date.parse(from.value) <= Date.parse(toDate.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 toggleVisibility(htmlId)
{
        var legend = document.getElementById(htmlId);
        if (legend.style.display=='block') {
                legend.style.display='none';
        } else {
                legend.style.display='block';
        }
        return false;
}



// Added by J.Scott on Dated: 3 April, 2006
function openPopup(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}



/**
 * atid   - art template ID
 * pid    - product ID
 * cid    - category ID
 * width  - width of the image
 * height - height of the image
 */
function viewProof(atid, pid, cid, width, height) {
    if (atid && pid && cid) {
        var args = '';
        // skipp the first 5 arguments, and the last one is blank
        for (var ii=5; ii<viewProof.arguments.length-1; ii++) {
            var _val = document.getElementById(viewProof.arguments[ii]);
            args += '&'+ viewProof.arguments[ii] +'='+ URLEncode(_val.value);
        }

        // open the proof in a new window
        window.open('proof_wrapper.php?atid=' + atid + '&pid=' + pid + '&cPath=' + cid + args,
                    'blank',
                    'toolbar=0,status=1,scrollbars=1,menubar=0,resizable=0,width=' + width + ',height=' + height);
    }

    return false;
}

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that
// (a) you leave this copyright notice intact, and
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
/** karn - modified to take a string input **/
function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

//===============hide drop-down lists when top layer is present (for ie6) ============
function displayselects(formname,action,spanname){
    var spanobj;
    var text;
    if(action) var d = 'visible';
    else var d = 'hidden';
    //alert(document.forms[formname]);
    for(var i=0; i<document.forms[formname].elements.length; i++){
        //alert(document.forms[formname].elements[i].name+' = '+document.forms[formname].elements[i].type);
        if(document.forms[formname].elements[i].type=='select-one'){
            document.forms[formname].elements[i].style.visibility = d;
            spanobj=gettrailobj(spanname);
            if (spanobj) {
            text = spanobj.innerHTML;
            if(action)
            spanobj.innerHTML = '';
            else
            spanobj.innerHTML = document.forms[formname].elements[i].options[document.forms[formname].elements[i].selectedIndex].text;
            }
        }
    }

}

function popupWindow(url) {
  window.open(url, 'popupWindow', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150');
}

////////// moved from product info /////////////

/**
 * karn - this code is used to check required custom fields
 *
 */
function customField( required, fieldKey, fieldName, regularExpression ) {
	this.required = required;
	this.fieldKey = fieldKey;
	this.fieldName = fieldName;
	this.regularExpression = regularExpression;
}

/*
  added by hedwig due to go button checkup whether it will be redirect to wishlist page or the same page
*/
function checkform()
{
    if(document.getElementById("wishlistID").value == 0)
    {
      //alert(document.cart_quantity.products_id.value);
      window.location = "wishlistedit.php?action=add&products_id="+document.cart_quantity.products_id.value;
      return false;
    }
    else
    {
      window.location = "product_info.php?cPath="+ document.cart_quantity.cPath.value +"&products_id="+document.cart_quantity.products_id.value+"&W_ID="+document.cart_quantity.wishlistID.value;
      return false;
    }
}

/* DDB - 041031 - Form Field Progress Bar */
/***********************************************
* Form Field Progress Bar- By Ron Jonk- http://www.euronet.nl/~jonkr/
* Modified by Dynamic Drive for minor changes
* Script featured/ available at Dynamic Drive- http://www.dynamicdrive.com
* Please keep this notice intact
***********************************************/
function textCounter(field,counter,maxlimit,linecounter)
{
	// text width//
	var fieldWidth =  parseInt(field.offsetWidth);
	var charcnt = field.value.length;
	// trim the extra text
	if (charcnt > maxlimit)
  {
		field.value = field.value.substring(0, maxlimit);
	}
  else
  {
  	// progress bar percentage
  	var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;
  	document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";
  	document.getElementById(counter).innerHTML="Limit: "+percentage+"%"
  	// color correction on style from CCFFF -> CC0000
  	setcolor(document.getElementById(counter),percentage,"background-color");
	}
}

function setcolor(obj,percentage,prop)
{
	obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";
}

function update_qty()
{
	var has_sizes=false;
    var formObj = document.cart_quantity;
    var total_qty = 0;
    var prod_qty_obj = document.getElementById('product_quantity');
    var reg = new RegExp("size.+", "i");
    for (var i=0;i < formObj.length;i++)
    {
		fldObj = formObj.elements[i];
		if(reg.exec(fldObj.id))
		{
			has_sizes = true;
            if(fldObj.value != '')
            {
                total_qty = parseInt(total_qty) + parseInt(fldObj.value);
            }
        }
	}
	if (has_sizes) prod_qty_obj.value = total_qty;
}

function makeEditWindow(page, height, width, scrollbars)
{
	window.open(page, 'newWindow','toolbar=0,scrollbars=' + scrollbars + ',location=0,statusbar=1,menubar=0,resizable=0,width=' + width + ',height=' + height+ ',top=10,left=100');
}


/**
 * Karn - check custom fields (only the required ones)
 *
 */
function checkCustomFields()
{
	var i = 0;
	
	for (i = 0; i < customFields.length; i++) {

		var nameString = new String(i+"_"+customFields[i].fieldKey);
		nameString = nameString.toLowerCase();
		var regEx = /\s+/g;
		nameString = nameString.replace(regEx,'_');
		
		var formDoc = document.getElementById(nameString);
		
		if (formDoc.value == undefined)
		{
			//Check radio buttons			
			var fieldByName = new String(customFields[i].customFieldId+"*"+customFields[i].fieldName);
			
			if (customFields[i].required)
			{
				fieldByName = fieldByName+'*required';
			}
			
			var regEx = /\s+/g;
			fieldByName = fieldByName.toLowerCase();
			fieldByName = fieldByName.replace(regEx,'_');
			
			var bIsSelect = false;
			
			var getByName = document.getElementsByName(fieldByName);
			
			if (getByName.length)
			{
				for (j = 0; j < getByName.length; j++) 
				{
					if (getByName[j].checked == true)
					{
						bIsSelect = true;
						break;
					}
				}
				
				if (bIsSelect == false)
				{
					alert('The field "'+ customFields[i].fieldName +'" is required.');
		            document.getElementById(nameString).focus();
		            return false;
				}
			}
		}
		
		
		
		// This MUST be before any checks, as an undefined value will yield JS errors in the later checks.
        if(formDoc == null || formDoc.value == undefined) continue;
        
		if (customFields[i].required && trim(formDoc.value).length == 0)
        {
            alert('The field "'+ customFields[i].fieldName +'" is required.');
            document.getElementById(nameString).focus();
            return false;
        }
        
        //if you change this from g also change the admin reg ex testing
        var regExObj = new RegExp(customFields[i].regularExpression, "g");
        if (!trim(formDoc.value).match(regExObj) && trim(formDoc.value).length > 0) {
            alert('The field "'+ customFields[i].fieldName +'" is formatted incorrectly.');
            document.getElementById(nameString).focus();
            return false;
        }
	}
	return true;
}

/**
 * karn - trimming function
 *
 * got from http://forum.java.sun.com/thread.jspa?threadID=684934&messageID=3987789
 */
function trim(str)
{
	if(!str) return '';
    // updated to use result var as to not modify str
    var result = str;
    return result.replace(/^\s*|\s*$/g,"");
}
/**
 * karn - format money
 *
 * got from http://www.web-source.net/web_development/currency_formatting.htm
 */
function formatMoney(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';

	if(i < 0) { minus = '-'; }

	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);

	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }

	s = minus + s;

	return s;
}

//Natalie 5-Mar-2008 if skip upload flag is set - go to shopping cart
function check_form_action(form){
    var str=form.action;
    if(form.elements['skipartupload'].checked==true){
        str = str.replace('artwork_products','shopping_cart');
        form.action = str.replace('artwork_product','add_product');
        form.method = "POST";
    }
}

// js functions for event calendar tool
function ge(id) {
    return document.getElementById(id);
}

// update event info
function update_event(calendar_id, month, day, year, event_id) {
    var name = ge('name').value;
    var start_date = ge('start_date').value;
    var type = ge('type').value;
    var interval = parseInt(ge('interval').value);
    var interval_type = ge('interval_type').value;
    var description = ge('description_field').value;
    var shipping_addresses = document.forms['event_calendar'].shipping_address_id;
    var shipping_address = 0;

    var index = 0;
    while (shipping_addresses[index]) {
        if (shipping_addresses[index].checked) {
            shipping_address = shipping_addresses[index].value;
            break;
        }

        index++;
    }

    if (!check_event_calendar_fields(shipping_address)) return false;

    xajax_update_event(calendar_id, month, day, year, event_id, name,
        start_date, type, interval, interval_type, description, shipping_address);
}

function create_event(calendar_id) {
    var name = ge('name').value;
    var start_date = ge('start_date').value;
    var type = ge('type').value;
    var interval = parseInt(ge('interval').value);
    var interval_type = ge('interval_type').value;
    var description = ge('description_field').value;
    var shipping_addresses = document.forms['event_calendar'].shipping_address_id;
    var shipping_address = 0;

    var index = 0;
    while (shipping_addresses[index]) {
        if (shipping_addresses[index].checked) {
            shipping_address = shipping_addresses[index].value;
            break;
        }

        index++;
    }

    if (!check_event_calendar_fields(shipping_address)) return false;

    xajax_create_event(calendar_id, name, start_date, type, interval, interval_type, description, shipping_address);
}

// check fields of event
function check_event_calendar_fields(shipping_address) {
    var name = ge('name').value;
    var start_date = ge('start_date').value;
    var type = ge('type').value;
    var interval = parseInt(ge('interval').value);
    var interval_type = ge('interval_type').value;
    var description = ge('description_field').value;
    var shipping_addresses = document.forms['event_calendar'].shipping_address_id;

    var errors = '';
    if (name.length == 0) {
        errors += 'Name is required.'+ "\n";
    }
    if (start_date.length == 0) {
        errors += 'Start Execution Date is required.'+ "\n";
    }
    if (type.length == 0) {
        errors += 'Type is required.'+ "\n";
    }
    if (isNaN(interval) || (interval < 0)) {
        errors += 'Interval should be equal or greater 0.'+ "\n";
    } else {
	    if ((interval > 0) && (interval_type.length == 0)) {
	        errors += 'Set Interval Type.'+ "\n";
	    }
    }
    if (shipping_address == 0) {
        errors += 'Shipping address is required.'+ "\n";
    }

    if (errors.length > 0) {
        alert(errors);
        return false;
    }

    return true;
}

// This will highlight any assigned rows in a moduleTable table.
if (typeof($) != "undefined") {
	$(function(){ $('.moduleTable .moduleRow').hoverClass('moduleRowOver'); });
}
