// Initialize vars here that need to be global (used by multiple jquery files)
var siteUrl = '';	// used with product page jquery
var pid = '';		// used with product page jquery
var preventAutoLoadReviewCookie;	// used with product page jquery
var autoShowReviewModal;				// used with product page jquery
//var formId = 'order-form';
var bundles = new Array();		// used with ProductBundleJS.js
var virtClubProd = 0;

function Product(basenumber, list_price, pgc) {
    this.Basenumber = basenumber;
    this.List_Price = list_price;
    this.PGC = pgc;
}

function Variant(Size_Value, Color_Value, Color_Code, I, S, B, BD, Special_Handling, Kickback, PreOrder_Flag, Expected_Date) {
    this.I = I;
    this.Size_Value = Size_Value;
    this.Color_Value = Color_Value;
    this.Color_Code = Color_Code;
    this.S = S;
    this.B = B;
    this.BD = BD;
    this.Special_Handling = Special_Handling;
    this.Kickback = Kickback;
    this.P = PreOrder_Flag;
    this.Expected_Date = Expected_Date;

    this.setPricing = function(Base_Price, Loyalty_Price, Point_Cost) {
        this.Base_Price = Base_Price;
        this.Loyalty_Price = Loyalty_Price;
        this.Point_Cost = Point_Cost;
    }
}

/**
 * Size specific functions.
 */
function validate_size_menu() {
    var size = null;
    var size_array = new Array();

    if (document.getElementById('size')) {
        var s_el = document.getElementById('size');
        size = (s_el.options[s_el.selectedIndex].value == '') ? null: s_el.options[s_el.selectedIndex].value;
    }

    s_el.length = 0;
    s_el.options[0] = new Option('Elije', '');

    for (var i in sProduct.Variants) {
            if (size_in_menu(s_el, sProduct.Variants[i].Size_Value_Id) === false) {
                s_el.options[s_el.options.length] = new Option(sProduct.Variants[i].Size_Value, sProduct.Variants[i].Size_Value_Id);
            }
        }
    // Sorting function call
    sortSelect(document.getElementById('size'));
}

function size_in_menu(size_object, size) {
    for (var i = 0; i < size_object.options.length; i++) {
        if (size_object.options[i].value == size) {
            return true;
        }
    }
    return false;
}

// size drop-down sort function - ascending (case-insensitive)
function sortFuncAsc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();

    // This keeps choose at the top
    if (value1 === 'elije') return ( - 1);
    if (value2 === 'elije') return (1);

    // Lets handle letter sizes i.e s, m, l
    // basically converting the sizes into a numeric that
    // evaluates to the order we would like them to appear
    var sizeText = new Array('yxs', 'ys', 'ym', 'yl', 'yxl', 'xxs', '2xs', 'xs', 's', 'm', 'l', 'xl', 'xxl', '2xl', 'xxxl', '3xl');
    var tempValue1 = new String(value1);
    var tempValue2 = new String(value2);
    var matchLetters = new RegExp(/[a-z]+/);

    var resultSizeVal1 = tempValue1.match(matchLetters);
    var resultSizeVal2 = tempValue2.match(matchLetters);

    if (resultSizeVal1) {
        for (var abc = 0; abc <= sizeText.length; abc++)
        if (value1 == sizeText[abc]) value1 = abc;
    }
    if (resultSizeVal2) {
        for (var abc = 0; abc <= sizeText.length; abc++)
        if (value2 == sizeText[abc]) value2 = abc;
    }

    // get the length of each value for padding purposes
    var len_value1 = value1.length;
    var len_value2 = value2.length;
    // this makes sure the numbers actually compare correctly
    // since jscript isnt recognizing them as actual numbers
    // basically padding the string so that the digits line up
    if (len_value1 < len_value2) {
        for (var x = len_value1; x < len_value2; x++)
        value1 = ' ' + value1;
    }
    if (len_value2 < len_value1) {
        for (var x = len_value2; x < len_value1; x++)
        value2 = ' ' + value2;
    }

    // makes sure that half sizes line up with the matching
    // whole size
    var tempValue1a = new String(value1);
    var tempValue2a = new String(value2);
    var matchHalf = new RegExp(/\.5/);
    var resultHalfVal1 = tempValue1a.match(matchHalf);
    var resultHalfVal2 = tempValue2a.match(matchHalf);

    if (resultHalfVal1) {
        value1 = '  ' + value1.replace(/\.5/, '');
        // need to see if value 2 is a half size too
        if (tempValue2a.match(/\.5/)) value2 = '  ' + value2.replace(/\.5/, '');
        if (value1 >= value2) return (1);
        if (value1 < value2) return ( - 1);
    }

    if (resultHalfVal2) {
        value2 = '  ' + value2.replace(/\.5/, '');
        // need to see if value 1 is a half size too
        if (tempValue1a.match(/\.5/)) value1 = '  ' + value1.replace(/\.5/, '');
        if (value2 >= value1) return ( - 1);
        if (value2 < value1) return (1);
    }

    // if we make it here, just flat out compare them
    if (value1 > value2) return (1);
    if (value1 < value2) return ( - 1);
    return (0);
}

function sortSelect(selectToSort) {
    // copy options into an array
    var myOptions = [];
    for (var loop = 0; loop < selectToSort.options.length; loop++) {
        myOptions[loop] = {
            optText: selectToSort.options[loop].text,
            optValue: selectToSort.options[loop].value
        };
    }

    myOptions.sort(sortFuncAsc);

    // copy sorted options from array back to select box
    selectToSort.options.length = 0;
    for (var loop = 0; loop < myOptions.length; loop++) {
        var optObj = document.createElement('option');
        optObj.text = myOptions[loop].optText;
        optObj.value = myOptions[loop].optValue;
        selectToSort.options[selectToSort.options.length] = new Option(optObj.text, optObj.value);
    }
}
// End Size Sort functions
/**
 * Color specific functions
 */
function update_image(basenumber) {
    if (update_image_customization()) {
        return true;
    }

    var color = null;
    var color_code = null;
    var i = 0;
    var j = 0;
    var q = 0;

    if (document.getElementById('color')) {
      var c_el = document.getElementById('color');
      color = (c_el.options[c_el.selectedIndex].value == '') ? null: c_el.options[c_el.selectedIndex].value;
    } else if (document.getElementById('selectedsinglecolor')) {
    	var c_el = document.getElementById('selectedsinglecolor');
      color = (c_el.value == '') ? null: c_el.value;
    }

    if (c_el) {
        if (color) {
            for (i in sProduct.Variants) {
                if (color == sProduct.Variants[i].Color_Value_Id) {
                    color_code = sProduct.Variants[i].Color_Code;
                    break;
                }
            }
        }
        else {
            for (i in sProduct.Variants) {
                if (q <= sProduct.Variants[i].I) {
                    q = sProduct.Variants[i].I;
                    color_code = sProduct.Variants[i].Color_Code;
                }
            }
        }
		
		if (typeof document.images.ProductImage != 'undefined') {
			if (document.images.ProductImage.src != 'http://' + window.location.host + 'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/Images/Catalog/ProductImages/300/' + basenumber + '.' + color_code + '.JPG') {
				document.images.ProductImage.src = 'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/Images/Catalog/ProductImages/300/' + basenumber + '.' + color_code + '.JPG';
			}
		}
    }
}

function update_image_giftcard(basenumber) {
    var color = null;
    var color_code = null;
    var i = 0;
    var j = 0;
    var q = 0;

	if (document.getElementById('color')) {
      var c_el = document.getElementById('color');
      color = (c_el.options[c_el.selectedIndex].value == '') ? null: c_el.options[c_el.selectedIndex].value;
    } else if (document.getElementById('selectedsinglecolor')) {
    	var c_el = document.getElementById('selectedsinglecolor');
      color = (c_el.value == '') ? null: c_el.value;
    }

    if (c_el) {
        if (color) {
            for (i in sProduct.Variants) {
                if (color == sProduct.Variants[i].Color_Value_Id) {
                    color_code = sProduct.Variants[i].Color_Code;
                    break;
                }
            }
        }
        else {
            for (i in sProduct.Variants) {
                if (q <= sProduct.Variants[i].I) {
                    q = sProduct.Variants[i].I;
                    color_code = sProduct.Variants[i].Color_Code;
                }
            }
        }
		
		if (typeof document.images.ProductImage != 'undefined') {
			if (document.images.ProductImage.src != 'http://' + window.location.host + 'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/Images/Catalog/ProductImages/300/' + basenumber + '.' + color_code + '.JPG') {
				document.images.ProductImage.src = 'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/Images/Catalog/ProductImages/300/' + basenumber + '.' + color_code + '.JPG';
			}
		}
    }
}

function validate_color_menu() {
    var color = null;
    var color_array = new Array();

    if (document.getElementById('color')) {
      var c_el = document.getElementById('color');
      color = (c_el.options[c_el.selectedIndex].value == '') ? null: c_el.options[c_el.selectedIndex].value;
      c_el.length = 0;
    	c_el.options[0] = new Option('Elije', '');
    } else if (document.getElementById('selectedsinglecolor')) {
    	var c_el = document.getElementById('selectedsinglecolor');
      color = (c_el.value == '') ? null: c_el.value;
    }

    for (var i in sProduct.Variants) {
        if (sProduct.Variants[i].I >= 1 || sProduct.Variants[i].B >= 1 || sProduct.Variants[i].S >= 1) {
            c_el.options[c_el.options.length] = new Option(sProduct.Variants[i].Color_Value, sProduct.Variants[i].Color_Value_Id);
        }
    }
}
// End Color specific functions
function update_image_customization() {
    // Array of available cust_packages with name='Package_Name'
    var cust_packages = document.getElementsByName('Package_Name');
    // They clicked Customize? Yes radio
    if (document.getElementsByName('Customize').length >= 1) {
        if (document.getElementsByName('Customize')[0].checked == true) {
            // There should be 1 or more customization cust_packages to loop through
            for (var p = 0; p < cust_packages.length; p++) {
                // Customer's selected package
                if (cust_packages[p].checked == true) {
                    // Following code is for Club Store cust_packages
                    if (cust_packages[p].getAttribute('value').substring(0, 3).toUpperCase() == 'CS.') {
                        var values = document.getElementsByName(cust_packages[p].getAttribute('value') + '.LOGO');
                        for (var m = 0; m < values.length; m++) {
                            if (values[m].getAttribute('type') == 'radio') {
                                if (values[m].checked == true) {
                                    packageImageUpdateFunctions[cust_packages[p].getAttribute('value')](document.getElementsByName(cust_packages[p].getAttribute('value') + '.LOGO')[m].value);
                                    return true;
                                }
                            }
                        }
                    }
                    // Following code is for DLHERO and REPLICA cust_packages
                    else if (cust_packages[p].getAttribute('value').toUpperCase() == 'DLHERO' || cust_packages[p].getAttribute('value').toUpperCase() == 'ORIGINALES') {
                        var jersey_name = '';
                        var jersey_num = '';
                        // <div> that contains the customization package elements
                        var div_name = '' + cust_packages[p].getAttribute('value').toUpperCase() + '.NameNumber.Section';
                        // All <input> tags under the <div>
                        var div_input_tags = document.getElementById(div_name).getElementsByTagName('input');
                        // Lets find the right <input> tags
                        for (var i = 0; i < div_input_tags.length; i++) {
                            // Want don't want the hidden <input> tags
                            if (div_input_tags[i].getAttribute('type') == 'text') {
                                // Input tags 'name' attribute
                                var input_name_attr = div_input_tags[i].getAttribute('nombre');
                                // Need to know the <input id="?"> value for the NAME customization
                                if (jersey_name == '' && input_name_attr.match("NOMBRE")) {
                                    jersey_name = input_name_attr;
                                }
                                // Need to know the <input id="?"> value for the NUMBER customization
                                else if (jersey_num == '' && input_name_attr.match("N\332MERO")) {
                                    jersey_num = input_name_attr;
                                }
                            }
                        }
                        // If input ids for for exit then make the call to the inline javascript generated by ProductCustomizationPackages.tem
                        if (jersey_name != '' && jersey_num != '') {
							if (document.getElementById(jersey_name)!=null) {
								packageImageUpdateFunctions[cust_packages[p].getAttribute('value')](document.getElementById(jersey_name).value, document.getElementById(jersey_num).value);
								return true;
							}
                        }
                    }
                }
            }
        }
    }
    return false;
}

/**
 * Tier Pricing specific functions
 */
function open_tierpricing_matrix() {
    if (document.getElementById('matrix')) document.getElementById('matrix').style.display = 'none'
    document.getElementById('tierPricing').style.display = 'block';
    if (document.getElementById('tierPricing').style.display == 'block') {
        document.getElementById('PriceChartLink').style.display = 'none';
    } else {
        document.getElementById('PriceChartLink').style.display == 'block'
    }

}
// End Tier Pricing specific functions

/**
 * Sizes AND Colors exist
 */
function open_availability_matrix() {
    if (document.getElementById('tierPricing')) document.getElementById('tierPricing').style.display = 'none';
    document.getElementById('matrix').style.display = 'block';
}

function update_color_menu() {
    var size = null;
    var color = null;

    if (document.getElementById('size')) {
        var s_el = document.getElementById('size');
        size = (s_el.options[s_el.selectedIndex].value == '') ? null: s_el.options[s_el.selectedIndex].value;
    }

    if (document.getElementById('color')) {
      var c_el = document.getElementById('color');
      color = (c_el.options[c_el.selectedIndex].value == '') ? null: c_el.options[c_el.selectedIndex].value;
      c_el.length = 0;
    	c_el.options[0] = new Option('Elije', '');
    } else if (document.getElementById('selectedsinglecolor')) {
    	var c_el = document.getElementById('selectedsinglecolor');
      color = (c_el.value == '') ? null: c_el.value;
    }

    if (size == null) {
        return;
    }

    for (var i in sProduct.Variants) {
        if (size == sProduct.Variants[i].Size_Value_Id && (sProduct.Variants[i].I >= 1 || sProduct.Variants[i].B >= 1 || sProduct.Variants[i].S >= 1)) {
            c_el.options[c_el.options.length] = new Option(sProduct.Variants[i].Color_Value, sProduct.Variants[i].Color_Value_Id);
        }
    }
}

/**
 * Sizes OR Colors Exist
 */
function update_availability() {
    var size = null;
    var color = null;

    var availability = null;
    var a_el = document.getElementById('availability');

    clearTimeout(pulse_events['availability']);

    if (document.getElementById('size')) {
        var s_el = document.getElementById('size');
        size = (s_el.options[s_el.selectedIndex].value == '') ? null: s_el.options[s_el.selectedIndex].value;
    }

    if (document.getElementById('color')) { // Color dropdown exists
        var c_el = document.getElementById('color');
        color = (c_el.options[c_el.selectedIndex].value == '') ? null: c_el.options[c_el.selectedIndex].value;
    } else if (document.getElementById('singlecolor')) { // No color dropdown, hidden field
		color = document.getElementById('singlecolor').value;
    }

    if (s_el && c_el) availability = '<a href="javascript:void();" onclick="open_availability_matrix(); return false;" title="\277Qu\351 significa esto?">Verificar la disponibilidad</a>'
    else availability = '&nbsp;<br>';

    for (var i in sProduct.Variants) {
        if (size == sProduct.Variants[i].Size_Value_Id && color == sProduct.Variants[i].Color_Value_Id) {
            if (sProduct.Variants[i].I >= 1) {
                availability = '<a onclick="return SEI_createWindow(\'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsInStock.html\', \'WhatIsInStock\', \'height=315,width=300,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1\');" href="http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsInStock.html" target="_blank">En existencia</a>';
                if (document.getElementById('specialorder')) {
                    document.getElementById('specialorder').style.display = 'none';
                }
            }
            else if (sProduct.Variants[i].S >= 1) {
                availability = '<a onclick="return SEI_createWindow(\'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsSpecialOrder.html\', \'WhatIsSpecialOrder\', \'height=315,width=300,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1\');" href="http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsSpecialOrder.html" target="_blank">Pedido especial</a>';
                if (document.getElementById('specialorder')) {
                    document.getElementById('specialorder').style.display = 'block';
                }
            }
            else if ((sProduct.Variants[i].B >= 1) && (sProduct.Variants[i].P == 0)) {
                availability = '<a onclick="return SEI_createWindow(\'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsBackOrder.html\', \'WhatIsBackOrder\', \'height=315,width=300,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1\');" href="http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsBackOrder.html" target="_blank">Pedido retrasado</a>';
                if (sProduct.Variants[i].Expected_Date != '') {
                    availability += ': Expected in ' + sProduct.Variants[i].Expected_Date + '.';
                }
                if (document.getElementById('specialorder')) {
                    document.getElementById('specialorder').style.display = 'none';
                }
            }
            else if ((sProduct.Variants[i].B >= 1) && (sProduct.Variants[i].P == 1)) {
                availability = '<a onclick="return SEI_createWindow(\'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsPreOrder.html\', \'WhatIsPreOrder\', \'height=315,width=300,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1\');" href="http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsPreOrder.html" target="_blank">Pre-order</a>';
                if (sProduct.Variants[i].Expected_Date != '') {
                    availability += ': Expected in ' + sProduct.Variants[i].Expected_Date + '.';
                }
                if (document.getElementById('specialorder')) {
                    document.getElementById('specialorder').style.display = 'none';
                }
            }
        }
    }

	if (a_el!=null) {
		if (a_el.innerHTML.toLowerCase() != availability.toLowerCase()) {
			a_el.style.visibility = 'hidden';
			a_el.innerHTML = availability;
			if (availability == '&nbsp;<br>' || availability.indexOf('Verificar la disponibilidad') >= 1) a_el.style.visibility = 'visible';
			else pulse_events['availability'] = setTimeout('pulse_value(\'availability\', true, 3);', 500);
		}
	}
}

function authenticateCustomName(input) {
	var Regex = new RegExp("^[A-Za-z .'ÀÁÈÉÍÖÜÑ-]+$");
	var val = input.value;
	if( val != '' &&  !val.match( Regex ) ) {
	var newValue = '';
		alert('Names can only contain the following: letters A – Z, À, Á, È, É, Í, Ö, Ü, Ñ spaces, and special characters dot(.), apostrophe (\'), or hyphen (–).');
		newText = new Array(val.length);
		for (i=0; i<newText.length; i++) {
			if(val.charAt(i).match( Regex )) {
				newText[i] = val.charAt(i);
				}
			}
		newValue = newText.join('');
		input.value = newValue;
		//input.value = '';
  		return false;
 	} else {
		return true;
		}
}

function scrubLetter(v) {
	var Regex = new RegExp("^[A-Za-z .'ÀÁÈÉÍÖÜÑ-]+$");
	if( !v.match( Regex ) ) {
		newText = new Array(v.length);
		for (i=0; i<newText.length; i++) {
			if(v.charAt(i).match( Regex )) {
				newText[i] = v.charAt(i);
				}
			}
		newValue = newText.join('');
		return newValue;
		} else {
		return v;
		}
}

function authenticateCustomNumber(input) {
	var Regex = new RegExp("^[0-9]+$");
	var val = input.value;
	if( val != '' && !val.match( Regex ) ) {
  		alert('Los n\372meros s\363lo pueden contener los n\372meros 0-99');
		newText = new Array(val.length);
		for (i=0; i<newText.length; i++) {
			if(val.charAt(i).match( Regex )) {
				newText[i] = val.charAt(i);
				}
			}
		newValue = newText.join('');
		input.value = newValue;
		//input.value = '';
  		return false;

 	} else {
		return true;
		}
}

function scrubNumber(v) {
	var Regex = new RegExp("^[0-9]+$");
	if( !v.match( Regex ) ) {
		newText = new Array(v.length);
		for (i=0; i<newText.length; i++) {
			if(v.charAt(i).match( Regex )) {
				newText[i] = v.charAt(i);
				}
			}
		newValue = newText.join('');
		return newValue;
		} else {
		return v;
		}
}

function CharacterCounter(element_name, max) {
    element = document.forms['OrderByVariantSimple'].elements[element_name];
    if (element.value.indexOf('\r\n') >= 0) {
        element.value = element.value.replace(/\r\n/g, '<br />');
    }

    if (element.value.length > max) {
        element.value = element.value.substring(0, max);
    }
    else {
        document.getElementById(element_name + 'Counter').innerHTML = (max - element.value.length) + ' caracteres disponibles';
    }
}

var pulse_events = new Array();

function pulse_value(object, visible, repeat) {
    if (repeat > 0) {
        if (visible) document.getElementById(object).style.visibility = 'visible';
        else document.getElementById(object).style.visibility = 'hidden';
        pulse_events[object] = setTimeout('pulse_value(\'' + object + '\', ' + !visible + ', ' + (--repeat) + ');', 500);
    }
}

function addslashes(str) {
	//example: addslashes("kevin's birthday"); returns 1: 'kevin\'s birthday'
    return (str + "").replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}

$('.name').live('keyup', function(event) {
	var cleanIt = scrubLetter($(this).val());
	$(this).val(cleanIt);
});

$('.number').live('keyup', function(event) {
	var cleanIt = scrubNumber($(this).val());
	$(this).val(cleanIt);
});

/////////////////////////////////////////////////////////////////////
//BEGIN Product-page multi-add functions

//These vars are defined globally and are used to keep track of last matrix quantity entered
//These needs to be global so that they works inside and outside of document.ready / jquery
var lastMatrixQty;

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) {
		return null;
	}
}

function toggle_matrix(mode) {
	var $radios = $('input:radio[name=bundle-customization]');
	// Single size add
	if (mode==0) {
		$("#prodVariants_matrix").hide('r\341pido');
		$("#prodVariants").show('r\341pido');
		$("#MultiAdd").val('0');
		//Force to No if multi-add mode
		if($("#size").val()=='') {
			$radios.filter('[value=No]').attr('revisado', true);
			$("#bundle-section").hide('r\341pido');
		} else {
			$("#bundle-section").show('r\341pido');
		}
	// Multiple size add
	} else if (mode==1) {
		$("#bundle-section").hide('r\341pido');
		$("#prodVariants").hide('r\341pido');
		$("#prodVariants_matrix").show('r\341pido');
		$("#MultiAdd").val('1');
		//Force to Yes if multi-add mode
		$radios.filter('[value=Yes]').attr('revisado', true);
	}
}

function ValidateCustomizationNonClub (Parameter) {
	//var clubCookie = Get_Cookie('Club');
	var multi_add = document.getElementById('MultiAdd');
	var cust = $('input:radio[name=Customize]:checked');
	var custVal = $('input:radio[name=Customize]:checked').val().toLowerCase();
	var custStyle = $('input:radio[name=Package_Name]:checked');
	var custStyleChecked = $('input:radio[name=Package_Name]').attr('revisado');
	var nameVisible = $('.name').parent().parent().css('display');
	var numVisible = $('.number').parent().parent().css('display');
	var emptyName = 0;
	var emptyNumber = 0;
	var someEmptyPlayerFlag = 0;
	var invalidPlayerNumber = 0;
	//var nameInputId = '';
	var numberInputId = '';
	var reInt = new RegExp(/^\d+$/);
	
	if(multi_add.value=='0')
	{
		if(custVal=='yes')
		{
			if(custStyleChecked==false) {
				alert("Debes seleccionar un estilo de personalizaci\363n para este art\355culo.");
				return false;
			} else if(nameVisible=='none' && numVisible=='none') {
				//alert('got here');
				cust.click();
				custStyle.click();
				//alert("You must select a customization style for this item.");
				//return false;
			}
			
			if(nameVisible=='block' || numVisible=='block') {
				$('.name').each(function(){
					if ($(this).val()==''){
						emptyName = 1;
						//if (nameInputId=='')
						//	nameInputId = $(this).attr('id');
					}
				});
				
				$('.number').each(function(){
					if ($(this).val()=='')
						emptyNumber = 1;
					var playerNum = parseInt($(this).val());
					if (!reInt.test(playerNum) || playerNum < 0) {
						invalidPlayerNumber = 1;
						if (numberInputId=='')
							numberInputId = $(this).attr('id');
					}
				});
				
				if(emptyName==1 && emptyNumber==1) {
					alert("Debes especificar los detalles de personalizaci\363n (nombre y/o n\372mero) para este art\355culo.");
					//document.getElementById(playerInputId).focus();
					//ret = ret && false;
					return false;
				} else if(emptyNumber==0 && invalidPlayerNumber==1) {
					alert("Los n\372meros s\363lo pueden contener los n\372meros 0-9.");
					document.getElementById(numberInputId).focus();
					//ret = ret && false;
					return false;
				}
			}
				//}
			//}
		}
		$('#prodVariants_matrix').remove();
		return validateQTY(Parameter);
	} else if (multi_add.value=='1') {
		if(CheckCustomizationQuantity_multi() && removeEmptyFormElements_matrix()){ // version to remove empty form elements
			return true;
		} else {
			return false;
		}
	}
}

function CheckCustomizationQuantity_multi() {
/* Check if an element has quantity entered and if it's customizable
*  that the customization has been entered.
*/
	var ret = true;
	var reInt = new RegExp(/^\d+$/);
	var allEmptyQtyFlag = 1;
	var someEmptyPlayerFlag = 0;
	var invalidQtyFlag = 0;
	var invalidPlayerNum = 0;
	var qtyInputId = $(".player_quantity_field_matrix").first().attr('id');
	var playerInputId = '';
	$(".player_quantity_field_matrix").each(function(i){
		var q = parseInt($(this).val());
		if (!reInt.test(q) || q==null || q < 0) {
			invalidQtyFlag = 1;
			qtyInputId = $(this).attr('id');
		} 
		else if (q > 0) {
			allEmptyQtyFlag = 0;
			var pid = $(this).attr('id').substring(8);
			var r = '#roster-'+pid;
			if ($(r)!=null){
				$(r+" > .player_matrix > .player_inputs > .player_field > ingresa").each(function(){
					if ($(this).val()==''){
							someEmptyPlayerFlag = 1;
							if (playerInputId=='')
								playerInputId = $(this).attr('id');
					}
					else if ($(this).attr('clase')=='n\372mero') {
						var playerNum = parseInt($(this).val());
						if (!reInt.test(playerNum) || playerNum < 0) {
							invalidPlayerNum = 1;
							if (playerInputId=='')
								playerInputId = $(this).attr('id');
						}
					}
				});
			}
		}
	});
	
	//If both empty flags are true, show required alert
	if(invalidQtyFlag==1) {
		alert("Has ingresado una cantidad no v\341lida.");
		ret = ret && false;
		return false;
	}
	else if(allEmptyQtyFlag==1) {
		alert("Debes ingresar una cantidad por al menos un tama\361o.");
		ret = ret && false;
		return false;
	}
	else if(invalidPlayerNum==1) {
		alert("Los n\372meros s\363lo pueden contener los n\372meros 0-9.");
		document.getElementById(playerInputId).focus();
		ret = ret && false;
		return false;
	}
	else if(someEmptyPlayerFlag==1) {
		alert("Debes ingresar los detalles de personalizaci\363n (nombre/n\372mero) por cada art\355culo.");
		document.getElementById(playerInputId).focus();
		ret = ret && false;
		return false;
	}
	return ret;
}

function removeEmptyFormElements_matrix(){
/* Remove empty quantity and supporting roster inputs */
var lastQtyDivId = '';
var lastRemovedQtyDivId = '';
	$(".player_quantity_field_matrix").each(function(){
		var pid = $(this).attr('id').substring(8);
		var qtyDivId = '#Quantity'+pid+'Div';
		if($(this).val()=='' || $(this).val()=='0'){
			$(qtyDivId).remove();
			lastRemovedQtyDivId = '#'+qtyDivId;
		}
		lastQtyDivId = qtyDivId;
	});
	if(lastQtyDivId!=lastRemovedQtyDivId)
		$(lastQtyDivId).addClass('bottomBorder');
	return true;
}

function findEmptyFormElements(frmId) {
	var elem = document.getElementById(frmId).elements;
	var index = elem.length-1;
	for(var i = index;i >= 0; i--){
		if(elem[i] && elem[i].name == 'Cantidad' && elem[i].value == 0){
			var pid = elem[i].id.substring(8);
			removeFormElement('Product_Id'+pid);
			removeFormElement('Club_Template_Product_Id'+pid);
			removeFormElement('Cantidad'+pid);
			
		}
	}
}

function removeFormElement(elId) {
	if(document.getElementById(elId) != null){
		document.getElementById(elId).parentNode.removeChild(document.getElementById(elId));
	}
}

function previewSingleTeam_matrix(bundleId, productId, player, roster, clubFlag) {
	var theName = 'MUESTRA';
	var theNumber = 10;
	var color = '';

	/**
	 * If the optional parameter, player, exists and is an HTML node
	 * (typeof "object" in JavaScript), override the default name and
	 * number values.
	 */
	var linkId = '#'+player;
	var rosterId = '#'+roster;
	var playerDivId = $(linkId).parent().parent().parent().attr('id');
	var rosterDivId = $(rosterId).attr('id');
	var nameNumberDivId = '';
	var err = '';
	
	$("#"+rosterDivId+" > #"+playerDivId+" > .player_inputs > .player_field > ingresa").each(function(j) {
		if ($(this).attr('clase')=='nombre' || $(this).attr('clase')=='name_matrix') {
			if ($(this).val()=="") {
				err = 'nombre';
				if(nameNumberDivId=='')
					nameNumberDivId = $(this).attr('id');
				//break;
			} else {
				var validName = authenticateName($(this).val());
				if(validName){
					theName = $(this).val();
					//break;
				} else{
					if(nameNumberDivId=='')
						nameNumberDivId = $(this).attr('id');
					return false;
				}
			}
		} else if ($(this).attr('clase')=='n\372mero' || $(this).attr('clase')=='number_matrix') {
			if ($(this).val()=="") {
				err = (err!=''?'nombre y n\372mero':'n\372mero');
				if(nameNumberDivId=='')
					nameNumberDivId = $(this).attr('id');
				//break;
			} else {
				var validNumber = authenticateNumber($(this).val());
				if(validNumber){
					theNumber = $(this).val();
					//break;
				} else{
					err = (err!=''?'nombre y n\372mero':'n\372mero');
					if(nameNumberDivId=='')
						nameNumberDivId = $(this).attr('id');
					return false;
				}
			}
		}
	});
	
	if(err!=''){
		alert("Ingresa un "+err+" para previsualizar la personalizaci\363n.");
		document.getElementById(nameNumberDivId).focus();
		return false;
	}
	
	if($('#color').length >= 1)
	{
		color = ($('#color').val()=='') ? null : $('#color').val();
		var jerseyColor = $('#color option:selected').text();
	} else if ($('#singlecolor').length >= 1) {
		if($('#singlecolor').val()=='')
			color = null;
		else
			color = $('#singlecolor').val();
		var jerseyColor = $('#selectedsinglecolor_matrix').html();
	}
	var q = 0;
	
	if(color) {
		for(i in sProduct.Variants)
		{
			if(color == sProduct.Variants[i].Color_Value_Id)
			{
				color_code = sProduct.Variants[i].Color_Code;
				break;
			}
		}
	} else {
		for(i in sProduct.Variants)
		{
			if(q <= sProduct.Variants[i].I)
			{
				q = sProduct.Variants[i].I;
				color_code = sProduct.Variants[i].Color_Code;
				break;
			}
		}
	}
	
	var ColorSelectID = "bundle-" + bundleId + "-modifier-0-color-option-0";
	var StrokeSelectName = "Paquete" + bundleId + "StrokeColor";
	var FillSelectName = "Paquete" + bundleId + "FillColor";
	
	if (typeof document.getElementsByName(FillSelectName)[0] != 'undefined') {
		var fillColor = document.getElementsByName(FillSelectName)[0].value;
	} else {
		var fillColor = '';
	}
	if (document.getElementsByName(StrokeSelectName).length>0) {
		var strokeColor = document.getElementsByName(StrokeSelectName)[0].value;
	} else {
		var strokeColor = '';
	}

	var previewPopup = window.open('/jerseycustomization/PreviewSingleTeam.php5?id='
	+ bundleId + '&name=' + theName + '&number=' + theNumber + '&productId=' +
	productId + '&fillColor=' + fillColor + '&strokeColor=' + strokeColor + '&jerseyColor=' + color_code +
	'&size=600&orientation=front&clubFlag=' + clubFlag, 'vista previa',
	'width=400,height=400,toolbars=no');
	previewPopup.focus();
}
//END Product-page multi-add functions

$(document).ready(function() {
	//Update product sizing customer callouts for classic view
	$('#sizeStatus, #widthStatus').live('cambiar', function() {
		var choiceVal = $(this).val();
		var dropDownName = $(this).attr('nombre');
		setCookie('CustomerSizingChoice', choiceVal, 3650);
		if(choiceVal!='Los clientes' && choiceVal!='Todos'){
			$('#starText').addClass('heroStarText');
		} else {
			$('#starText').removeClass('heroStarText');
		}
		$('#starText').show('r\341pido');
		update_by_reviewer_status(choiceVal, dropDownName);
	});
});
