function change_case(form_object) {
	form_object.logonUsername.value = form_object.logonUsername.value.toLowerCase();
	return true;
}

function popUp(url) {
	sealWin=window.open(url,"win",'toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=500,height=450');
	self.name = "mainWin";
}

function ChangeAddressOption() {
	if(document.forms[document.forms.length - 1].elements.ShippingAddressOption)
	{
		if(document.forms[document.forms.length - 1].elements.ShippingAddressOption.length)
		{
			document.forms[document.forms.length - 1].elements.ShippingAddressOption[document.forms[document.forms.length - 1].elements.ShippingAddressOption.length - 1].checked = 'true';
		}
	}
}

function ChangePaymentOption(elementID) {
	document.getElementById(elementID).checked = 'true';
}

function getdigits(s) {
   return s.replace (/[^\d]/g, '');
}

function valPayment(thisform) {
	if(typeof(thisform.PaymentOption.length)!=='undefined'){
		myOption = -1;
		for (i=thisform.PaymentOption.length-1; i > -1; i--) {
			if (thisform.PaymentOption[i].checked) {
				myOption = i; i = -1;
			}
		}
		pmt_option_id = thisform.PaymentOption[myOption].value;
	} else {
		pmt_option_id = -1;
	}

	if(pmt_option_id == '-1' && (parseFloat(thisform.RemainingBalance.value) >= 0.01) && thisform.GiftCardNumber.value=='') {
		/*  
		*	There is only one selection (no saved cards) OR they selected to enter new card data
		*	AND remaining balance >= 0
		*	AND no gift card filled in.
		*/
		if(!checkPaymentType(thisform) || !isNotBlank('N\372mero de tarjeta de cr\351dito',thisform.CreditCardNumber,thisform.CreditCardNumber.value) || !isNotBlank('Identificaci\363n de la tarjeta de cr\351dito',thisform.CreditCardId,thisform.CreditCardId.value) || !checkExpiration(thisform) || !isNotBlank('Nombre del titular de la tarjeta',thisform.Name, thisform.Name.value)){
			return false;
		} else {
			thisform.CreditCardNumber.value = getdigits(thisform.CreditCardNumber.value);
			if(thisform.CreditCardNumber.value.length < 15 || !ccLuhn(thisform.CreditCardNumber.value)) {
				alert("El n\372mero de tu tarjeta de cr\351dito es inv\341lido.");
				thisform.CreditCardNumber.focus();
				return false;
			} else {
				if(thisform.SameAsShippingAddress.checked==false) {
					// validate shipping address 
					if(!isNotBlank('Direcci\363n de facturaci\363n l\355nea 1',thisform.Address1,thisform.Address1.value) || !isNotBlank('Ciudad',thisform.City,thisform.City.value) || !isNotBlank('State/Province/Region',thisform.ProvinceCode,thisform.ProvinceCode.value) || !isNotBlank('C\363digo Postal',thisform.PostalCode,thisform.PostalCode.value) || !checkCountry(thisform) || !isNotBlank('Tel\351fono de facturaci\363n',thisform.BillingPhone,thisform.BillingPhone.value) || !isNotBlank('Email',thisform.EmailAddress,thisform.EmailAddress.value)) {
						return false;
					} else {
						if(!isValidEmailAddress(thisform.EmailAddress.value)){
							alert(thisform.EmailAddress.value+' no es una direcci\363n de email v\341lida. Por favor rev\355sala.');
							thisform.EmailAddress.focus();
							} else {
								thisform.submit();
								}
					}
				} else {// SameAsShippingAddress checked
				thisform.submit(); // this line submits the form after validation
				}
			}
		} 
	} else { // Check to see if they left the CCID field blank on a saved CC
		var id = pmt_option_id;

		var fieldname = 'SavedCreditCardId_'+id;
		var field = document.getElementsByName(fieldname);
		if((parseFloat(thisform.RemainingBalance.value) >= 0.01) && thisform.GiftCardNumber.value==''){ // Not using a GC
			if(isNotBlank('Identificaci\363n de la tarjeta de cr\351dito', field[0], field[0].value)){ //CCID empty?
				thisform.submit();	
			}
		} else {
			thisform.submit();
		}
	}
}

function checkPaymentType(thisform) {
	var myindex=thisform.CardType.selectedIndex;
	if (myindex==0) {
		alert("Debes seleccionar un tipo de pago.");
		thisform.CardType.focus();
		return false;
		} else {
			return true;
	   }
}

function checkCountry(thisform) {
	var myindex=thisform.CountryName.selectedIndex;
	if (myindex==0) {
		alert("Debes seleccionar un pa\355s.");
		thisform.CountryName.focus();
		return false;
		} else {
			return true;
	   }
}

function checkExpiration(thisform) {
	var i_1=thisform.ExpirationMonth.selectedIndex;
	var i_2=thisform.ExpirationYear.selectedIndex;
	if (i_1==0 || i_2==0) {
		alert("Debes seleccionar una fecha de vencimiento v\341lida.");
		thisform.ExpirationMonth.focus();
		return false;
		} else {
			return true;
	   }
}

function isNotBlank(fieldName, field, value) {
	if(value==null || value==""){
		alert("Debes completar "+fieldName);
		field.focus();
		return false;
	} else {
		return true;
	}
}

function ccLuhn(cc) {
    // digits 0-9 doubled with nines cast out
    var doubled = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];

    // remove non-digit characters
    cc = cc.replace(/[^\d]/g,'');
    var digits = cc.split('');

    // alternate between summing the digits
    // or the result of doubling the digits and
    // casting out nines (see Luhn description)
    var alt = false;
    var total = 0;
    while (digits.length) {
        var d = Number(digits.pop());
        total += (alt ? doubled[d] : d);
        alt = !alt;
    }
    return total % 10 == 0;
}

function PopulateProvince(Field, State) {
	opener.document.forms[opener.document.forms.length - 1].elements[Field].value = State;
	self.close();
}

//Popup Window for Free Shipping Restrictions
function open_freeshipping(){
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/freeshipping.html', 'FreeShipping', 'height=260,width=300,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1');
}

//Popup Window for Shipping Source Explanations
function open_whatis_instock(){
	window.open('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');
}

function open_whatis_specialorder(){
	window.open('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');
}

function open_specialorder_deadlines(){
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/CheckVendorCutoffDate.process', 'WhatIsSpecialOrder', 'height=200,width=480,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1');
}

function open_whatis_backorder(){
	window.open('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');
}

function open_whatis_preorder(){
	window.open('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');
}

function open_club_status(statusCode){
	switch(statusCode) {
		case 'InStock':
			window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsClubInStock.html', 'WhatIsClubInStock', 'height=315,width=300,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1');
			break;
		case 'SpecialOrder':
			window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/WhatIsClubSpecialOrder.html', 'WhatIsClubSpecialOrder', 'height=315,width=300,resizable=0,status=0,menubar=0,toolbar=0,scrollbars=1');
			break;
	}
}

function EstimateShipping()
{
	var Shipping_Method_Id = document.forms.shipping.Shipping_Method_Id[document.forms.shipping.Shipping_Method_Id.selectedIndex].value;
	var Postal_Code = document.forms.shipping.Postal_Code.value;
	if(Postal_Code == '')
	{
		alert('Por favor ingresa tu C\363digo Postal en el espacio que aparece.');
	} else {
		window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/javascript/OM/ShippingEstimator.process?Shipping_Method_Id=' + Shipping_Method_Id + '&Postal_Code=' + Postal_Code + '&OnlyGC=0', 'ShippingEstimator', 'height=140,width=300,resizable=1,status=0,menubar=0,toolbar=0,scrollbars=0');
	}
}

function copyCatalogSourceCode()
{
	var sourcecode = document.placeOrder2.CatalogSourceCode.value;
	document.placeOrder.CatalogSourceCode.value = sourcecode;
}

function AddBILBtoGearbag(val)
{
	document.forms['GearBag'].elements['BILB'].value = val;
	document.forms['GearBag'].submit();
}

//Customization Code

function showCustomizations(customizations)
{
	var rio = customizations;
	rio = rio.split(",");
	if(rio[8] == "--------"){ rio[8] = "NIKE SWOOSH"; }
	else{ rio[8] += "\t"; }
	rio[8] = rio[8].replace(/-/g, " ");
	rio[5] = rio[5].replace(/-/g, " ");
	switch(rio[2])
	{
		case '117423': rio[2] = 'Material: PIEL DE NAPA DE LA M\301S ALTA CALIDAD\tZoom Air: SIN AIRE'; break;
		case '117424': rio[2] = 'Material: GRANO ENTERO\tZoom Air: AIRE EN EL TAL\323N'; break;
		case '117425': rio[2] = 'Material: GRANO ENTERO\tZoom Air: HEEL Y FF AIR'; break;
		case '117426': rio[2] = 'Material: MICROFIBRA\tZoom Air: SIN AIRE'; break;
		case '117427': rio[2] = 'Material: MICROFIBRA\tZoom Air: AIRE EN EL TACO'; break;
		case '117428': rio[2] = 'Material: MICROFIBRA\tZoom Air: AIRE EN EL TACO Y FF'; break;
		case '117429': rio[2] = 'Material: CANGURO\tZoom Air: SIN AIRE'; break;
		case '117430': rio[2] = 'Material: CANGURO\tZoom Air: AIRE EN EL TALON'; break;
		case '117431': rio[2] = 'Material: CANGURO\tZoom Air: AIRE EN EL TACO Y FF'; break;
	}
	alert("Tus Adaptaciones (Talla " + rio[4] + ")\n\n" + rio[2] + "\nPrimary iD: " + rio[8] + "\tSecondary iD: " + rio[5] + "\nColor: " + rio[13] + "\t\tOutsole: " + rio[29]);
}

// BEGIN PRODUCT PAGE SPECIFICS

function SEI_createWindow(url, name, options) {
	if(url) {
		var w = window.open(url, name, options);
		w.focus();
		return false;
	} else
		return false;
}

function view360(product, winType) {
	var pageLoc;
	if(winType == '360') 
		pageLoc	= "/360/"+product+"/"+product+".html";
	if(winType == 'video')
		pageLoc	= "http://videos.soccer.com/prod_vids.php?pc="+product+"&res=lo";
	if(winType == '')
		pageLoc	= "/360/"+product+"/"+product+".html";
	window.open(pageLoc,"360","toolbar=0,statusbar=0,menubar=0,width=500,height=400");
}

function viewVideo(product, winType) {
	var pageLoc;
	if(winType == '360') 
		pageLoc	= "/360/"+product+"/"+product+".html";
	if(winType == 'video')
		pageLoc	= "http://videos.soccer.com/prod_vids.php?pc="+product+"&res=lo";
	if(winType == '')
		pageLoc	= "/360/"+product+"/"+product+".html";
	window.open(pageLoc,"360","toolbar=0,statusbar=0,menubar=0,width=660,height=410");
}

function dictionaryWindow(DictionaryID) {
	var dictionaryLink = "http://www.soccer.com/dictionary/definition.php?dictionaryID=" + DictionaryID;
	window.open(dictionaryLink, 'dictionary_window','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,height=200,width=220');
}

function display_tab(tab) {
	document.getElementById('itemDetails').style.display = 'none';
	document.getElementById('itemReviews').style.display = 'none';
	document.getElementById(tab).style.display = 'block';
}

function imagePop (url, name, options) {
	var w = window.open(url, name, options);
	w.focus();
	return false;
}

// Function that will swap the display/no display for large callout images

function showCallout(index) {
	var d, i=0;
	while (d = document.getElementById('display' + (i))) {
		d.style.display = 'none';
		document.getElementById('imageClose' + i).style.display = 'none';
		i++;
	}
	document.getElementById('display' + index).style.display = 'block';
	document.getElementById('imageClose' + index).style.display = 'block';
}

function validateQTY(qty_object) {
	if(typeof(qty_object) === 'undefined')
		qty_object = document.OrderByVariantSimple.OMQuantity;
	
	qty_value = qty_object.value.replace(/\D/g, '');
	if(qty_value == "" || qty_value == 0){ qty_value = 1; }
	qty_object.value = qty_value;

	var error = false;

	if(document.getElementById('size')){
		if(document.getElementById('size').options[document.getElementById('size').selectedIndex].text == 'Elije'){
			error = true;
		}
	}

	if(document.getElementById('color')){
		if(document.getElementById('color').options[document.getElementById('color').selectedIndex].text == 'Elije'){
			error = true;
		}
	}

	if(error){
		alert('Debes elegir una talla y/ o color para adquirir este art\355culo.');
	}
	return !error;
}

function change_case(form_object) {
	form_object.logonUsername.value = form_object.logonUsername.value.toLowerCase();
	return true;
}

function writeDate() {
	ddate = new Date();
	day = ddate.getDay();
	date = ddate.getDate();
	month = ddate.getMonth();
	year = ddate.getYear();
	if(year < 1900){ year = year + 1900; }
	var days = new Array("Dom","Lun","Mar","Mi\351","Jue","Vie","S\341b");
	var months = new Array("Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic");
	document.write(days[day]+", "+months[month]+" "+date+", "+year);
}

// This function was created to apply a Gift Card on the Payment page
function ApplyGiftCard() {
	document.location = "http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/PlaceOrder.process?GiftCardNumber=" + document.forms.payment.GiftCardNumber.value + "&GCRecipientName=" + document.forms.payment.GCRecipientName.value +"&GiftCardAction=Apply&IWPEProcessFlow.submitted.sequenceID=" + document.forms.payment.sequenceID.value;
	return true;
}

function checkGiftCardBalance() {
	var GiftCardNumber = document.forms.payment.GiftCardNumber.value;
	var PIN = document.forms.payment.PIN.value;
	if(GiftCardNumber == '')
	{
		alert('Por favor ingresa el N\372mero de Tarjeta de Regalo');
	} else {
		window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/javascript/OM/GiftCardBalance.process?GiftCardNumber=' + GiftCardNumber + '&PIN=' + PIN, 'GiftCardBalance', 'height=80,width=370,resizable=1,status=0,menubar=0,toolbar=0,scrollbars=0');
	}
}

function toggle_visibility(display_block) {
	if (document.getElementById(display_block).style.display == "block")
	 document.getElementById(display_block).style.display="none";
	else
	 document.getElementById(display_block).style.display = "block";
}

function showZones() {
	//window.open('/shipmapholiday.html', 'window', 'top=15,left=15,width=640,height=520,statusbar=0,toolbar=0,resizable=1');
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/shipmapsmall.html', 'window', 'top=15,left=15,width=640,height=455,statusbar=0,toolbar=0,resizable=1');
}

function nikeGinga() {
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/channels/features/nike_ginga/index.html', 'window', 'top=0,left=15,width=980,height=700,statusbar=0,toolbar=0,resizable=1');
}

/* Customization JavaScript */

function iconPop() {
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/channels/customize/iconpop.html', 'window', 'top=15,left=15,width=750,height=550,scrollbars=1,statusbar=0,toolbar=0,resizable=0'); 
}

function JerseyStylePop() {
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/channels/customize/jerseystylepop.html', 'window', 'top=15,left=15,width=750,height=600,scrollbars=0,statusbar=0,toolbar=0,resizable=1'); 
}

function JerseyStyleAuthPop() {
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/channels/customize/jerseystyleauthpop.html', 'window', 'top=15,left=15,width=380,height=585,scrollbars=0,statusbar=0,toolbar=0,resizable=1'); 
}

function JerseyStyleBasicPop() {
	window.open('http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/channels/customize/jerseystylebasicpop.html', 'window', 'top=15,left=15,width=380,height=585,scrollbars=0,statusbar=0,toolbar=0,resizable=1'); 
}

/* Cookie Functions */

function setCookie(name, value, days) {
	if(!days)
		days=null;
	var expires = '';
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 *60 * 60 * 1000));
		expires = '; expires=' + date.toGMTString();
	}
	document.cookie = name + '=' + value + expires + '; path=/';
}

function getCookie(name) {
	var name = name + '=';
	var cookies = document.cookie.split(';');
	for (var i=0; i < cookies.length; i++) {
		var c = cookies[i];
		while (cookies[i].charAt(0) == ' ') {
			cookies[i] = cookies[i].substring(1, cookies[i].length);
		}
		if (cookies[i].indexOf(name) == 0) {
			return cookies[i].substring(name.length, cookies[i].length);
		}
	}
	return null;
}

function deleteCookie (name) {
	setCookie(name, '', -1);
}

function changeSizeOptInSearch (newValue) {
	var sizeOpt = document.getElementsByName("SizeOpt")
	sizeOpt[newValue].checked = true;
}

/* end Cookie Functions */

/**
 * toggleElement
 *
 * @param element	the element on the page to toggle
 * @param maximize	(optional) force minimize or maximize
 */
function toggleElement(element /*, maximize*/) {
	if (element === null) {
		return;
	}

	var maximize = (element.style.display === 'none');
	/**
	 * If the optional parameter maximize is a boolean, override the
	 * calculated action.
	 */
	if (typeof arguments[1] === 'boolean') {
		maximize = arguments[1];
	}

	/**
	 * Show or hide the element depending on what action is needed (or
	 * was specified).
	 */
	if (maximize) {
		element.style.display = 'block';
	} else {
		element.style.display = 'none';
	}		
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function trim(str){
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

var CardNameTested = 0;	
function hasNumbers(s, field) {
	var re = new RegExp(/[\d]/);
	if(!CardNameTested && re.test(s)){
		if(confirm("El campo \042titular de la tarjeta\042 tiene un n\372mero. \277Es eso lo que quisiste decir?\n\n\tHaz clic en \042OK\042 si quieres mantener el n\372mero all\355,\n\Haz clic en \042Cancelar\042 si quieres corregirlo.")){
			CardNameTested = 1;
			return true;
		} else {
			field.value = s.replace (/[\d]/g, '');
			field.focus();
			return false;
		}
	}
}
