var PLACES_COUNT = 20;
var LIMIT_PLACES = false;
Event.observe(window, 'load', function() {
     if (navigator.appVersion.indexOf("MSIE") == -1){
		Event.observe(document, 'keypress', function(event){
			if(event.keyCode == 13 && event.target.id !='LOCATION_INPUT') {
				$('pib-submit-btn').click();
				return false;

			}
		});
	}

	pibresultDiv = $('pib_result_div');
	if(pibresultDiv) {
	    pibresultDiv.show();
    }
	locationInput = $('LOCATION_INPUT');
    if(locationInput) {
    	locationInput.observe('keyup',function(event){
	    	rewriteLocation();
		});
    	locationInput.observe('blur',function(event){
	    	rewriteLocation();
		});
    	locationInput.observe('click',function(event){
	    	clearLocation();
		});
    }

    byPhraseMiddle = $('by-phrase-middle');
    if(byPhraseMiddle) {
    	byPhraseMiddle.observe('click',function(event){
	    	toggleRadioButton('filterClickA','/templates/skins/pekao2');
		});
    }
    byCityMiddle = $('by-city-middle');
    if(byCityMiddle) {
    	byCityMiddle.observe('click',function(event){
	    	toggleRadioButton('filterClickB','/templates/skins/pekao2');
		});
    }

    provId = $('PROVINCES_ID');
    if(provId) {
        AMG.CustomForms.replaceSelects(provId, {onChange:function(sourceElement, el){ updateListOfCities();}});
    }
    citiesId = $('CITIES_ID');
    if(citiesId) {
        AMG.CustomForms.replaceSelects(citiesId);
    }
    selectedCityId = $('SELECTED_CITY');
    if(selectedCityId && provId.getValue()!='') {
    	updateListOfCities(selectedCityId.value);
    }

    pc = $('PLACES_COUNT');
    if(pc) {
    	if(pc.getValue() == "true") {
    		PLACES_COUNT = 20;
    		LIMIT_PLACES = true;
    	} else {
        	PLACES_COUNT = pc.getValue();
    	}
    }


});

//function manageHours() {
	//$$('.show-other-hours').each(function(el){
	//	hideOtherHours(el);
	//});
//	$$('.show-other-hours').each(function(el){
//		el.observe('click',function(event){showOtherHours(this);});
//	});
//	$$('.hide-other-hours').each(function(el){
//		el.observe('click',function(event){hideOtherHours(this);});
//	});
//}

function hideOtherHours(elem) {
    $(elem).up().up().select('.all').each(function(el) {el.hide()});
    $(elem).up().up().select('.current').each(function(el) {el.show()});
    $(elem).up().select('.hide-other-hours').each(function(el) {el.hide()});
    $(elem).up().select('.show-other-hours').each(function(el) {el.show()});
}
function showOtherHours(elem) {
	$(elem).up().up().select('.all').each(function(el) {el.show()});
	$(elem).up().up().select('.current').each(function(el) {el.hide()});
	$(elem).up().select('.hide-other-hours').each(function(el) {el.show()});
	$(elem).up().select('.show-other-hours').each(function(el) {el.hide()});
}

function hidePibDetailsLinks(el) {
	$(el).up().up().select('.details').each(function(ul) {
		ul.hide();
	});
	var link = $(el).up().select('.show-details')[0];
	$(el).hide();
	link.show();
}
function showPibDetailsLinks(el) {
	$(el).up().up().select('.details').each(function(ul) {
		ul.show();
	});
	var link = $(el).up().select('.hide-details')[0];
	$(el).hide();
	link.show();
}
function hideShowLinks() {}

function checkForm() {
  if($('BY_CITY_S_TYPE').checked) {
    var prov = $('PROVINCES_ID');
    var city = $('CITIES_ID');
    if(!prov || !prov.getValue() || !prov.getValue().length>0) {
    	$$('#PROVINCES_ID_empty').invoke('show');
    	return false;
    }
    $$('.empty').invoke('hide');
    if(!city || !city.getValue() || !city.getValue().length>0) {
    	$$('#CITIES_ID_empty').invoke('show');
    	return false;
    }
    $$('.empty').invoke('hide');
  } else {
	  var loc = $('LOCATION_VALUE');
	  var locInput = $('LOCATION_INPUT');
	  if(loc) {
		  if(locInput && (!loc.getValue() || loc.getValue().length<1)) {
			  rewriteLocation();
		  }
		  if(!loc.getValue() || !loc.getValue().length>0 || !locInput || !locInput.getValue() || !locInput.getValue().length>0) {
			  loc.up().select('.empty').invoke('show');
			  return false;
		  }
      } else {
    	  return false;
      }
  }
  return true;
}

function clearCoords() {
	$('COORDS_LAT_ID').setValue("");
	$('COORDS_LNG_ID').setValue("");
	$('COORDS_FADDRESS_ID').setValue("");
}
function submitSearchBtn() {
	clearCoords();
	return submitSearch();
}
function submitSearch() {
	if($('BY_CITY_S_TYPE').checked) {
		submitWithCoords();
	} else {
		var locInp = $('LOCATION_INPUT');
		var address = locInp.getValue();
		var hintSearch = $('hint-search');
		var hintSearchBottom = $('hint-search-bottom');
		var PL = ', Polska';
		var EN = ', Poland';
		hintSearch.hide();
		hintSearchBottom.hide();
		$$('#hint-search li.coords-item').each(function(e){e.remove()});
		$$('.empty').invoke('hide');

		if(checkCoords()) {
			return submitWithCoords();
		} else {
			geocoder.geocode( { 'address': address + PL, 'region':'pl'}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					if(results.length > 1) {
						var stringResults = '';
						for(i=0; i<results.length; i++) {
							var prov = '';
							var isProv = false;
							addrComp = results[i].address_components;
							for(j=0; j<addrComp.length && !isProv; j++) {
								types = addrComp[j].types;
								for(k=0; k<types.length && !isProv; k++) {
									if(types[k] == "administrative_area_level_1") {
										prov = " ("+addrComp[j].long_name.toLowerCase()+")";
										isProv = true;
									}
								}
							}
							addr = results[i].formatted_address;
							addr = addr.replace(PL, '');
							addr = addr.replace(EN, '');
							stringResults+=('<li class="coords-item"><span onclick="selectedCoords('+results[i].geometry.location.lat()+','+results[i].geometry.location.lng()+',\''+addr+'\');">'+addr+prov+'</span></li>');
						}
						hintSearch.insert(stringResults);
						hintSearch.show();
						hintSearchBottom.show();

					} else if(results.length == 0) {
						return submitWithCoords();
					} else {
						addr = results[0].formatted_address;
						addr = addr.replace(PL, '');
						addr = addr.replace(EN, '');
						return selectedCoords(results[0].geometry.location.lat(), results[0].geometry.location.lng(), addr)
					}
				} else {
					//return false;
					return submitWithCoords();
				}
			});
		}
	}
	return false;
}

function submitWithCoords() {
	if(!checkForm()) {
		return false;
	} else {
		$('pib-search-form').submit();
		return true;
	}
}

function clearLocation() {
	var locInp = $('LOCATION_INPUT');
	var locVal = $('LOCATION_VALUE');
	if(!locVal || !locInp || !locVal.getValue() || !locVal.getValue().length>0) {
        locInp.setValue("");
    }
}
function rewriteLocation() {
	var locInp = $('LOCATION_INPUT');
	var locVal = $('LOCATION_VALUE');

    if(!locVal || !locInp || !locInp.getValue()) {
        return false;
    }
    locVal.value = locInp.getValue();
}

function checkCoords() {
	lat = $('COORDS_LAT_ID').getValue();
	lng = $('COORDS_LNG_ID').getValue();
	//address $('COORDS_FADDRESS_ID').getValue();
    if(lat && lat.length > 0 && lng && lng.length > 0) {
    	return true;
    }
    return false;
}

function selectedCoords(lat, lng, address) {
	$('COORDS_LAT_ID').setValue(lat);
	$('COORDS_LNG_ID').setValue(lng);
	$('COORDS_FADDRESS_ID').setValue(address);
	return submitWithCoords();
}

function printPIB(printPath, paramName, branchId, contextId) {
	window.open(printPath+'?r,main,printType=PIB&'+paramName+'='+branchId+'&r,main,docId='+contextId,'_blank','menubar=no, toolbar=no, location=no, scrollbars=yes, status=no, height=600, width=800, resizable=0')
}

function printCashpoint(printPath, cashpointId, contextId) {
	window.open(printPath+'?r,main,printType=PIB&r,main,cId='+cashpointId+'&r,main,docId='+contextId,'_blank','menubar=no, toolbar=no, location=no, scrollbars=yes, status=no, height=600, width=800, resizable=0')
}


/* przełącza customowe checkboxy w formularzu wyszukiwania placowek i bankomatow */
toggleCheckBox = function(imageId, skin) {
	var icon = document.getElementById(imageId);
	var filter = imageId+"Info";
	if (icon.src.indexOf('checkbox_small_off.gif') > 0) {
		icon.src = skin + '/img/pib/checkbox_small_on.gif';
		$(filter).setValue('on');
	} else {
		icon.src = skin + '/img/pib/checkbox_small_off.gif';
		$(filter).setValue('off');
	}
}

/* przełącza customowe radiobuttony w formularzu wyszukiwania placowek i bankomatow */
toggleRadioButton = function(imageId, skin) {
	var icon = document.getElementById(imageId);
	var iconA = document.getElementById("filterClickA");
	var iconB = document.getElementById("filterClickB");
	iconA.src = skin + '/img/pib/radio_button_off.gif';
	iconB.src = skin + '/img/pib/radio_button_off.gif';

	if( imageId == "filterClickA" ){
		icon.src = skin + '/img/pib/radio_button_on.gif';
		$('BY_PHRASE_S_TYPE').checked='checked';
		$('by-phrase-top').removeClassName('box-radio-top-clear').addClassName('box-radio-top');
		$('by-phrase-middle').removeClassName('box-radio-middle-clear').addClassName('box-radio-middle');
		$('by-phrase-bottom').removeClassName('box-radio-bottom-clear').addClassName('box-radio-bottom');
		$('by-city-top').removeClassName('box-radio-top').addClassName('box-radio-top-clear');
		$('by-city-middle').removeClassName('box-radio-middle').addClassName('box-radio-middle-clear');
		$('by-city-bottom').removeClassName('box-radio-bottom').addClassName('box-radio-bottom-clear');
	}
	if( imageId == "filterClickB" ){
		icon.src = skin + '/img/pib/radio_button_on.gif';
		$('BY_CITY_S_TYPE').checked='checked';
		$('by-phrase-top').addClassName('box-radio-top-clear').removeClassName('box-radio-top');
		$('by-phrase-middle').addClassName('box-radio-middle-clear').removeClassName('box-radio-middle');
		$('by-phrase-bottom').addClassName('box-radio-bottom-clear').removeClassName('box-radio-bottom');
		$('by-city-top').removeClassName('box-radio-top-clear').addClassName('box-radio-top');
		$('by-city-middle').removeClassName('box-radio-middle-clear').addClassName('box-radio-middle');
		$('by-city-bottom').removeClassName('box-radio-bottom-clear').addClassName('box-radio-bottom');

	}
}

toggleCheckBoxAndSubmit = function(imageId, skin) {
	toggleCheckBox(imageId, skin);
	submitSearch();
}

function checkBranchForm() {
    var prov = $('PROVINCES_ID');
    var city = $('CITIES_ID');
    if(!prov || !prov.getValue() || !prov.getValue().length>0) {
        prov.up().select('.empty').invoke('show');
        return false;
    }
    if(!city || !city.getValue() || !city.getValue().length>0) {
        city.up().select('.empty').invoke('show');
        return false;
    }
    $$('.empty').invoke('hide');
    return true;
}

function getSelectedProvince(selectFieldId){
    var selectField = document.getElementById(selectFieldId);
    return selectField.value;
}

function updateListOfCities(city) {
	var type = $('PIB_TAB_TYPE').getValue();
    var province = $('PROVINCES_ID').getValue();
  //  alert(province);
    //var pname = 'PIBCitiesResp';

    new Ajax.Updater('CITIES_ID', '/htmlresp?app=Pekao2&pname=PIBCitiesResp',
        {
    	//&r,main,province='+province+'&r,main,city='+city+'&r,main,type='+type+'&ts='+new Date().getTime()
            method: 'get',
          //  encoding: 'UTF-8',
            parameters: {'r,main,province': province,'r,main,city':city, 'r,main,type':type, 'ts':new Date().getTime()},
            onComplete: function(transport){
               var response = transport.responseText || "no response text";
               document.getElementById('CITIES_ID').innerHtml = response;
               AMG.CustomForms.Controls.removeSelect('CITIES_ID');
               AMG.CustomForms.replaceSelects($('CITIES_ID'));
            }
        }
    );
}


