var validNumber = false;
var requestProcessing = false;
var submitForm = false;
var form;
var checked = false;
var con;
var callback;


function startup(){
  obj = document.getElementById('operator');
  var i = obj.selectedIndex;
  if( i!= 0 && obj.value!=1) var color = $("#pgOperatorsHeader li").eq(i-1).css("color");
	else if (obj.value==1) var color = "#ffcc00";
  else var color = "#eee";
	$("#pgContent").animate({ backgroundColor: color }, "normal" );
}


function setGG(){
  document.getElementById('operator').value = 1;
  ChangeOperator(1);
  color = '#ffcc00';
  $("#pgContent").animate({ backgroundColor: color }, "normal" );
}

function setGGAir(){
  document.getElementById('operator').value = 8;
  ChangeOperator(8);
  color = '#ffcc00';
  $("#pgContent").animate({ backgroundColor: color }, "normal" );
}


function isEmail(string) {
  if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
    return true;
  else
    return false;
}

function resetAlerts(){

	tags = document.getElementsByName('validator');
	
	for (i=0;i<tags.length;i++){
	  tags[i].innerHTML = '';
	}
}

function showAlerts(str,name){
	
	var div = document.getElementById("alerts");
	var divAlerts = document.getElementById("divAlerts");
	
	if (str==''){
	  resetAlerts();
	  div.style.display="none";	  
	  if (divAlerts!=null)
        divAlerts.style.display="none";
	  return;
	} 

	var obj = document.getElementById(name+"Validator");
	
	if (obj!=null){
		
		obj.innerHTML = '<div class="tipMsg"><span class="validatorMessage">'+str+'</span><div class="tipMsg">'
	  return;
	}
	
    if (divAlerts!=null)
	  divAlerts.style.display="block";	
	
	div.style.display="block";	
	div.innerHTML = str; 
}


function hideWait(){
	document.getElementById('ver').style.display = "none";
}

function showWait(){
	document.getElementById('ver').style.display = "block";
}

function checkPhoneNumber(f){  
  form = f;
  if (requestProcessing)
    return;

  tel = document.getElementById('telefon').value;
  operator = document.getElementById("operator").value;
    
  min = operatorsMinMax[operator]['min'];
  max = operatorsMinMax[operator]['max'];   
  
  if (tel=='' || operator=='')
    return;
    
  kwota = document.getElementById('kwota').value;
  if (kwota=='i') {
    kwota = document.getElementById('ikwota').value;
  }
  if (kwota=='')
    return;
  
  if (parseInt(kwota)<parseInt(min) || parseInt(kwota)>parseInt(max)){    
    return;
  }
    
  checked = true;
  requestProcessing = true;
  var callback = { 
    success : function(o) {  
       //alert(o.responseText);
       
       tab = o.responseText.split('_');                          
       if (tab[0] && tab[0]==0){
         if (submitForm){
            form.submit();
         }
         validNumber = true;                  
       }
       else
       {         
         error = tab[1]?tab[1]:"błąd sprawdzania numeru";
         lastError = error;
         showAlerts(lastError,'');
       }          
       requestProcessing = false;
       hideWait();
    }, 
    failure : function(o) {   
      requestProcessing = false;
      lastError = 'Błąd sprawdzania numeru';
      showAlerts('Błąd sprawdzania numeru','');
      hideWait();
    } 
   } 
     
        
  // Connect to our data source and load the data
  conn = YAHOO.util.Connect.asyncRequest("GET", "/ajax/checkNumber?operator="+operator+"&phone="+tel+"&amount="+kwota, callback);

}

function validateSumbit(f){	
	
	showAlerts('','');
	tel = document.getElementById("telefon");
	tel2 = document.getElementById("telefon2");
	email = document.getElementById("email");
	operator = document.getElementById("operator").value;

//  if (operator== 2 || operator==3 || operator==38 || operator==39){  
//    showAlerts('Doładowania dla wybranego operatora są w tej chwili niedostępne');  
//    return false;
 // }

	if (operator==0){
		showAlerts("Proszę wybrać operatora", "operator");
		return false;	
	}		
	
	if (tel.value==''){
		showAlerts("Proszę podać nr telefonu", "phone");
		return false;
	}	
	
	if (tel2.value!=tel.value){
		showAlerts("Numer telefonu niepoprawnie powtórzony","repeatPhone");
		return false;
	}
	
	if (!isEmail(email.value)){
		showAlerts("Niepoprawny adres email","email");
		return false;	
	}

  
  if (!price_validate()){
    return false;
  }  
  

  
  if (validNumber && !requestProcessing){
    return true;
  }
  else if (requestProcessing)
  {
    //alert(2);
    submitForm = true;
    showWait();        
    return false;
  }
  else{
    //alert(3);
    submitForm = true;
    showWait();
    checkPhoneNumber(f);    
    return false;
  }  
}


//messages
var errors = {
  '2': "Aktualnie doładowania bezpośrednie dostępne są wyłącznie dla sieci: Orange Go/POP, Simplus, Sami Swoi, Tak Tak oraz Heyah.",
  '3': "Proszę czekać Trwa weryfikacja podanego numeru telefonu przez operatora.",
  '4': "Proszę zmienić numer telefonu.",
  '5': "Podany numer jest nieprawidłowy.",
  '6': "Numer telefonu nieprawidłowo powtórzony.",
  '7': "Niepoprawny format numeru telefonu.",
  '8': "Kwota zasilenia musi być przedziału |x| zł-|y| zł",
  '11': "Niepoprawny format adresu e-mail.",
  '12': "Przepraszamy. Doładowania w sieci Orange Go/POP chwilowo niedostępne.",
  '13': "Proszę podać adres e-mail.",
  '16': "Proszę wybrać operatora"
}


//create select of prices
function CreateSelect(ind) {
	var kwota = document.getElementById("kwota");
	kwota.length=0;
  //schowaj kwote inna  
	
	selected=0;
	
	counter = 0;
	for (i in operatorsPrices[ind]) { 
		kwota[counter] = new Option(operatorsPrices[ind][i]['desc'], operatorsPrices[ind][i]['price']);
		if (operatorsPrices[ind][i]['price']==operatorsDefaults[ind]){
		  selected = counter;
		} 
		counter++;   
	}
	kwota.selectedIndex = selected;
}

function ChangeOperator(ind) {
  YAHOO.util.Connect.abort(con, callback);
  validNumber = false;
  requestProcessing = false;
  submitForm = false;
  checked = false;
  showAlerts('','');
  //if (ind== 2 || ind==3 || ind==38 || ind==39)  
    //showAlerts('Doładowania dla wybranego operatora są w tej chwili niedostępne');
  
   
  CreateSelect(ind);
	var tel = document.getElementById("telefon");
	var tel2 = document.getElementById("telefon2");
	
	var kwota = document.getElementById("kwota");
  label1 = document.getElementById("telefon1Label");
  label2 = document.getElementById("telefon2Label");
  span1 = document.getElementById("telefon1Span");
  span2 = document.getElementById("telefon2Span");  

  Zmien_Kwota(kwota);
  if (ind==1){
    if (span1!=null)
    	span1.style.display = "none";
    if (span2!=null)
    	span2.style.display = "none";
    if (label1!=null)
    	label1.innerHTML = "Numer konta GG do zasilenia:";
    if (label2!=null)
    	label2.innerHTML = "Powtórz numer konta GG:";
    tel.setAttribute('maxlength',10);
    tel2.setAttribute('maxlength',10);
  }
  else
  {
	if (span1!=null)
		span1.style.display = "block";
	if (span2!=null)
		span2.style.display = "block";
    if (label1!=null)
    	label1.innerHTML = "Numer telefonu do zasilenia:<span id='telinfo' class='infoMsg'>9 cyfr, bez spacji</span>";
    if (label2!=null)
    	label2.innerHTML = "Powtórz numer telefonu:";
    tel.setAttribute('maxlength',9);
    tel2.setAttribute('maxlength',9);    
  }

  tel.value = '';
  tel2.value = '';
  
  return true;
}

//prepare number to search
function CheckOperator() {
	var operator_ind = document.getElementById("operator").value;
	
	if (operator_ind == '0') {
    showErrors(errors[16]);
    return false;
  }
  
  return true;
}


//only digits are available
function OnlyDigits(V, e) {
	var key;
	var keychar;
  
	if (window.event) key = window.event.keyCode;
	else 
		if (e) key = e.which;
		else return true;
		
		keychar = String.fromCharCode(key);

		// control keys
		if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) return true;

		// numbers
		else 
			if ((("0123456789").indexOf(keychar) > -1)) return true;
			else return false;
}

//set payback points
function PodstawPunkty(kwota) {
  var operator_ind = document.getElementById("operator").value;
  
  divisor = (operatorsPoints[operator_ind]) ? operatorsPoints[operator_ind] : 0;
  if (divisor==0)
    return 0;
    
  obj = document.getElementById("punkty");
   obj1 = document.getElementById("punkty2");
  if (obj!=null)
    obj.innerHTML = Math.round(kwota/divisor);
  if (obj1!=null)
    obj1.value = Math.round(kwota/divisor);  
}

//show additional input (DIV) for any price if needed	
function Zmien_Kwota(obj) {

	var ikwota = document.getElementById("ikwota");
	var kwota = document.getElementById("kwota");
  var punkty = document.getElementById("punkty"); 
  var punkty2= document.getElementById("punkty2"); 
  
  if (obj.value!='i') {

    PodstawPunkty(obj.value);
    if (ikwota) {
      ikwota.value="";
      ikwota = document.getElementById("inna").style.display = 'none';
    }
  }else {
    ikwota.value="";
    if (punkty!=null)
      punkty.innerHTML=0;
    if (punkty2!=null)
      punkty2.value=0;
    ikwota = document.getElementById("inna").style.display = '';
    ikwota.value="";
  }
}

//check price range
function price_validate() {
  var operator_ind = document.getElementById("operator").value;
  min = operatorsMinMax[operator_ind]['min'];
  max = operatorsMinMax[operator_ind]['max'];
  
  kwota = document.getElementById('kwota').value;
  if (kwota=='i') {
    kwota = document.getElementById('ikwota').value;
  }
  
  if (parseInt(kwota)<parseInt(min) || parseInt(kwota)>parseInt(max)){    
    error = errors[8];
    error = error.replace('|x|', min);
    error = error.replace('|y|', max);

    showAlerts(error, document.getElementById('kwota').value=='i'?'amount2':'amount');
    return false;
  } 
	return true;
}

$(document).ready(function(){
	$("#pgOperatorsHeader li").each(function(i) {
		$(this).click( function(){		  			
      $("#pgContent").animate({ backgroundColor: $(this).css("color") }, "normal" );
			$("#operator option").eq(i+1).attr("selected", "selected");
			ChangeOperator(document.getElementById('operator').value);
		});
	});
	$("#operator").change( function(){
    var i = (this).selectedIndex;
    if( i!= 0 && this.value!=1) var color = $("#pgOperatorsHeader li").eq(i-1).css("color");
		else if (this.value==1) var color = "#ffcc00";
    else var color = "#eee";
		$("#pgContent").animate({ backgroundColor: color }, "normal" );
	});


	$("#staticList dd").hide();
	$("#staticList dt").click( function(){
		$(this).next().toggle().siblings("dd").hide();
		document.location.hash=$(this).attr("id");
	});
	if(hash=document.location.hash) $("#staticList "+hash).next().show();

	$('[@rel="external"]').attr({target: "_blank"});
});


