/**
 * Funci�n encargada de cargar el id del Price Plan y enviar el formulario
 */
var submitSelectPricePlanForm = function() {
	$("#selectPricePlanForm").submit();
}

/**
 * Funci�n que carga los datos del terminal seleccionado
 */
 // Variables auxiliares
var flagIsVersionSelected = false;
var selectedPartialURL = '';

var selectHandset = function(partialURL, handsetCode, handsetDescription, handsetPrice, handsetColor, handsetGiftWithPortability, handsetGiftWithoutPortability) {
	flagIsVersionSelected = true;
	selectedPartialURL = partialURL;
	$("#handsetCode").val(handsetCode);
	$("#handsetDescription").val(handsetDescription);
	$("#handsetPrice").val(handsetPrice);
	$("#handsetColor").val(handsetColor);
    $("#handsetGiftWithPortability").val(escape(handsetGiftWithPortability));
    $("#handsetGiftWithoutPortability").val(escape(handsetGiftWithoutPortability));
}

/**
 * Funci�n enviar el formulario de selecci�n de handset
 */
var submitSelectHandsetForm = function(partialURL, handsetCode, handsetDescription, handsetColor, handsetGiftWithPortability, handsetGiftWithoutPortability) {
	if ((flagIsVersionSelected && selectedPartialURL != '' && partialURL != selectedPartialURL) || !flagIsVersionSelected) {
		// El usuario ha seleccionado una versi�n y luego ha dado al bot�n comprar de otro m�vil o no ha seleccionado versi�n -> sobreescribe
		$("#handsetCode").val(handsetCode);
		$("#handsetDescription").val(handsetDescription);
		//$("#handsetPrice").val(handsetPrice);
        $("#handsetColor").val(handsetColor);
        $("#handsetGiftWithPortability").val(escape(handsetGiftWithPortability));
        $("#handsetGiftWithoutPortability").val(escape(handsetGiftWithoutPortability));
    }
	
	// Restauramos los valores iniciales
	flagIsVersionSelected = false;
	selectedPartialURL = '';	

	// Enviamos el formulario
	$("#selectHandsetForm").submit();
}

/*
 * Funci�n que realiza la petici�n para cargar los datos de cuenta asociados al msisdn
 */
var submitAccountInfoForm = function(msisdn, accountType) {
	if (msisdn != "" ) {
		// Cargamos los datos
		$("#msisdn").val(msisdn);
		$("#accountType").val(accountType);
		// Enviamos el formulario
		$("#accountInfoForm").submit();
	} else {
		if (accountType == 1) {
			$("#accountInfoPrepaidForm").clearForm();
			$("#payment_type_prepaid").attr("checked", "checked");
		} else {
			$("#accountInfoPostpaidForm").clearForm();
			$("#payment_type_postpaid").attr("checked", "checked");
		}
		
	}
}

var submitSuggestNumberForm = function() {
	$('#partialMsisdn').val($('#selected_digits').val());
	$('#suggestNumberForm').submit();
}

var submitSelectNumberForm = function() {
	if (document.getElementById("number_type_portabilidad").checked == true) {
		if (validateSelectPortabilityNumberForm(document.getElementById('selectPortabilityNumberForm'))) {
			document.getElementById('selectPortabilityNumberForm').submit();
		}
		
	} else if (document.getElementById("number_type_nuevo").checked == true) {
		if (validateSelectNumberForm(document.getElementById('selectNumberForm'))) {
			document.getElementById('selected_phone_number').value = document.getElementById('selected_phone_number').value;
			$('#selectNumberForm').submit();
		}
	}
}

var submitAccountInfoPrepaidForm = function(){
	var retorno = validateAccountInfoPrepaidForm(document.getElementById('accountInfoPrepaidForm'));
	if (retorno)
		$('#accountInfoPrepaidForm').submit();
}


var submitAccountInfoPostpaidForm = function(){
	var retorno = validateAccountInfoPostpaidForm(document.getElementById('accountInfoPostpaidForm'));
	if (retorno)
		$('#accountInfoPostpaidForm').submit();
}

var submitMisRecomendadosForm = function(){
	//var retorno = validateMisRecomendadosForm($('#misRecomendadosForm'));
		$('#misRecomendadosForm').submit();
}

var submitFriendsAndFamilyForm = function(){
	//var retorno = validateMisRecomendadosForm($('#misRecomendadosForm'));
		$('#friendsAndFamilyForm').submit();
}
/*
 * Funci�n encargada de poner en blanco el formulario de datos de cobro cuando el usuario va a actualizarlos
 */
var clearMisDatosAccountInfoForm = function() {
	if ($('#isUpdating').val() == 'false') {
		$('#isUpdating').val('true');
		$('#misDatosAccountInfoForm').clearForm();
	}	
}

var clearMisDatosAccountInfoBankDataForm = function() {
	if ($('#isUpdatingBankData').val() == 'false') {
		$('#isUpdatingBankData').val('true');
		$('#misDatosAccountInfoBankDataForm').clearForm();
	}
}

/*
 * Inicio - C�digo de los carruseles de selecci�n de n�meros - The Coktail (lo he sacado de la p�gina porque es un huevo de javascript)
 */
 	function load_carousels() {
		if (!window.carousels_loaded) {
			select_nuevo_numero();
			select_numeros_incluidos();
			window.carousels_loaded = true;			
		}
	}


	function select_nuevo_numero() {
		//separar el array de n�meros en varios arrays para cada fila de n�meros
		max_rows = 3; //m�ximo de filas slider a crear
		items_per_row = 3; //n�mero de items visibles en cada fila slider
		rows = Math.floor(AVAILABLE_NUMBERS.length / items_per_row);
		if (rows > max_rows) {
			rows = max_rows;
		} else if (rows < 1) {
			rows = 1;
		} 

		numbers_per_array = Math.floor(AVAILABLE_NUMBERS.length / rows); //n�mero base de elementos para cada array
		number_pos = 0; //para recorrer el array AVAILABLE_NUMBERS
		for (i=0; i<rows; i++) {
			ROW_NUMBERS[i] = [];
			for (j=0; j<numbers_per_array; j++) {
				ROW_NUMBERS[i][j] = AVAILABLE_NUMBERS[number_pos++];
			}
		}

		//incluimos en la �ltima fila los n�meros restantes si los hay
		rest = AVAILABLE_NUMBERS.length % rows;
		for (k=0; k<rest; k++) {
			ROW_NUMBERS[i-1][ROW_NUMBERS[i-1].length] = AVAILABLE_NUMBERS[number_pos++];
		}

		//generar carruseles
		for (i=0; i<rows; i++) {
			$("#nuevo_numero_content #sliders").append('<ul class="listanumeros jcarousel-skin-tango" id="lista_'+(i+1)+'"></ul>');
		}

		//activar carruseles
   		$('.listanumeros').jcarousel({
			buttonNextHTML: '<a></a>',
			buttonPrevHTML: '<a></a>',
			itemLoadCallback: mycarousel_itemLoadCallback,
			itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) {carousel.remove(i);}}
		});
	}


	function select_numeros_incluidos() {
    $('#first_numbers .numero_incluido a.prev').click(function(){
			set_selected_numbers($(this), 1);
			return false;
		});	
    $('#first_numbers .numero_incluido a.next').click(function(){
			set_selected_numbers($(this), -1);
			return false;
		});	
	}


	function mycarousel_itemLoadCallback(carousel, state)
	{
		// Check if the requested items already exist
		if (carousel.has(carousel.first, carousel.last)) {
			return;
		}

		numbers = get_numbers(carousel.list, carousel.first, carousel.last);
		mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, numbers);
	}


	function mycarousel_itemAddCallback(carousel, first, last, numbers)
	{
		id = get_list_id(carousel.list) - 1;
		
		// Set the size of the carousel
		carousel.size(ROW_NUMBERS[id].length);
		
		for (i=first; i<numbers.length+first; i++) {
			if (carousel.has(i)) continue;
			if (i > ROW_NUMBERS[id].length) break;
			e = carousel.add(i, '<a href="#">'+ROW_NUMBERS[id][i-1]+'</a>');
			e.click(function(){
				$("ul.listanumeros a").attr("class", ""); //desmarcar todos los n�meros
				a = $("a", this).attr("class", "selected"); //marcar n�mero pulsado
				$("input#selected_phone_number").attr("value", '34' + a.html()); //guardar valor en campo oculto
				$("#suggested_number").fadeOut(); //ocultar n�mero sugerido (de los de 4 primeros n�meros)			
			});
		}
	}


	function get_numbers(list, first, last) {
		id = get_list_id(list);
		numbers = [];
		for (i=first; i<=last; i++) {
			numbers[numbers.length] = ROW_NUMBERS[id-1][i-1];
		}
		return numbers;
	}


	//devuelve el identificador num�rico de una lista
	function get_list_id(list) {
		return parseInt($(list).attr("id").split("_")[1]); //obtener el n�mero identificador a partir del id de la lista, que tiene formato "lista_N"
	}


	function set_selected_numbers(item, add) {
		//actualizar n�mero
		number_container = $(item).parent();
		current_value = parseInt($("span", number_container).html());
		new_value = current_value + add;
		if (new_value < 0) {
			new_value = 9;
		} else if (new_value > 9) {
			new_value = 0;
		}
		$("span", number_container).html(new_value+"")
		
		//asignar nuevos 4 n�meros al campo oculto
		number_id = number_container.attr("id"); //item es el li. Accedemos a la lista padre y obtenemos su id
		number_position = parseInt(number_id.split('_')[2]) - 1; //el id tiene el formato 'selected_number_N'. Obtenemos N-1
		current_digits = $("input#selected_digits").attr("value");
		new_digits = "";
		for (i=0; i<4; i++) {
			if (i == number_position) {
				new_digits += new_value;
			} else {
				new_digits += current_digits.charAt(i);				
			}
		}
		$("input#selected_digits").attr("value", new_digits);
	}
	
/*
 * Fin - C�digo de los carruseles de selecci�n de n�meros
 */
 
 
 function checkDC(cc1,cc2,dc){
 
 	// Comprobar que los datos son correctos
 	
 	if (!(cc1.match(/^\d{8}$/) && cc2.match(/^\d{10}$/) && dc.match(/^\d{2}$/) )) return false;

    var arrWeights = new Array(1,2,4,8,5,10,9,7,3,6); // vector de pesos
    var dc1=0, dc2=0;

	
    // C�lculo del primer d�gito de cintrol

    for (i=7;i>=0;i--) dc1 += arrWeights[i+2] * cc1.charAt(i);
    dc1 = 11 - (dc1 % 11);
    if (11 == dc1) dc1 = 0;
    if (10 == dc1) dc1 = 1;


		// C�lculo del segundo d�gito de control

        for (i=9;i>=0;i--) dc2 += arrWeights[i] * cc2.charAt(i);
        dc2 = 11 - (dc2 % 11);
       	if (11 == dc2) dc2 = 0;
        if (10 == dc2) dc2 = 1;


        // Comprobar la coincidencia y delvolver el resultado

        return (10*dc1+dc2 == dc);     // Javascript infiere tipo entero para dc1 y dc2

} // end checkDC()

function checkCardNumWithMod10(cardNum) {
       var i;
       var cc = new Array(16);
       var checksum = 0;
       var validcc;

       // assign each digit of the card number to a space in the array
       for (i = 0; i < cardNum.length; i++) {
               cc[i] = Math.floor(cardNum.substring(i, i+1));
       }

       // walk through every other digit doing our magic
       // if the card number is sixteen digits then start at the
       // first digit (position 0), otherwise start from the
       // second (position 1)
       for (i = (cardNum.length % 2); i < cardNum.length; i+=2) {
               var a = cc[i] * 2;
               if (a >= 10) {
                       var aStr = a.toString();
                       var b = aStr.substring(0,1);
                       var c = aStr.substring(1,2);
                       cc[i] = Math.floor(b) + Math.floor(c);
               } else {
                       cc[i] = a;
               }
       }

       // add up all of the digits in the array
       for (i = 0; i < cardNum.length; i++) {
               checksum += Math.floor(cc[i]);
       }

       // if the checksum is evenly divisble by 10
       // then this is a valid card number
       validcc = ((checksum % 10) == 0);

       return validcc;
}

function cleanCardNum(cardNum) {
       var i;
       var ch;
       var newCard = "";

       // walk through the string character by character to build
       // a new string with numbers only
       i = 0;
       while (i < cardNum.length) {
               // get the current character
               ch = cardNum.substring(i, i+1);
               if ((ch >= "0") && (ch <= "9")) {
                       // if the current character is a digit then add it
                       // to the numbers-only string we're building
                       newCard += ch;
               } else {
                       // not a digit, so check if its a dash or a space
                       if ((ch != " ") && (ch != "-")) {
                               // not a dash or a space so fail
                               return "";
                       }
               }
               i++;
       }

       // we got here if we didn't fail, so return what we built
       return newCard;
}

//validaci�n de tarjeta de cr�dito en base al tipo
//  5  = VISA
//  1  = MASTER CARD
//  2  = AMEX
function checkCard(cardType, cardNum)
{
       var validCard;
       var cardLength;
       var cardLengthOK;
       var cardStart;
       var cardStartOK;

       // check if the card type is valid
       if ( (cardType != "5") && (cardType != "1") && (cardType != "2") )
       {
               return false;
       }

       // clean up any spaces or dashes in the card number
       validCard = cleanCardNum(cardNum);
       if (validCard != "") {
               // check the first digit to see if it matches the card type
               //  5  = VISA
               //  1  = MASTER CARD
               //  2  = AMEX
               cardStart = validCard.substring(0,1);
               cardStartOK = ( ((cardType == "5") && (cardStart == "4")) ||
                               ((cardType == "1") && (cardStart == "5")) ||
                               ((cardType == "2") && (cardStart == "3")) );
               if (!(cardStartOK)) {
                       // card number's first digit doesn't match card type
                       return false;
               }

               // the card number is good now, so check to make sure
               // it's a the right length
               cardLength = validCard.length;
               cardLengthOK = ( ((cardType == "5") && ((cardLength == 13) || (cardLength == 16))) ||
                                ((cardType == "1") && (cardLength == 16)) ||
                                ((cardType == "2") && (cardLength == 15)) );
               if (!(cardLengthOK)) {
                       // not the right length
                       return false;
               }

               // card number seems OK so do the Mod10
               if (checkCardNumWithMod10(validCard)) {
                       return true;
               } else {
                       return false;
               }
       } else {
               return false;
       }
}

/*
*Funcion de tabulacion entre camp�s
*/
function tabBetweenFields(component, componentToTab, numberCharacters){
	if (component.value.length == numberCharacters)
		$(componentToTab).focus();
}

/*
*Funcion de validacion de tarjeta credito
*/
function customValidateCreditCard(creditCardNumber, creditCardType){
	if (checkCard(creditCardType, creditCardNumber))
		return true;
		
	alert('Los datos de tarjeta introducidos no son correctos');
								
    return false;
}