
// MYFOCUS SYSTEMS
// Librería de funciones JAVASCRIPT
// =========================================================================================

// Abre una ventana emergente
//
function LibWindowPopup(url_page, window_name, w, h)
{
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	if (winl < 0) winl = 0;
	if (wint < 0) wint = 0;
	
	windowprops = "height="+h+",width="+w+",top="+ wint +",left="+ winl +",location=no,"
	+ "scrollbars=no,menubar=no,toolbar=no,resizable=no,status=no,directories=no,titlebar=no";
	
	window.open(url_page, window_name, windowprops);
	return false;
}

// Abre una ventana emergente con scroll
//
function LibWindowPopupScroll(url_page, window_name, w, h)
{
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	if (winl < 0) winl = 0;
	if (wint < 0) wint = 0;
	
	windowprops = "height="+h+",width="+w+",top="+ wint +",left="+ winl +",location=no,"
	+ "scrollbars=yes,menubar=no,toolbar=no,resizable=no,status=no,directories=no,titlebar=no";

	window.open(url_page, window_name, windowprops);
	return false;
}

// Comprueba si un valor está en un array
function LibInArray(List,Object)
{
  var i = List.length - 1;
  if (i >= 0) {
		do {
			// alert( i + ' | ' + List[i] + ' | ' + Object.value );
			// alert( i + ' | ' + List[i].toLowerCase() + ' | ' + Object.value.toLowerCase() );
			// if (List[i] === Object.value) {
			if (List[i].toLowerCase() === Object.value.toLowerCase()) {
				return true;
			}
		} while (i--);
  }
	
  return false;
}

// Comprueba si un email es válido		
function LibIsValidEmail(Object)
{
	var CheckString = /^[\w\.\-]+\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
	return ( CheckString.exec( Object.value ) );
}

// Comprueba si un campo está vacío
function LibIsEmpty(Object)
{
	return ( Object.value == "" );
}

// Numeric check
function LibNumCheck( InputNum, Max )
{
  var Num = InputNum * 1; // Pasamos a numérico

  // Comprobamos que ho haya pasado el límite
  if( Num < 0 )
  {
			alert( "El importe debe ser mayor de cero" );
			return false;
	}
	else
	{
    if( Num > Max )
		{
			alert( "Ha sobrepasado el saldo (" + Max + ")" );
			return false;
		}
	}
	
  return true;
}

// Autocorrección de número en el input
function LibNumInput (str, dec, bNeg)
{
	var cDec 	= '.'; // Símbolo para decimales
	var bDec 	= 0;
	var val 	= "";
	var strf 	= "";
	var neg 	= "";
	var i		 	= 0;

	if (str == "") {
		str=0;
	}
	
	round_number (parseFloat ("0"), dec);
	
	if (bNeg && str.charAt (i) == '-') { neg = '-'; i++; }

	for (i; i < str.length; i++) {
		val = str.charAt (i);
		if (val == cDec) {
			if (!bDec) {
				strf += val; bDec = 1;
			}
		}
		else if (val >= '0' && val <= '9') {
			strf += val;
		}
	}
	
	strf = (strf == "" ? 0 : neg + strf);
	
	return round_number (parseFloat (strf), dec);
}

// strpos('Buffer', 'Char', Init);
function strpos( haystack, needle, offset)
{
  var i = (haystack+'').indexOf( needle, offset ); 
  return i===-1 ? false : i;
}

function round_number (num, dec)
{ // low-level numeric format with upward rounding at 5+
 var cDec = '.'; // decimal point symbol
 if (!(dec >= 0 && dec <= 9))
  dec = 2;
 if (isNaN (num) || num == '')
 { // zero values are returned in proper decimal format
  var sdec = "";
  for (var i = 0; i < dec; i++)
   sdec += '0';
  return "0" + (sdec != "" ? cDec + sdec : "");
 }
 var snum = new String (num);
 var arr_num = snum.split (cDec);
 var neg = '';
 var nullify = 0;
 dec_a = arr_num.length > 1 ? arr_num[1].length : 0;
 if (dec_a <= dec)
 { // fill decimal places with trailing zeros if necessary
  if (!dec_a)
   arr_num[1] = "";
  for (var i = 0; i < dec - dec_a; i++)
   arr_num[1] += '0';
  dec_a = dec;
 }
 // total decimal places in value before rounding and formatting
 dec_i = dec_a;
 dec_a -= dec;
 if (arr_num[0].charAt(0) == '-')
 { // preserve negative symbol, remove from value (calculations)
  neg = '-';
  arr_num[0] = arr_num[0].substring (1, arr_num[0].length);
 }
 if (!parseInt (arr_num[0])) // case when whole value is 0
 { // nullify a zero whole value for correct decimal point placement
  arr_num[0] = "1"; // 0 whole # would not preserve amount in calc.
  nullify = 1; // flag to remove greatest 1 portion from whole #
 }
 var whole = parseInt (arr_num[0] * Math.pow (10, arr_num[1].length));
 // remove leading zeros
 for (i = 0; i < arr_num[1].length; i++)
  if (arr_num[1].charAt (i) != '0')
   break;
 if (arr_num[1].length == i) // decimal portion blank or all zeros
  return (neg + arr_num[0] + (arr_num[1] != "" ? (cDec + arr_num[1]) : ""));
 whole += parseInt (arr_num[1].substring (i, arr_num[1].length));
 if (arr_num[1].length != dec)
 { // round number affecting appropriate cluster of decimal places
  var diff = "";
  var str = new String (whole);
  for (i = dec_a; i > 0; i--)
   diff += str.charAt (str.length - i);
  diff = Math.pow (10, dec_a) - parseInt (diff);
  whole += ((diff <= 5 * Math.pow (10, dec_a - 1)) ? diff : 0);
 }
 str = new String (whole);
 var str_f = "";
 var j = 0;
 var k = 0;
 if (nullify)
 {
  arr_num[0] = "0"; // remove 1 from greatest decimal place (restoration)
  str = (parseInt (str.charAt(0)) - 1) + str.substring (1, str.length);
 }
 else // re-assign whole numeric portion from entire numeric string value
  arr_num[0] = str.substring (0, str.length - dec_i);
 for (i = 0; i < str.length; i++)
 { // combine portions of decimal number (whole, fraction, sign)
  if (k - 1 > dec)
   break; // fraction termination case
  if (j == arr_num[0].length)
  {
   if (!j)
    str_f += 0;
   str_f += (dec != 0 ? cDec : ''); // insert decimal point
   --i; // backtrack one character
   k++; // signal fraction count
  }
  else // assign character by character
   str_f += str.charAt (i);
  j++;
  if (k) // fractional counter increment
   k++;
 }
 return neg + str_f;
} 

// Date
// Simulates PHP's date function
Date.prototype.format = function(format) {
        var returnStr = '';
        var replace = Date.replaceChars;
        for (var i = 0; i < format.length; i++) {
                var curChar = format.charAt(i);
                if (replace[curChar])
                        returnStr += replace[curChar].call(this);
                else
                        returnStr += curChar;
        }
        return returnStr;
};

Date.replaceChars = {
        shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        
        // Day
        d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
        D: function() { return Date.replace.shortDays[this.getDay()]; },
        j: function() { return this.getDate(); },
        l: function() { return Date.replace.longDays[this.getDay()]; },
        N: function() { return this.getDay() + 1; },
        S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 13 && this.getDate() != 1 ? 'rd' : 'th'))); },
        w: function() { return this.getDay(); },
        z: function() { return "Not Yet Supported"; },
        // Week
        W: function() { return "Not Yet Supported"; },
        // Month
        F: function() { return Date.replace.longMonths[this.getMonth()]; },
        m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
        M: function() { return Date.replace.shortMonths[this.getMonth()]; },
        n: function() { return this.getMonth() + 1; },
        t: function() { return "Not Yet Supported"; },
        // Year
        L: function() { return "Not Yet Supported"; },
        o: function() { return "Not Supported"; },
        Y: function() { return this.getFullYear(); },
        y: function() { return ('' + this.getFullYear()).substr(2); },
        // Time
        a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
        A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
        B: function() { return "Not Yet Supported"; },
        g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
        G: function() { return this.getHours(); },
        h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
        H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
        i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
        s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
        // Timezone
        e: function() { return "Not Yet Supported"; },
        I: function() { return "Not Supported"; },
        O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
        T: function() { return "Not Yet Supported"; },
        Z: function() { return this.getTimezoneOffset() * 60; },
        // Full Date/Time
        c: function() { return "Not Yet Supported"; },
        r: function() { return this.toString(); },
        U: function() { return this.getTime() / 1000; }
}

// NAVs
var treeopened = null;
function opentree(tree)
{
	var cls = '';
	if (document.getElementById) {
		var el = document.getElementById (tree);
		if (el && el.className) {
			el.className = (el.className == 'navOpened') ? 'navClosed' : 'navOpened';
		}
	}
	if (navigator.appName == 'Microsoft Internet Explorer' && document.documentElement && navigator.userAgent.indexOf ('Opera') == -1) parent.setScrollInIE();
	return false;
}

// CATALOG
function domSetInnerHTML(obj, html_string)
{
  // IE ... and other browsers that support innerHTML
  if (obj.innerHTML != null)
    {
      obj.innerHTML = html_string;
    }
  // W3C method ... this *should* work
  else if (document.createRange)
    {
      	var rng = document.createRange();

	if (rng.setStartBefore && rng.createContextualFragment &&
	    obj.removeChild && obj.appendChild) {
           rng.setStartBefore(obj);
           htmlFrag = rng.createContextualFragment(content);
           while (obj.hasChildNodes())
      	      obj.removeChild(obj.lastChild);
           obj.appendChild(htmlFrag);
	}
    }
  else if (obj.document != null && obj.document.open != null)
    {

      /* this NS 4.x way is *almost* as trivial ... note you cannot do this
         *  with relatively positioned <div>'s or <layers>'s - it will puke.
       */
      obj.document.open ();
      obj.document.write (html_string);
      obj.document.close ();
    }
}


// dropdownCellId - the <td> id where the dropdown is in
// selectName - the <select> name
// selectID - the <select> id
// selectText - the empty option value text (ie: "Choose One", "Select"... etc; not displayed if empty)
// optionList - the list of arguments for <option> values (ie: "value1", 1, "value2", 2, etc.)
// if only one option is given, a hidden variable is set (rather than a one-option menu being displayed)
function newDropdownWithValues(dropdownCellId, selectName, selectID, selectText, changeAction, optionList) {
    var dropdownCell = document.getElementById(dropdownCellId);
    var selectBox;
    // There must be at least the selectText to create a new dropdown
    if (arguments.length > 3) {
        if (arguments.length > 7) { 
            var numOfOptions = arguments.length - 1;
						//selectBox = '<select name="' + selectName + '" id="' + selectID + '">"';
						// selectBox = '<select name="' + selectName + '" id="' + selectID + '" class="commerce_size">"';
						
						if( changeAction != "" ) {
							selectBox = '<select name="' + selectName + '" id="' + selectID + '" class="commerce_size" onchange="' + changeAction + '">"';
						}
						else {
							selectBox = '<select name="' + selectName + '" id="' + selectID + '" class="commerce_size">"';
						}
																		
            // Set the first option to be empty, with selectText
            if (selectText != "") {
                selectBox += '<option value="">' + selectText + '</option>';
            }
            // loop through and set the rest of the options (increments of 2)
            for (var i = 5; i < numOfOptions; i++) { 
                selectBox += '<option value="' + arguments[i] + '">' + arguments[i + 1] + '</option>';
                i++;
            }
            selectBox += '</select>';
            domSetInnerHTML(dropdownCell, selectBox);
        } else {
            document.getElementById(selectName).value = arguments[5]; 
        }
    }
}

// selectId - the id of the <select>
// optionValue - the value of <option> that you want it changed to
function populateDropdown(selectId, optionValue) {
    var field;
    var selected = 0;
    // make sure the <select> exists
    if (document.getElementById(selectId)) {
        field = document.getElementById(selectId);
        // loop through all the options and try to match the option value (not option text)
        for (var i = 0; i < field.options.length; i++) {
            if (field.options[i].value == optionValue) {
                // if found, set the index
                selected = i;
            }
        }
        field.selectedIndex = selected;
    }
}

function changePrice(priceCell, regPrice, salePrice) {
    var cell = document.getElementById(priceCell);
    var priceText;

    //if (salePrice != regPrice) {
		if (salePrice > '') {
        priceText = '<span class="hasStrike">' + regPrice + '</span>&nbsp;&nbsp;<span class="redColor">' + salePrice + '</span>';
    } else {
        priceText = '<span class="blueColor">'  + regPrice + '</span>';
    }

    domSetInnerHTML(cell, priceText);
}

// Permite obtener un campo indicando su nombre
function getAll(FieldName)
{
	var i = 0;
	var form = document.forms[i];
	while (form != null)
	{
		if (eval("form." + FieldName) != null) {
			return (eval("form." + FieldName));
		}
		form = document.forms[i];
		i++;
	}
	
	if (document.getElementById(FieldName) != null)
	{
			return (document.getElementById(FieldName));
	}
	
	i = 0;
	var objImage = document.images[i];
	while (objImage != null)
	{
		if (eval("objImage." + FieldName) != null) {
			return (eval("objImage." + FieldName));
		}
		objImage = document.images[i];
		i++;
	}
	
	return null;
}  